我无法将数据从一个活动传递到另一个活动。在使用Intents和setResult的活动之间传递数据的问题()
我可以很容易地使用startActivityForResult()发送一个intent与原始数据,然后在新的Activity中处理这些数据。然后,我在这个新Activity的onPause()函数中使用setResult()来返回Intent对象中的一些数据。这样做会在原始Activity中调用onActivityResult(),但发送给此函数的Intent始终以null结束,这是错误的。我不明白为什么这个意图对象是null。
这里是首发活动, “测试” 的主要功能:
@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");
}
}
这里是开展活动的主要功能, “翻转”:
@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);
}