I have an activity that has a button that calling a random activity, but I always encounter this error. I'm still learning, so I really have no idea.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
button = (Button) findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(eleven14.class);
activityList.add(fourth10.class);
activityList.add(MainActivity15.class);
activityList.add(MainActivity16.class);
activityList.add(nine15.class);
activityList.add(sixth8.class);
activityList.add(ten14.class);
activityList.add(twelve15.class);
Random generator = new Random();
int number = generator.nextInt(8) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
activity = eleven14.class;
// We are adding the number of the activity to the list
activityList.remove(eleven14.class);
break;
case 2:
activity = fourth10.class;
activityList.remove(fourth10.class);
break;
case 3:
activity = MainActivity16.class;
activityList.remove(MainActivity16.class);
break;
case 4:
activity = nine15.class;
activityList.remove(nine15.class);
break;
case 5:
activity = sixth8.class;
activityList.remove(sixth8.class);
break;
case 6:
activity = ten14.class;
activityList.remove(ten14.class);
break;
case 7:
activity = twelve15.class;
activityList.remove(twelve15.class);
break;
default:
activity = MainActivity15.class;
activityList.remove(MainActivity15.class);
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
// `intent.putExtra(...)` is used to pass on extra information to the next activity
intent.putExtra("LIST_A", activityList);
startActivity(intent);
}
});
I put this to other activity
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("LIST_A");
if (activityList.size() == 0) {
showDialog();
} else {
int r = new Random().nextInt(activityList.size());
Class<? extends Activity> activity = activityList.remove(r);
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("LIST_A", activityList);
startActivity(intent);
}