Android 不同Activity间传递数据

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

存储数据

// 方法一:用intent传递数据
intent.putExtra("string", str);

读取数据
// 方法一:用intent传递数据
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
str += "Fonction 1: " + bundle.getString("string") + "\n";

方法二:通过android.content.SharedPreferences传递数据,只能传递基类型

存储数据
// 方法二:用SharedPreferences传递数据
SharedPreferences preferences = getSharedPreferences("test", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("string", str);
editor.commit();

读取数据
// 方法二:用SharedPreferences传递数据
SharedPreferences preferences = this.getSharedPreferences("test", MODE_PRIVATE);
str += "Fonction 2: " + preferences.getString("string", "not found") + "\n";

方法三:自定义继承Application的类传递数据,可以传递基类型和自定义类型,需要在manifest中注册

manifest中注册
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name="mytest.xml.MyApp">

自定义继承Application的类
public class MyApp extends Application {
	
	private String str;
	private Obj obj;
	
	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
	public Obj getObj() {
		return obj;
	}
	public void setObj(Obj obj) {
		this.obj = obj;
	}	
}

存储数据
// 方法三:用Application自定义类传递数据
MyApp app = (MyApp)getApplicationContext();
app.setStr(str);
app.setObj(obj);

读取数据
// 方法三:用Application自定义类传递数据
MyApp app = (MyApp)this.getApplicationContext();
str += "Fonction 3 (string): " + app.getStr() + "\n";
str += "Fonction 3 (object): " + app.getObj().getMess();   // app.getObj返回自定义Obj类实例,getMess()方法返回类内定义的String内容


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值