Android之SharedPreferences

SharedPreferences是Android中存储一些轻量级(只能存储key-value对)数据的一种方式,实际上SharedPreferences会把数据保存在xml文件中,可以在/data/data/appPackageName/下查看对应的xml文件。

获取方式

Context对象的getSharedPreferences()和Activity对象的getPreferences()方法。
区别:
getSharedPreferences()获得的SharedPreferences允许该应用程序下的其他组件使用,而getPreferences()获得的SharedPreferences只能在该Activity中使用。

获取和保存数据

    //MainActivity.java主要代码:
    @Override
    protected void onStart() {
        super.onStart();
        //获取数据
        SharedPreferences sharedPreferences = this.getSharedPreferences("person", Context.MODE_PRIVATE);//person是文件名,对应到person.xml

        EditText nameEditText = (EditText) findViewById(R.id.name);
        String name = sharedPreferences.getString(R.id.name+"", "");
        nameEditText.setText(name);

        EditText ageEditText = (EditText) findViewById(R.id.age);
        String age = sharedPreferences.getString(R.id.age+"", "");
        ageEditText.setText(age);
    }

    public void saveSetting(View view) {
        //保存数据
        SharedPreferences sharedPreferences = this.getSharedPreferences("person", Context.MODE_PRIVATE);

        Editor edit = sharedPreferences.edit();

        EditText nameEditText = (EditText) findViewById(R.id.name);
        edit.putString(R.id.name+"", nameEditText.getText().toString());

        EditText ageEditText = (EditText) findViewById(R.id.age);
        edit.putString(R.id.age+"", ageEditText.getText().toString());

        edit.commit();
    }
    <!-- fragment_main.xml主要代码 -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/name" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
       android:id="@+id/name"/>

     <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/age" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
       android:id="@+id/age"/>

    <Button  android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
       android:id="@+id/saveButton" android:text="@string/saveSetting" android:onClick="saveSetting"/>

操作模式

Context.MODE_PRIVATE:私有,覆盖。
Context.MODE_APPEND:私有,追加。
Context.MODE_WORLD_READABLE:公开读(其他应用可读)。
Context.MODE_WORLD_WRITEABLE:公开读写(其他应用可读写)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值