I am having trouble passing data from one activity to another.
I can easily use startActivityForResult() to send an intent with the original data and then manipulate this data in the new Activity. I then use setResult() in the onPause() function of this new Activity to return some data in the Intent object. Doing this calls onActivityResult() in the original Activity, but the Intent sent to this function always ends up null, which is wrong. I don't understand why this Intent object is null.
Here are the main functions of the starting Activity, "Test":
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// add some data to play with
string_array_list.add("item1");
string_array_list.add("item2");
string_array_list.add("item3");
Button start_button = (Button) findViewById(R.id.button);
start_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// start an activity to reverse the order of items in the list
startFlip();
}
});
}
private void startFlip() {
// using a bundle isn't absolutely necessary,
// but useful in the real program
Intent i = new Intent(this, Flip.class);
Bundle extras = new Bundle();
extras.putStringArrayList(STRING_ARRAY_LIST, string_array_list);
i.putExtras(extras);
startActivityForResult(i, FLIP_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
string_array_list.clear();
switch(requestCode) {
case FLIP_REQUEST_CODE:
if(data != null) { // RIGHT ANSWER
Bundle extras = data.getExtras();
string_array_list = extras.getStringArrayList(STRING_ARRAY_LIST);
}
// WRONG ANSWER, but the only answer I get
else Log.d(TAG, "data is null");
}
}
And here are the main functions of the launched Activity, "Flip":
@Override
public void onCreate(Bundle joy) {
super.onCreate(joy);
// retrieve the data from intent (or bundle)
Intent i = getIntent();
Bundle extras = i.getExtras();
if(joy != null) oldList = joy.getStringArrayList(Test.STRING_ARRAY_LIST);
else oldList = extras.getStringArrayList(Test.STRING_ARRAY_LIST);
// reverse the list order
for(int x = oldList.size() - 1; x >= 0; --x)
newList.add(oldList.get(x));
}
@Override
public void onPause() {
super.onPause();
Intent data = new Intent(this, Test.class);
Bundle extras = new Bundle();
extras.putStringArrayList(Test.STRING_ARRAY_LIST, newList);
data.putExtras(extras);
setResult(Test.FLIP_REQUEST_CODE, data);
}