How to pass object to an activity?

前端 未结 2 1187
既然无缘
既然无缘 2020-12-11 20:52

I have two activities, NewTransferMyOwn.java and FromAccount.java

When I go from NewTransferMyOwn.java to FromAccount.java, I do write code as following

<         


        
相关标签:
2条回答
  • 2020-12-11 21:29

    You can't pass arbitrary objects between activities. The only data you can pass as extras/in a bundle are either fundamental types or Parcelable objects.

    And Parcelables are basically objects that can be serialized/deserialized to/from a string.

    You can also consider passing only the URI refering to the content and re-fetching it in the other activity.

    0 讨论(0)
  • 2020-12-11 21:35

    You can also implement your custom class by Serializable and pass the custom Object,

    public class MyCustomClass implements Serializable
    {
      // getter and setters
    }
    

    And then pass the Custom Object with the Intent.

    intent.putExtra("myobj",customObj);
    

    To retrieve your Object

    Custom custom = (Custom) data.getSerializableExtra("myobj");
    

    UPDATE:

    To pass your custom Object to the previous Activity while you are using startActivityForResult

    Intent data = new Intent();
    Custom value = new Custom();
    value.setName("StackOverflow");
    data.putExtra("myobj", value);
    setResult(Activity.RESULT_OK, data);
    finish();
    

    To retrieve the custom Object on the Previous Activity

    if(requestCode == MyRequestCode){
         if(resultCode == Activity.RESULT_OK){
             Custom custom = (Custom) data.getSerializableExtra("myobj");
             Log.d("My data", custom.getName()) ;
             finish();
         }
     }
    
    0 讨论(0)
提交回复
热议问题