Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

android - How to pass object to an activity?

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

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

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

When I do come back from FromAccount.java to NewTransferMyOwn.java, then I want to pass a complete object of class Statement

I do write code as

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

I do get error as following on putExtra,

Change to 'getIntExtra'

as I do, there is again casting st to int, what is issue over here, how can I pass Statement object towards back to acitivity?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
     }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...