About menu crash after press it - android-studio

I do not know what error I have. I already put MainActivity between new Intent and this.
This is my mainactivity.java
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.:
Intent intent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
This is menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/about"
android:title="About"
app:showAsAction="never"/>
</menu>
This is AboutActivity.java
package com.example.zakatcalculator;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class AboutActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
textView = findViewById(R.id.textViewLink);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
And this is AndroidManifest.xml
<activity
android:name=".AboutActivity"
android:exported="false">
</activity>
When I press about button, then its crash.

public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.about:
Intent intent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
replace R.id. to this R.id.about and try again.

Related

Broadcast Reciever ACTION_SHUTDOWN Intent is not working in Android version 11

Foreground service class code for calling the shutDown broadcast receiver.
public class SmsForegroundService extends Service{
private BroadcastReceiver receiver;
public static class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// do something
Log.d(TAG, "onReceive: "+intent.getAction());
if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
Log.d(TAG, "onReceive: ScreenOff");
}
}
// constructor
public MyReceiver(){
}
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN);
receiver = new MyReceiver();
this.registerReceiver(receiver,filter);
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy: service destroyed");
super.onDestroy();
this.unregisterReceiver(receiver);
}
//
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG ,"service running");
final String CHANNEL_ID = "foreground Service ID";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH
);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this,CHANNEL_ID)
.setContentText("Service is running")
.setContentTitle("Service is enabled")
.setSmallIcon(R.drawable.ic_launcher_background);
startForeground(1001, notification.build());
}
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return null;
}
}
AndroidManifest file, here I added only the permission for Foreground services, I think there is no other permission is required for action_shutdown in manifest for versions greater than Oreo.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.mywork.smsbroadcast">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.SmsBroadcast">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".SmsForegroundService">
</service>
</application>
</manifest>
MainActivity I have called the service class inside on Create method MainActivity class.
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!foregroundServiceRunning())
{
Intent serviceIntent = new Intent(this, SmsForegroundService.class);
ContextCompat.startForegroundService(this,serviceIntent);
}
}
public boolean foregroundServiceRunning(){
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(ActivityManager.RunningServiceInfo serviceInfo: activityManager.getRunningServices(Integer.MAX_VALUE)){
if(SmsForegroundService.class.getName().equals(serviceInfo.service.getClassName())){
return true;
}
}
return false;
}
}

How to fix Null Pointer Exception error in Java?

