【Android数据存储】- Shared Preferences


个人学习整理,如有不足之处,请不吝指教。转载请注明: @CSU-Max


Android中常用的数据存储方式简介

       Android中为开发人员提供了各种数据持久化方式,具体的选择需要根据应用本身,有的数据只需要存储在本地,有的数据要和其他应用共享,有的要存储在网络服务器上,很多的应用都是采取了多种存储方式结合的方式来存储数据信息的。

        Android中常用的几种数据存储方式:
        Shared Preferences :    以键值对的形式存储私有的基本类型数据。
        SQLite Database :    保存结构化数据到私有数据库。
        Internal Storage :    保存私有数据到设备的内部存储。
        External Storage :    保存数据到共享的外部存储,如SD卡等。
        Network Connection :    保存数据到网络服务器。
 

SharedPreferences

 
      若应用程序有少量的数据需要存储,而且数据格式很简单,通常就是普通字符串、标志变量等,比如各种配置信息(是否开启音效、是否记住密码等)就可以使用SharedPreferences进行数据的存储,在应用程序退出之后,数据仍然会保存。
 

    1、向 SharedPreferences 中写入信息

       (1)  获取 SharedPreferences 对象;
       (2) 调用 SharedPreferences 的 edit( ) 方法获取 Editor 对象;
       (3)  调用 Editor 的 putXxx(key, value) 写入值;
       (4)  调用 Editor 的 commit( ) 提交信息。
 

    2、读取 SharedPreferences 中的信息

       (1)  获取 SharedPreferences 对象;
       (2)  调用 SharedPreferences  的 getXxx(key, defaultValue)方法取值。
 
    注:
    SharedPreferences 本身是一个接口,无法创建其实例,只有通过 Context 的 getSharedPreferences(String name, int model) 来获取其实例,其中 model 参数的值有以下几种选择:
         MODE_PRIVATE : 默认方式,此种情况下该 SharedPreferences 数据只能被本应用读和写;
         MODE_WORLD_READABLE : 此种情况下该 SharedPreferences 数据能被其他应用读,不能写;
         MODE_WORLD_WRITEABLE : 此种情况下该 SharedPreferences 数据能被其他应用读和写。
    SharedPreferences  接口本身没有提供数据写入相关的方法,而是通过其内部接口实现的,调用其 edit() 方法,获取其对应的 Editor 对象, Editor 提供了多种写入数据的方法。
 
    代码实例:
        此 demo 很简单,就是一个普通的登录界面,输入用户名和密码后点击登录按钮,将用户的信息写入 SharedPreferences 中,并跳转到欢迎界面,再从 SharedPreferences  中读取存储的信息,显示在界面上。
    主要代码:

package com.example.sharedpreferencesdemo;
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
*
* @author CSUMax
* @version 1.0
* 2014-2-24
*/
public class MainActivity extends Activity {
 
    private EditText et_main_username;
    private EditText et_main_password;
    private Button bt_main_login;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        et_main_username = (EditText) this.findViewById(R.id.et_main_username);
        et_main_password = (EditText) this.findViewById(R.id.et_main_password);
        bt_main_login = (Button) this.findViewById(R.id.bt_main_login);
 
        bt_main_login.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                String username = et_main_username.getText().toString();
                String password = et_main_password.getText().toString();
 
                /***************the next is the point*****************/
                //使用 SharedPreferences 来存储信息
                //获取 SharedPreferences 对象,指定文件名称;
                SharedPreferences sp = getSharedPreferences("user",MODE_PRIVATE);
                //获取 Editor 对象
                Editor editor = sp.edit();
                // 调用 putXxx(key, value) 写入值;
                editor.putString("sp_username", username);
                editor.putString("sp_password", password);
                //提交
                editor.commit();
 
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, WelcomeActivity.class);
                startActivity(intent);
            }
        });
 
 
    }
 
}

package com.example.sharedpreferencesdemo;
 
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
/**
*
* @author CSUMax
* @version 1.0
* 2014-2-24
*/
public class WelcomeActivity extends Activity {
 
