I am developing sample a android app having three activities named Stationary, Books and Pens. I want to send data from Books and Pens activities to Stationary activity. In Stationary activity when I receive data from one activity either Books or Pens it works fine but when I receive data from both the activities my app “Stop Unexpectedly”
I have developed some code in this respect you can check it below.
in my Book activity am using the following code.
// in Book Activity
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(myBookSelected)
{
Intent intent = new Intent(Books.this,Stationary.class);
intent.putExtra("bookSelected", books.toString());
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(), "Please select books", Toast.LENGTH_LONG).show();
}
}
return true;
}
and in my Pens Activity am using the flowing code.
// in Pen Activity
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(myPenSelected)
{
Intent intent = new Intent(Pens.this,Stationary.class);
intent.putExtra("penSelected", pens.toString());
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(), "Please select Pens", Toast.LENGTH_LONG).show();
}
}
return true;
}
To receive data in Stationary activity from the above two activities that is Books and Pens. I am using the following code.
// in Stationary Activity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
numberOfBooks = extras.getString("bookSelected");
numberOfPens = extras.getString("penSelected");
}
NOTE: When I receive data from one activity either Books or Pens it works fine but when I receive data from both the activities my app “Stop Unexpectedly”
its because when you try to pass a Intent from your BookActivity your "penSelected" will be null and in the other case "bookSelected" will be null. So obviously you will hit NullPointerException here.
A simply nasty solution will be to surround them in separate try catch blocks. Or you might have to send another data to identify from which Activity you are being passed and based on that get only the required field.
Say for example you come from PenActivty then you could get only "penSelected" and leave the other one and vice versa.
So what you have to understand here is, in neither of the cases your object "extras" wont be null , but only any one of the above key will be null. So you can’t check for null there.
EDIT
i believe it is not true after all. You can check whether the Bundle Oject contains the key or not using the below code,