How to transfer an activity object?

I have two actions: NewTransferMyOwn.java and FromAccount.java

When I switch from NewTransferMyOwn.java to FromAccount.java, I write the code as follows

Intent i = new Intent(NewTransferMyOwn.this, FromAccount.class); startActivityForResult(i, FROM_ACCOUNT); 

When I return from FromAccount.java to NewTransferMyOwn.java, I want to pass the complete object of the Statement class

I write code like

 Statement st = ItemArray.get(arg2);//ItemArray is ArrayList<Statement>, arg2 is int Intent intent = new Intent(FromAccount.this,NewTransferMyOwn.class).putExtra("myCustomerObj",st); 

I get an error as shown on putExtra,

Change to 'getIntExtra'

like me, st to int is called again, which is the problem, how can I pass the Statement object back to acitivity?

+4
source share
2 answers

You can also implement your own Serializable class and pass a custom object

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

And then pass the custom object with the intent.

 intent.putExtra("myobj",customObj); 

To get an object

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

UPDATE:

To pass your custom object to the previous action while using startActivityForResult

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

To get a custom object in the previous step

 if(requestCode == MyRequestCode){ if(resultCode == Activity.RESULT_OK){ Custom custom = (Custom) data.getSerializableExtra("myobj"); Log.d("My data", custom.getName()) ; finish(); } } 
+7
source

You cannot pass arbitrary objects between actions. The only data that you can pass as optional / bundled 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 transferring only the URI that refers to the content and reusing it in another action.

+2
source

Source: https://habr.com/ru/post/1388706/


All Articles