    private TextView tv_welcome_username;
    private TextView tv_welcome_password;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
 
        tv_welcome_username = (TextView) this.findViewById(R.id.tv_welcome_username);
        tv_welcome_password = (TextView) this.findViewById(R.id.tv_welcome_password);
 
        /***************the next is the point*****************/
        //读取 SharedPreferences 中存储的信息
        //获取 SharedPreferences 对象,指定文件名称;
        SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
        //调用 getXxx(key, defaultValue)方法取值,若 SharedPreferences 中没有此 key 对应的值,则会返回 defaultValue 的值。
        String username = sp.getString("sp_username", "test");
        String password = sp.getString("sp_password", "test");
 
        tv_welcome_username.setText(username);
        tv_welcome_password.setText(password);
 
 
 
    }
 
}


  注: Android 中 SharedPreferences 使用 XML 来存储数据,我们可以在 DDMS 视图中的 File Explorer 的 data 文件夹中找到,文件名就是我们在程序中指定的名称。
 

    3、读取其他应用程序的 SharedPreferences

 
     代码实例:
            此 demo 很简单,就是另外新建一个应用,来读取上面例子中存储在 SharedPreferences 中的信息,当然,上面的例子也需要做一点小小的修改,就是要修改 getSharedPreferences 方法的第二个参数的值(MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE),不然是无法在其他程序中读取本应用的 SharedPreferences 信息。
     主要代码:
package com.example.sharedpreferencesdemo;
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
*
* @author CSUMax
* @version 1.0
* 2014-2-24
*/
public class MainActivity extends Activity {
 
    private EditText et_main_username;
    private EditText et_main_password;
    private Button bt_main_login;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        et_main_username = (EditText) this.findViewById(R.id.et_main_username);
        et_main_password = (EditText) this.findViewById(R.id.et_main_password);
        bt_main_login = (Button) this.findViewById(R.id.bt_main_login);
 
        bt_main_login.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                String username = et_main_username.getText().toString();
                String password = et_main_password.getText().toString();
 
                /***************the next is the point*****************/
                //使用 SharedPreferences 来存储信息
                //获取 SharedPreferences 对象;
                SharedPreferences sp = getSharedPreferences("user",MODE_WORLD_READABLE);
                //获取 Editor 对象
                Editor editor = sp.edit();
                // 调用 putXxx(key, value) 写入值;
                editor.putString("sp_username", username);
                editor.putString("sp_password", password);
                //提交
                editor.commit();
 
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, WelcomeActivity.class);
                startActivity(intent);
            }
        });
 
 
    }
 
}


package com.example.readspdemo;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.widget.TextView;
/**
* @author CSUMax
* @version 1.0
* 2014-2-24
*/
public class MainActivity extends Activity {
 
    private TextView tv_welcome_username;
    private TextView tv_welcome_password;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        tv_welcome_username = (TextView) this
                .findViewById(R.id.tv_welcome_username);
        tv_welcome_password = (TextView) this
                .findViewById(R.id.tv_welcome_password);
 
        /*************** the next is the point *****************/
        // 读取其他应用 SharedPreferences 中存储的信息
        // 获取其他应用的 Context,com.example.sharedpreferencesdemo 为要读取应用的程序包名
        Context otherContext = null;
        try {
            otherContext = createPackageContext("com.example.sharedpreferencesdemo", CONTEXT_IGNORE_SECURITY);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        // 使用其他应用程序的 Context 获取 SharedPreferences 对象;
        SharedPreferences sp = otherContext.getSharedPreferences("user", MODE_WORLD_READABLE);
        // 调用 getXxx(key, defaultValue)方法取值,若 SharedPreferences 中没有此 key 对应的值,则会返回 defaultValue 的值。
        String username = sp.getString("sp_username", "test");
        String password = sp.getString("sp_password", "test");
 
        tv_welcome_username.setText(username);
        tv_welcome_password.setText(password);
    }
 
}

          关于 Shared Preferences 的简单使用方法就介绍到这里,下一节将讲到 Android 中的 SQLite 使用。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值