The problem of transmitting value between Android activities

Source: Internet
Author: User

1. Pass data to the next activity

The intent provides a series of overloads of the Putextra () method that can temporarily present the data we want to pass in intent, starting an activity and simply removing the data from the intent. To do a simple demo demo:

Create a new project Mydatatrans and create a new class Second.java and layout second.xml in your project.

Modify the layout in Activity_main.xml (TextView is used to get values from the previous activity):

<LinearLayout Android:id="@+id/lin1"Android:layout_width="fill_parent"Android:layout_height="wrap_content"> <Button Android:id="@+id/btn"Android:layout_width="fill_parent"Android:layout_height="wrap_content"Android:text="Click on"/> </LinearLayout> <LinearLayout Android:id="@+id/line2"Android:layout_width="fill_parent"Android:layout_height="wrap_content"Android:layout_below="@id/lin1"> <TextView Android:id="@+id/textview1"Android:layout_width="match_parent"Android:layout_height="wrap_content"/> </LinearLayout>
Activity_main.xml

Modify the layout in Second.xml (TextView is used to get values from the previous activity):

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"Android:layout_width="match_parent"Android:layout_height="match_parent"android:orientation="Vertical"> <TextView Android:id="@+id/textview2"Android:layout_width="match_parent"Android:layout_height="wrap_content"/> <Button Android:id="@+id/btn2"Android:layout_width="fill_parent"Android:layout_height="wrap_content"Android:text=" Back"/></linearlayout>
Second.xml

Add a Click event for button 1 in Mainactivity.java, jump to activity 2,

btn1=(Button) Findviewbyid (R.ID.BTN);                Btn1.setonclicklistener (new  Onclicklistener () {                        @Override            publicvoid  OnClick (View arg0) {                //  TODO auto-generated method stub                Intent intent1=< C13>new Intent (mainactivity.  this, Second. class );                Intent1.putextra ("MyData", "Hello, I come from interface 1 .... ");                StartActivity (INTENT1);            }        });
Setonclicklistener ()

Here we start second with the display intent and pass a string through the Putextra () method. where Putextra () accepts two parameters, the first parameter is the key, which is used to fetch the value from intent, and the second parameter is the value to be passed. The
then goes into Second.java, where our goal is to remove the value from the previous page, and add the following code to the Oncreat () method:

    protected void onCreate (Bundle savedinstancestate) {        //  TODO auto-generated method stub         Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.second);        BTN2=(Button) Findviewbyid (R.ID.BTN2);        TextView2=(TextView) Findviewbyid (R.ID.TEXTVIEW2);                 // gets the value        of the last activity outgoing Intent intent=getintent ();        Textview2.settext (Intent.getstringextra ("MyData"));}
oncreat ()

The Getintent () method is used to get the intent of the second to start, and then call the Getstringextra () method to get the corresponding key value, you can get the data passed. It then displays the data that is passed on the TextView.

2. Return data to previous activity

The method is similar to the above, in the Mainactivity.java is still click Button control to jump to the second page,

Intent intent1=new Intent (mainactivity.this,second.class); Startactivityforresult (intent1, 1);

Here we use the Startactivityforresult () method to start the Second,startactivityforresult () method to accept two parameters, the first parameter is intent, and the second parameter is the request code, which is used to determine the source of the data in the callback. Where the request code as long as the unique value can be.

Register the Click event with the button in second and add the logic to return the data:

btn2=(Button) Findviewbyid (R.ID.BTN2); Btn2.setonclicklistener (new  Onclicklistener () {                        @ Override            publicvoid  OnClick (View arg0) {                Intent intentback=new Intent ();                Intentback.putextra ("Data_back", "Interface 1, Hello!!!" ");                Setresult (RESULT_OK, intentback);                Finish ();            }        });
View Code

Building intent here is just for passing data, without any specified intent. The data to be passed is then placed in Intentback, and then the Setresult () method is called to return data to the previous activity. The Setresult () method accepts two parameters, the first parameter is used to return processing results to the previous activity, typically only RESULT_OK or result_canceled, and the second parameter passes the Intentback with the data back, The finish () method is then called to destroy the current activity (it must be destroyed or it cannot be recalled).

Because of the second initiated using the Startactivityforresult () method, the Onactivityresult () method is recalled to the previous activity after being destroyed. It is therefore necessary to re-write this method in Mainactivity.java to get the returned data as follows:

protected voidOnactivityresult (intRequestcode,intResultCode, Intent data) {        //TODO auto-generated Method Stub        Super. Onactivityresult (Requestcode, ResultCode, data); TextView1=(TextView) Findviewbyid (R.ID.TEXTVIEW1); Super. Onactivityresult (Requestcode, ResultCode, data); Switch(requestcode) { Case1:            if(resultcode==RESULT_OK) {Textview1.settext (Data.getstringextra ("Data_back") + "I come from interface 2!!! "); }             Break; default:        }                    }
Onactivityresult ()

Onactivityresult () has three parameters, the first parameter Requestcode, which is the request code that we passed in when we started the activity, the second parameter ResultCode, which is the processing result we passed in when we returned the issue. The third parameter, data, is the intent with the returned data (this refers to Intentback).

Since it is possible for an activity to invoke the Startactivityforresult () method to initiate many different activities, the data returned by each activity is transferred to Onactivityresult (), so the first thing to do is to Requestcode, That is, the request code to check the judgment data source. Then, based on the value of the ResultCode, the processing result is judged to be successful. And finally hit him to pass in the returned data.

Q: When the user does not return through the button's Click event and returns by the back key, is it impossible to get the data that you want to return?

At this point we only need to call a method called onbackpressed () to solve this problem. The code is as follows:

 Public void onbackpressed () {        Intent intentback=new  Intent ();        Intentback.putextra ("Data_back", "Interface 1, Hello!!!" ");        Setresult (RESULT_OK, intentback);        Finish ();    }
onbackpressed ()

In fact, we can write a method of returning data separately, and then call it directly when the button registers a click event or onbackpressed ().

The problem of transmitting value between Android activities

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.