Android不同Activity之间数据的传递
Android项目中,很多时候,我们需要在一个activity中,调用另一个Activity的数据,目前,比较通用的方法有这么几类,通过intent跳转携带数据,使用SharedPreferences保存数据,使用数据库保存数据,使用全局变量,保存数据。
1.intent跳转携带数据
发送方:
val intent = Intent(this,MineOrdersListActivity::class.java)
intent.putExtra("id",1)
startActivity(intent)
接收方:
val id = intent.getIntExtra("id",0)
2.SharedPreferences传递数据
在一个Activity里保存数据。
val sp = getSharedPreferences("info", Context.MODE_PRIVATE)
val ed = sp.edit()
ed.putString("number","1")
ed.commit()
在另一个Activity里读取数据
val num:String? = null
val sp = getSharedPreferences("info", Context.MODE_PRIVATE)
val number = sp.getString("number",num)
3.数据库保存数据,见我上一篇文章《Android数据库GreenDao的使用》
4.全局变量保存数据
在项目的Application中初始化数据
class MyApplicatin : Application() {
private var ylabel: String? = null
fun getLabel(): String? {
return ylabel
}
fun setLabel(s: String) {
this.ylabel = s
}
override fun onCreate() {
super.onCreate()
setLabel("YUZHIBOYI_CSND!") //初始化全局变量
}
}
在需要的地方修改字符串的数据
private var yApp: MyApplication? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_payment)
yApp = application as MyApplication //获得自定义的应用程序YApp
yApp!!.setLabel("YUZHIBOYI!") //修改一下
在另外需要取数据的地方,取出数据
private MyApplication yApp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pay_result);
yApp = (MyApplication) getApplication(); //获得自定义的应用程序MyApp
Log.i("YAnG", "查看变量值是否修改了:"+yApp.getLabel()); //查看变量值是否修改了
}
另外大家有其他好的传递数据的方法,欢迎来讨论。
---------------------
作者:mlsnatalie
来源:CSDN
原文:https://blog.csdn.net/mlsnatalie/article/details/81187300
版权声明:本文为博主原创文章,转载请附上博文链接!

浙公网安备 33010602011771号