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
156 views
in Technique[技术] by (71.8m points)

How can I pass values between Activities on Android?

This is the navigation of my application:

Activity1 calls Activity2Activity2.finish(), call Activity3Activity3.finish()

When Activity3 finishes, it calls the onResume method of Activity1. Now how can I pass a value from Activity3 to Activity1?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Umesh shows a good technique but I think you want the opposite direction.

Step 1

When starting Activity 2 and 3, use startActivityForResult. This allows you handle the result in the calling activity.

startActivityForResult(MY_REQUEST_ID);

Step 2

In Activities 2 and 3, call setResult(int, Intent) to return a value:

Intent resultData = new Intent();
resultData.putExtra("valueName", "valueData");
setResult(Activity.RESULT_OK, resultData);
finish();

Step 3

In your calling activty, implement onActivityResult and get the data:

protected void onActivityResult(int requestCode, int resultCode,
          Intent data) {
      if (requestCode == MY_REQUEST_ID) {
          if (resultCode == RESULT_OK) {
            String myValue = data.getStringExtra("valueName"); 
            // use 'myValue' return value here
          }
      }
}

Edit:

Technique #2

Yes, you can also use global application state by adding a class to your application that extends Application, see this StackOverflow answer


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

...