Android: static variables for Activity data transmission
Using Intent can easily transfer data between different activities. This is also officially recommended, but it also has some limitations.
That is, Intent cannot pass objects that cannot be serialized. We can use static variables to solve this problem.
Obj class
package com.example.activity;public class Obj{String name;public String getName(){return name;}public void setName(String name){this.name=name;}}
Declare a static variable in OtherActivity
public static Obj obj;
Add a button component to MainActivity and add a click event to it
Intent intent = new Intent (); intent. setClass (MainActivity. this, OtherActivity. class); startActivity (intent); Obj obj = new Obj (); obj. setName ("I am Su"); OtherActivity. obj = obj;
Then output this value in OtherActivity.
Toast.makeText(OtherActivity.this, obj.getName(), Toast.LENGTH_LONG).show();
After doing this, we also need to do one thing in OtherActivity to make obj = null when this Activity is destroyed;
This is because there is a garbage collection mechanism in java that only recycles objects with no pointing type, that is, null.
protected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();obj=null;}
Running result:
,