My app keeps crashing when I try to log in (after LoginActivity file). Here's the code. I"d really appreciate some help with this.
MainActivity (opens the register/login screen)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText username, password, repassword;
Button signup, signin;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
repassword = (EditText) findViewById(R.id.repassword);
signup = (Button) findViewById(R.id.btnsignup);
signin = (Button) findViewById(R.id.btnsignin);
DB = new DBHelper(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
String repass = repassword.getText().toString();
if(user.equals("")||pass.equals("")||repass.equals(""))
Toast.makeText(MainActivity.this, "Please enter all the fields", Toast.LENGTH_SHORT).show();
else{
if(pass.equals(repass)){
Boolean checkuser = DB.checkusername(user);
if(checkuser==false){
Boolean insert = DB.insertData(user, pass);
if(insert==true){
Toast.makeText(MainActivity.this, "Registered successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(MainActivity.this, "User already exists! please sign in", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Passwords not matching", Toast.LENGTH_SHORT).show();
}
} }
});
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}
}
LoginActivity (once registered then proceed to login)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button btnlogin;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username1);
password = (EditText) findViewById(R.id.password1);
btnlogin = (Button) findViewById(R.id.btnsignin1);
DB = new DBHelper(this);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
if(user.equals("")||pass.equals(""))
Toast.makeText(LoginActivity.this, "Please enter all the fields", Toast.LENGTH_SHORT).show();
else{
Boolean checkuserpass = DB.checkusernamepassword(user, pass);
if(checkuserpass==true){
Log.d("mytag","1");
Toast.makeText(LoginActivity.this, "Sign in successfull", Toast.LENGTH_SHORT).show();
Log.d("mytag","2");
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Log.d("mytag","3");
startActivity(intent);
}else{
Toast.makeText(LoginActivity.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
HomeActivity (this should open the main screen of the app. The app has a add button which adds items using recyclerview)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class HomeActivity extends Activity {
RecyclerView recyclerView;
FloatingActionButton add_button;
ImageView empty_imageview;
TextView no_data;
MyDatabaseHelper myDB;
ArrayList<String> book_id, book_title, book_author, book_pages;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
empty_imageview = findViewById(R.id.empty_imageview);
no_data = findViewById(R.id.no_data);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this, AddActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(HomeActivity.this);
book_id = new ArrayList<>();
book_title = new ArrayList<>();
book_author = new ArrayList<>();
book_pages = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(HomeActivity.this,this, book_id, book_title, book_author,
book_pages);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
recreate();
}
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
empty_imageview.setVisibility(View.VISIBLE);
no_data.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
book_id.add(cursor.getString(0));
book_title.add(cursor.getString(1));
book_author.add(cursor.getString(2));
book_pages.add(cursor.getString(3));
}
empty_imageview.setVisibility(View.GONE);
no_data.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.delete_all){
confirmDialog();
}
return super.onOptionsItemSelected(item);
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete All?");
builder.setMessage("Are you sure you want to delete all Data?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(HomeActivity.this);
myDB.deleteAllData();
//Refresh Activity
Intent intent = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jovanovic.stefan.sqlitetutorial">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".UpdateActivity"
android:parentActivityName=".HomeActivity"/>
<activity android:name=".HomeActivity"
android:label="GDSC Items App"/>
<activity android:name=".LoginActivity"
android:label="GDSC Items App"/>
<activity
android:name=".AddActivity"
android:label="Add Item"
android:parentActivityName=".HomeActivity" />
<activity
android:name=".MainActivity"
android:label="GDSC Items App">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Error log
2022-01-27 20:31:01.505 3354-3354/com.jovanovic.stefan.sqlitetutorial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jovanovic.stefan.sqlitetutorial, PID: 3354
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jovanovic.stefan.sqlitetutorial/com.jovanovic.stefan.sqlitetutorial.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.jovanovic.stefan.sqlitetutorial.HomeActivity.onCreate(HomeActivity.java:45)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
Make sure you setting the correct layout inside the setContentView() method
For example:
setContentView(R.layout.activity_home);

On swiping fragments are changing but bottom navigation icons are not changing in android studio

I created a bottom navigation bar with 3 icons and 3 different fragments linked to them.
On clicking an icon,
1.the icon changes
2. icon color changes
3. that related fragment appears on screen
On swipe,
only that fragment is changing.(icon is not changing).
Menu with 3 icons
<item
android:id="#+id/ic_birthdays"
android:title="#string/birthdays"
android:icon="#drawable/change_ic_cake"
/>
<item
android:id="#+id/ic_add"
android:title="#string/add"
android:icon="#drawable/change_ic_add"
/>
<item
android:id="#+id/ic_profile"
android:title="#string/profile"
android:icon="#drawable/change_ic_profile"
/>
The three icons linked in menu are:
1.Birthdays icon
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/ic_cake_clicked" />
<item android:state_checked="false" android:drawable="#drawable/ic_cake_not_clicked"/>
</selector>
2.Add Icon
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_add_not_clicked" android:state_checked="false"/>
<item android:drawable="#drawable/ic_add_clicked" android:state_checked="true"/>
</selector>
3.Profile icon
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_profile_not_clicked" android:state_checked="false"/>
<item android:drawable="#drawable/ic_profile_clicked" android:state_checked="true"/>
</selector>
MainActivity.java
package com.example.bottom_nav;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.bottom_nav.databinding.ActivityMainBinding;
import com.google.android.material.navigation.NavigationBarView;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding ui;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ui = ActivityMainBinding.inflate(getLayoutInflater());
ViewGroup root = ui.getRoot();
setContentView(root);
//Instantiating 3 fragments
ViewPageAdapter viewPageAdapter = new ViewPageAdapter(this);
ui.viewPager.setAdapter(viewPageAdapter);
//Linking those three fragments to their respective icons of bottom nav bar
ui.bottomNav.setOnItemSelectedListener(
new NavigationBarView.OnItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.ic_birthdays:
ui.viewPager.setCurrentItem(0);
break;
case R.id.ic_add:
ui.viewPager.setCurrentItem(1);
break;
case R.id.ic_profile:
ui.viewPager.setCurrentItem(2);
break;
}
return true;
}
}
);
}
}
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_nav" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_navigation_menu" />
</RelativeLayout>
ViewPageAdapter.java
package com.example.bottom_nav;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.example.bottom_nav.fragments.add;
import com.example.bottom_nav.fragments.birthdays;
import com.example.bottom_nav.fragments.profile;
public class ViewPageAdapter extends FragmentStateAdapter {
public ViewPageAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position){
case 1: return new add();
case 2: return new profile();
default: return new birthdays();
}
}
#Override
public int getItemCount() {
return 3;
}
}
The 3 fragments code
1.birthdays.java
package com.example.bottom_nav.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bottom_nav.R;
public class birthdays extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_birthdays, container, false);
}
}
2.add.java
package com.example.bottom_nav.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bottom_nav.R;
public class add extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add, container, false);
}
}
3.profile.java
package com.example.bottom_nav.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bottom_nav.R;
public class profile extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add, container, false);
}
}
You need to have a listener on viewpager, and keep track of previous item selected,
so create a global variable,
Global variable:
MenuItem previousMenuItem;
then a viewpager listener:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (previousMenuItem != null) {
previousMenuItem.setChecked(false);
}
else {
mBottomNavigationView.getMenu().getItem(0).setChecked(false);
}
mBottomNavigationView.getMenu().getItem(position).setChecked(true);
previousMenuItem = mBottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Don't forget to set a default item (first) to be selected of BottomNav on activity start.

