Android两种存储用户临时数据的方式比较:Preferences & Bundle

本文介绍了SharedPreferences和Bundle在Android开发中的应用。SharedPreferences适用于保存用户的偏好设置等简单键值对数据,并将其持久化存储;而Bundle主要用于在不同Activity间传递数据,如用户输入的信息等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Preferences 用于当按键Home or Back时保存用户临时输入的数据。

常常在OnCreate() 和OnStop()函数中使用。

用法:

public static final String PREFS_NAME = "MyPrefsFile";
 
OnCreate() 方法中调用

// Restore preferences 

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 

boolean silent = settings.getBoolean("silentMode", false); 

setSilent(silent); 

OnStop()函数调用

// Save user preferences. We need an Editor object to 

// make changes. All objects are from android.context.Context 

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 

SharedPreferences.Editor editor = settings.edit(); 

editor.putBoolean("silentMode", mSilentMode); 

// Don't forget to commit your edits!!! 

editor.commit();

 

一、Bundle在API文档的说明

  1.介绍

    用于不同Activity之间的数据传递

  1.重要方法

    clear():清除此Bundle映射中的所有保存的数据。

    clone():克隆当前Bundle

    containsKey(String key):返回指定key的值

    getString(String key):返回指定key的字符

    hasFileDescriptors():指示是否包含任何捆绑打包文件描述符

    isEmpty():如果这个捆绑映射为空,则返回true

    putString(String key, String value):插入一个给定key的字符串值

    readFromParcel(Parcel parcel):读取这个parcel的内容

    remove(String key):移除指定key的值

    writeToParcel(Parcel parcel, int flags):写入这个parcel的内容

二、实例

  Bundle bundle = new Bundle();  //保存输入的信息  

  bundle.putString("name", info);    

 Intent intent=new Intent(BundleDemo.this,BundleDemo1.class);   

  intent.putExtras(bundle);

//接受 传递后的值

Bundle b=getIntent().getExtras();
  //获取Bundle的信息
String info=b.getString("name");

 

总结:

SharedPreferences是简单的存储持久化的设置,就像用户每次打开应用程序时的主页,它只是一些简单的键值对来操作。它将数据保存在一个xml文件中

Bundle是将数据传递到另一个上下文中或保存或回复你自己状态的数据存储方式。它的数据不是持久化状态。(类似于Session的用法)。

转载于:https://www.cnblogs.com/nidongde/archive/2012/11/28/2791998.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值