having Problem with adding menu to an app - android-studio

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...

Related

About menu crash after press it

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.

What can I change in buttonadd in the section I think there is a problem

package com.example.gymmanagment;
import static com.example.gymmanagment.Trainignactivity2.Training_key;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
public class plandetailsdialogue extends DialogFragment {
private Button buttondismiss,butoonadd;
private TextView txtname;
private EditText edittextmintues;
private Spinner spinnerdayy;
public interface passplaninteface{
void getplan(plan plan);
}
private passplaninteface passplaninteface;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
View
view=getActivity().getLayoutInflater().inflate(R.layout.dialoguedetails,null);
intiviews(view);
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle("enter details");
Bundle bundle=getArguments();
if(null !=bundle){ Training training=bundle.getParcelable(Training_key);
if(null!=training){
txtname.setText(training.getName());
buttondismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
butoonadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String day=spinnerdayy.getSelectedItem().toString();
int
minitues=Integer.valueOf(edittextmintues.getText().toString());
plan plan=new plan(training,minitues,day,false);
try {
passplaninteface=(passplaninteface) getActivity();
passplaninteface.getplan(plan);
dismiss();
}catch (ClassCastException e){
e.printStackTrace();
dismiss();
}}
});
}
}
return builder.create();
}
private void intiviews(View view){
buttondismiss= view.findViewById(R.id.buttondissmiss);
butoonadd= view.findViewById(R.id.onlyadd);
txtname= view.findViewById(R.id.txtname234);
edittextmintues= view.findViewById(R.id.edttxtminutes);
spinnerdayy= view.findViewById(R.id.spinnerdays);
}
}
The error is below:
022-01-29 13:20:54.963 8688-8688/com.example.gymmanagment E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.gymmanagment, PID: 8688
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.valueOf(Integer.java:801)
at
com.example.gymmanagment.plandetailsdialogue$2.onClick(plandetailsdialogue.java:52)
at android.view.View.performClick(View.java:7448)
at
com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1131)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Your EditText is probabbly empty. The error shows that input string is: "". You can't assign a value of nothing to an Integer. You should check if EditText isn't empty before casting it to an Integer.
Try something like this:
if(!edittextminutes.getText().toString.isEmpty())
{
//cast to Integer
}

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.

Get Resource with ID from String

My program is supposed to have a listview, which when clicked, displays information for the clicked item. My problem is that I have attached the clicked item's name as an extra of the Intent that starts the new Activity. The information I need to display is stored as a string array. I need to use the string that I receive from the Intent to find the string array and bring it into Java. Can someone help me with this?
Thanks.
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listview = (ListView) findViewById(R.id.stationlist);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
String[] stations = getResources().getStringArray(R.array.stations);
String station_name = stations[position] + "_timings";
Intent intent = new Intent(MainActivity.this, Station_timings.class);
intent.putExtra("stationwithtime", station_name);
intent.putExtra("position", position);
startActivity(intent);
};
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Station_timings.class
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Station_timings extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station_timings);
String station_name = getIntent().getStringExtra("stationwithtime");
int position = getIntent().getIntExtra("position", 0);
TextView tv = (TextView) findViewById(R.id.textview);
Resources res = getResources();
String[] array = getResources().getStringArray(R.array.stations);
tv.setText(station_name);
int arrayid = res.getIdentifier(station_name, "array" , this.getPackageName());
String[] array2 = res.getStringArray(arrayid);
ListView listView = new ListView(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_station_timings, array);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.station_timings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="stations" style="#style/names_of_stations">
<item name="Oceanside">Oceanside Station</item>
<item name="San Clemente">San Clemente Station</item>
<item name="San Juan Capistrano">San Juan Capistrano Station</item>
<item name="Irvine">Irvine Station</item>
<item name="Tustin">Tustin Station</item>
<item name="Santa Ana">Santa Ana Station</item>
<item name="Orange">Orange Station</item>
<item name="Anaheim">Anaheim Station</item>
<item name="Fullerton">Fullerton Station</item>
<item name="Buena Park">Buena Park Station</item>
<item name="Santa Fe Springs/Norwalk">Santa Fe Springs/Norwalk Station</item>
<item name="Commerce">Commerce Station</item>
<item name="Los Angeles">Los Angeles Union Station</item>
</string-array>
<string-array name ="oceanside">
<item name="1"> 5:45 </item>
<item name="2"> 6:30 </item>
</string-array>
<string-array name ="station_timings">
<item name="1"> wrong </item>
<item name="2"> wrong </item>
</string-array>
<string name="title_activity_station_timings">Station_timings</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
In your example, the variable station_name will contain the String "Oceanside Station". You are then calling
res.getIdentifier(station_name, "array" , this.getPackageName());
which will try to get a resource identifier for a string-array with the name "Oceanside Station". You've provided a string-array with the name "oceanside". They don't match.
Another thing you may wish to consider is using a more structured format to store your data, such as a JSON document, an XML document, a CSV file, or similar. You can then read that into your program as actual objects making them much easier to deal with.

Resources