Encrypt Bluetooth Chat

Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}

having Problem with adding menu to an app

I'm trying to add some menus to my app. here is my code:
java code:
package com.example.excercise;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
TextView my_text;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_text=findViewById(R.id.textView);
my_text.setText(new Date().toString());
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random random=new Random();
my_text.setTextColor(Color.rgb(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
}
});
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
return true;
}
});
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "MainActivity: OnResume()", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
main_menu xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Item1"/>
<item android:title="Item2"/>
<item android:title="Item3"/>
<item
android:id="#+id/app_bar_search"
android:icon="#drawable/ic_search_black_24dp"
android:title="Search"
app:actionViewClass="android.widget.SearchView"/>
<item android:title="Item4">
<menu>
<item android:title="SubItem1"
android:onClick="itemClick"/>
<item android:title="SubItem2"/>
</menu>
</item>
I'm getting this message in red in logcat :
2019-07-14 02:49:18.148 6160-6160/com.example.excercise
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.excercise, PID: 6160
android.view.InflateException: Couldn't resolve menu item onClick handler itemClick in class com.example.excercise.MainActivity
at androidx.appcompat.view.SupportMenuInflater$InflatedOnMenuItemClickListener.(SupportMenuInflater.java:254)
at androidx.appcompat.view.SupportMenuInflater$MenuState.setItem(SupportMenuInflater.java:482)
at androidx.appcompat.view.SupportMenuInflater$MenuState.addItem(SupportMenuInflater.java:530)
at androidx.appcompat.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:206)
at androidx.appcompat.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:184)
at androidx.appcompat.view.SupportMenuInflater.inflate(SupportMenuInflater.java:128)
at com.example.excercise.MainActivity.onCreateOptionsMenu(MainActivity.java:69)
at android.app.Activity.onCreatePanelMenu(Activity.java:4055)
at androidx.fragment.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:378)
at androidx.appcompat.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:94)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.onCreatePanelMenu(AppCompatDelegateImpl.java:2549)
at androidx.appcompat.app.AppCompatDelegateImpl.preparePanel(AppCompatDelegateImpl.java:1589)
at androidx.appcompat.app.AppCompatDelegateImpl.doInvalidatePanelMenu(AppCompatDelegateImpl.java:1869)
at androidx.appcompat.app.AppCompatDelegateImpl$2.run(AppCompatDelegateImpl.java:230)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NoSuchMethodException: com.example.excercise.MainActivity.itemClick [interface
android.view.MenuItem]
at java.lang.Class.getMethod(Class.java:2072)
at java.lang.Class.getMethod(Class.java:1693)
at androidx.appcompat.view.SupportMenuInflater$InflatedOnMenuItemClickListener.(SupportMenuInflater.java:250)
at androidx.appcompat.view.SupportMenuInflater$MenuState.setItem(SupportMenuInflater.java:482)
at androidx.appcompat.view.SupportMenuInflater$MenuState.addItem(SupportMenuInflater.java:530)
at androidx.appcompat.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:206)
at androidx.appcompat.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:184)
at androidx.appcompat.view.SupportMenuInflater.inflate(SupportMenuInflater.java:128)
at com.example.excercise.MainActivity.onCreateOptionsMenu(MainActivity.java:69)
at android.app.Activity.onCreatePanelMenu(Activity.java:4055)
at androidx.fragment.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:378)
at androidx.appcompat.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:94)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.onCreatePanelMenu(AppCompatDelegateImpl.java:2549)
at androidx.appcompat.app.AppCompatDelegateImpl.preparePanel(AppCompatDelegateImpl.java:1589)
at androidx.appcompat.app.AppCompatDelegateImpl.doInvalidatePanelMenu(AppCompatDelegateImpl.java:1869)
at androidx.appcompat.app.AppCompatDelegateImpl$2.run(AppCompatDelegateImpl.java:230)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
what is the problem and how should I fix it? I should add that in all java classes that red message refer me to, I get the "cannot resolve R symbol" error.
In your main_menu.xml add an id to the item element
<?xml version="1.0" encoding="utf-8"?>
<item android id="#+id/item1"
android:title="Item1"/>
<item android id="#+id/item2"
android:title="Item2"/>
<item android id="#+id/item3"
android:title="Item3"/>
In your MainActivity.java add onOptionsItemSelected method
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
//respond to menu item selection
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "You clicked on item 1", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "You clicked on item 1", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Finally to solve the cannot resolve R symbol error...You have not imported the R class into your java file.There are two steps to do that
Step One
Click on the R symbol you should see a red bulb...click on that red bulb...you'd see a popup showing import class...Click on import
Or Step Two
Click on the R symbol...Then Press Alt + Enter
I hope this helps...

Resources