Android return object as a activity result

大憨熊 提交于 2020-08-18 02:29:53

问题


Is it possible to return object as a activity result from child activity to parent? Just something like:

Intent resultIntent = new Intent(null);
resultIntent.putExtra("STRING_GOES_HERE", myObject);
setResult(resultIntent);
finish();

If it is possible, how should I retrieve myObject in parent activity?

I figured out, that to retrieve data I need to do something like this:

protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    if(requestCode == REQ_CODE_CHILD) {
        MyClass myObject = data.getExtra("STRING_GOES_HERE");
    }
}

Thing is that I get error, that can not resolve method 'getExtra'....


回答1:


You cannot return an object, but you can return an intent containing your objects (provided they are primitive types, Serializable or Parcelable).

In your child activity, the code will be something like:

int resultCode = ...;
Intent resultIntent = new Intent();
resultIntent.putExtra("KEY_GOES_HERE", myObject);
setResult(resultCode, resultIntent);
finish();

In your parent activity you'll need to start the child activity with startActivityForResult:

public final static int REQ_CODE_CHILD = 1;

...
Intent child = new Intent(getPackageName(), "com.something.myapp.ChildActivity");
startActivityForResult(child, REQ_CODE_CHILD);

and then in the onActivityResult, you'll have:

protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    if(requestCode == REQ_CODE_CHILD) {
        MyClass myObject = (MyClass)data.getExtras().getSerializable("KEY_GOES_HERE");
    }

    ...
}

You can read about the methods on the Activity javadoc page.




回答2:


Check out this answer, which explains how to use startActivityForResult and onActivityResult.

This same process can be used for any object that is Serializable or Parcelable. Thus, if myObject is a custom class you've created, you will need to implement one of these interfaces.




回答3:


You can use setResult(int) read the android activity reference , specifically starting activities and getting results.



来源:https://stackoverflow.com/questions/26703691/android-return-object-as-a-activity-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!