Android 不同Activity间传递数据


方法一:通过Android.content.Intent传递数据,只能传递基类型

存储数据
  1. // 方法一:用intent传递数据   
  2. intent.putExtra("string", str);  
读取数据
  1. // 方法一:用intent传递数据   
  2. Intent intent = this.getIntent();  
  3. Bundle bundle = intent.getExtras();  
  4. str += "Fonction 1: " + bundle.getString("string") + "\n";  
方法二:通过android.content.SharedPreferences传递数据,只能传递基类型

存储数据
  1. // 方法二:用SharedPreferences传递数据   
  2. SharedPreferences preferences = getSharedPreferences("test", MODE_PRIVATE);  
  3. SharedPreferences.Editor editor = preferences.edit();  
  4. editor.putString("string", str);  
  5. editor.commit();  
读取数据
  1. // 方法二:用SharedPreferences传递数据   
  2. SharedPreferences preferences = this.getSharedPreferences("test", MODE_PRIVATE);  
  3. str += "Fonction 2: " + preferences.getString("string""not found") + "\n";  
方法三:自定义继承Application的类传递数据,可以传递基类型和自定义类型,需要在manifest中注册

manifest中注册
  1. <application android:icon="@drawable/icon" android:label="@string/app_name" android:name="mytest.xml.MyApp">  
自定义继承Application的类
  1. public class MyApp extends Application {  
  2.       
  3.     private String str;  
  4.     private Obj obj;  
  5.       
  6.     public String getStr() {  
  7.         return str;  
  8.     }  
  9.     public void setStr(String str) {  
  10.         this.str = str;  
  11.     }  
  12.     public Obj getObj() {  
  13.         return obj;  
  14.     }  
  15.     public void setObj(Obj obj) {  
  16.         this.obj = obj;  
  17.     }     
  18. }  
存储数据
  1. // 方法三:用Application自定义类传递数据   
  2. MyApp app = (MyApp)getApplicationContext();  
  3. app.setStr(str);  
  4. app.setObj(obj);  
读取数据
  1. // 方法三:用Application自定义类传递数据   
  2. MyApp app = (MyApp)this.getApplicationContext();  
  3. str += "Fonction 3 (string): " + app.getStr() + "\n";  
  4. str += "Fonction 3 (object): " + app.getObj().getMess();   // app.getObj返回自定义Obj类实例,getMess()方法返回类内定义的String内容  

相关内容