Android Learning Path 1: How to pass data between activity

Source: Internet
Author: User

Passing Data
    • New Activity

Right-click in the project, select New, continue to select activity below, and finally the Blank activity.

At this point, Android Studio automatically adds a corresponding layout file for us, adding an ID to the TextView in the layout file for later use.

    • Send data with intent

Create a new Button control in the main layout file, define it in the main class, and set the Click listener event for it.

Button button;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Findviewbyid (R.id.button). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent i =NewIntent (mainactivity. This, Main2activity.class); I.putextra ("Thanks","Thank for reading my blog.");            StartActivity (i);    }        }); }
    • Receive data with Intent

Next, create a new Intent in the Activity you created earlier to accept. Similar to sending a trial PutExtra, acceptance can also be getstringextra. Of course, it is possible to use different methods for different data types.

private TextView tv;                                 @Override                                            protectedvoidonCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);                  setContentView(R.layout.activity_main2);             Intent i = getIntent();                              tv = (TextView)findViewById(R.id.tv);                tv.setText(i.getStringExtra("Thanks"));          }                                                                                            
Pass Bundle Bundles

You can also use bundle packets to transfer data between two Activity, which can contain more data than the previous one, and you can think of it as a collection, which is in line with the concept of "package".

    • New Bundle

    • Bundles can nest bundles

    • Using the Putextras method with Intent objects

@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); Findviewbyid (R.id.button). Setonclicklistener (NewView.onclicklistener () {@Override         Public void OnClick(View v) {Intent i =NewIntent (mainactivity. This, Main2activity.class); Bundle A =NewBundle (); A.putstring ("Thanks","Thank for reading my blog."); Bundle B =NewBundle (); B.putstring ("Android","Google"); B.putstring ("Windows","Microsoft"); A.putbundle ("Bundle", b);            I.putextras (a);        StartActivity (i); }    });}
    • Obtain the corresponding bundle data according to the corresponding Key value
@Override protected void OnCreate (Bundle Savedinstan Cestate) {Super. OnCreate(savedinstancestate); Setcontentview (R. Layout. Activity_MAIN2); Intent i = getintent (); Bundle A2 = i. Getextras(); TV = (TextView) Findviewbyid (R. ID. TV); Tv. SetText(String. Format("%s Android belongs to%s,windows belongs to%s", A2. getString("Thanks"), A2. Getbundle("Bundle"). getString("Android"), A2. Getbundle("Bundle"). getString("Windows"))); }
passing a custom object

There is no "class" in the Android development process, so how can this data be transmitted?

    • Remember: Be sure to perform serialization, that is, add "implements Serializable"
 Public  class Source implements Serializable{    Private intSourcePrivateString ID; Public int GetSource() {returnSource } Public void SetSource(intSOURCE) { This. Source = Source; } PublicStringGetID() {returnID; } Public void SetID(String ID) { This. id = ID; } Public Source(String ID,intSOURCE) { This. Source = Source; This. id = ID; }}

With the corresponding understanding of the previous, we can directly guess how to use, then I will no longer wordy.

@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); Findviewbyid (R.id.button). Setonclicklistener (NewView.onclicklistener () {@Override         Public void OnClick(View v) {Intent i =NewIntent (mainactivity. This, Main2activity.class); I.putextra ("Source",NewSource ("Player", +));        StartActivity (i); }    });}
@Override protected void OnCreate (Bundle savedinstancestate) { Super. OnCreate(savedinstancestate); Setcontentview (R. Layout. Activity_MAIN2); Intent i = getintent (); SOURCE S = (source) I. Getserializableextra("Source"); TV = (TextView) Findviewbyid (R. ID. TV); Tv. SetText(String. Format("ID is%s, score is%d", S. GetID(), S. GetSource())); }
returning data from activity

The user needs to interact with the app, and the app needs to return the data entered by the user, so ...

The Button and TextView are defined in the main activity, which is used to navigate to the secondary activity, which is used to display the returned data.

The Button and EditText are defined in the secondary activity, which is used to confirm and return to the main activity, which is used for user input.

In the secondary Activity:

    • Also use Intent to pass data

    • Return results with Setresult settings

    • Finally use finish

PrivateButton button;PrivateEditText EditText;@Override                                                       protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);                        Setcontentview (r.layout.activity_main2);               EditText = (editText) Findviewbyid (R.id.edittext);                    Button = (button) Findviewbyid (R.id.button2); Button.setonclicklistener (NewView.onclicklistener () {@Override                                                        Public void OnClick(View v) {Intent i =NewIntent (); I.putextra ("Info", Edittext.gettext (). toString ()); Setresult (0, i);//0 indicates successFinish ();                                                         }                                                           }); }

In the main Activity:

    • Navigate with Startactivityforresult and request the results
    PrivateButton button;PrivateTextView TextView;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        TextView = (TextView) Findviewbyid (R.id.textview); Findviewbyid (R.id.button). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent i =NewIntent (mainactivity. This, Main2activity.class); Startactivityforresult (I,0);    }        }); }
    • Overloads the Onactivityresult method, and obtains the data through the database parameter.
    @Override    protectedvoidonActivityResult(intint resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        textView.setText(data.getStringExtra("info"));    }

Well, that's how the data is passed between the Activity ...

It's:30. Go to bed......

Copyright NOTICE: This article is nomasp Couvant original article, without permission is prohibited reprint! Welcome to my blog: http://blog.csdn.net/nomasp

Android Learning Path 1: How to pass data between activity

Related Article

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.