Android中的数据存储之SharedPreferences

使用SharedPreference时,数据的保存必须使用commit()方法,否则数据不会保存;
数据会保存在DDMS的包目录下的shared_prefs下:
Activity代码
public class ContentProviderActivity extends Activity {
    /** Called when the activity is first created. */
    private static final String FILENAME = "tmacsky";
    private TextView author = null;
    private TextView age = null;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*SharedPreferences share = getSharedPreferences(FILENAME,Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = share.edit();//指定操作的文件名称
        editor.putString("author", "huanglong");
        editor.putInt("age", 24);
        editor.commit();*///第一段代码
        setContentView(R.layout.main);
        author = (TextView)findViewById(R.id.author);
        age = (TextView)findViewById(R.id.age);
        SharedPreferences share = getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        author.setText("作者: "+share.getString("author", "没有作者信息"));
        age.setText("年龄: "+share.getInt("age", 0));//第2段代码
    }
}

XML代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF" 
        android:textSize="22px"
        android:id="@+id/author"/>
	<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF" 
        android:textSize="22px"
        android:id="@+id/age"/>
</LinearLayout>

先用第一段代码里的内容写入数据,然后把第一段注释掉,用下面第2段代码加上main.xml来读取数据:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值