In the Android development process, it is very common to pass data between different acitivity. I spent a little time summarizing the data transfer between acitivity and documenting it.
1. Simple transfer of key value pairs
This method of delivery is very simple, just need to add the corresponding key-value pair in the construction intent.
In Activitya, the code for calling intent is as follows:
1 New Intent (Activitya. this, activityb. class ); 2 I.putextra ("name", "Finlay Liu"); 3 I.putextra ("Age", "+"); 5 startactivity (i);
In Activityb, it is possible to read directly from the corresponding key-value pairs.
1 String s = getintent (). Getstringextra ("name") + ":" + getintent (). Getstringextra ("Age"); 4 toast.maketext (This, S, Toast.length_short). Show ();
2. Passing objects
It is also a very common practice to pass objects between different acitivity. I didn't read the Android development documentation carefully before, so when I was writing Android code, object passing between different acitivity was done by static classes. The initial transfer of objects between the activity is also very simple, similar to the above method of passing key values.
The first is to add a serialized interface to the class that needs to be passed:
1 PackageCom.finlayliu.passingobject;2 3 Importjava.io.Serializable;4 5 Public classPersonImplementsSerializable {6 7 Private Static Final LongSerialversionuid = 1L;8 9 Public intgetId () {Ten returnID; One } A - Public voidSetId (intID) { - This. ID =ID; the } - - PublicString GetName () { - returnname; + } - + Public voidsetName (String name) { A This. Name =name; at } - - Public intGetage () { - returnAge ; - } - in Public voidSetage ( ShortAge ) { - This. Age =Age ; to } + - Private intID; the PrivateString name; * Private intAge ; $ Panax Notoginseng PublicPerson () { - the } + A PublicPerson (intID, String name,intAge ) { the This. ID =ID; + This. Name =name; - This. Age =Age ; $ $ } - - PublicString toString () { the returnID + ":" + This. Name + ":" +Age ; - }Wuyi}
Person class
In Activitya, the code for calling intent is as follows:
1 New Intent (mainactivity. this, otheractivity. class ); 2 New Person (1, "finaly Liu", +); 3 I.putextra ("person", p); 4 5 startactivity (i);
In Activityb, read the corresponding object code as follows:
1 person p = (person) getintent (). Getserializableextra (' person ' ); 2 Toast.maketext (Getapplicationcontext (), p.tostring (), Toast.length_long). Show ();