【九】数据持久化

2018-03-12  本文已影响0人  晴天ccc

数据持久化的三种方式:

文件存储读写

sharedPreference(类似iOS的NSUserdefault)

SQLite

sharedPreference为例

当我们的应用想要保存用户的一些偏好参数,比如是否自动登陆,是否记住账号密码,是否在Wifi下才能等。

通常使用 一个轻量级的存储类——SharedPreferences来保存用户偏好的参数!SharedPreferences也是使用xml文件, 然后类似于Map集合,使用键-值的形式来存储数据;我们只需要调用SharedPreferences的getXxx(name), 就可以根据键获得对应的值!使用起来很方便。

编写简单的SP工具类:SharedHelper.java

/**

 * Created by Jay on 2015/9/2 0002.

 */

public class SharedHelper {

    private Context mContext;

    public SharedHelper() {

    }

    public SharedHelper(Context mContext) {

        this.mContext = mContext;

    }

    //定义一个保存数据的方法

    public void save(String username, String passwd) {

        SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sp.edit();

        editor.putString("username", username);

        editor.putString("passwd", passwd);

        editor.commit();

        Toast.makeText(mContext, "信息已写入SharedPreference中", Toast.LENGTH_SHORT).show();

    }

    //定义一个读取SP文件的方法

    public Map<String, String>read() {

        Map<String, String>data = new HashMap<String, String>();

        SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE);

        data.put("username", sp.getString("username", ""));

        data.put("passwd", sp.getString("passwd", ""));

        return data;

    }

}

最后是MainActivity.java实现相关逻辑:

public class MainActivity extends AppCompatActivity {

    private EditText editname;

    private EditText editpasswd;

    private Button btnlogin;

    private String strname;

    private String strpasswd;

    private SharedHelper sh;

    private Context mContext;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mContext = getApplicationContext();

        sh = new SharedHelper(mContext);

        bindViews();

    }

    private void bindViews() {

        editname = (EditText)findViewById(R.id.editname);

        editpasswd = (EditText)findViewById(R.id.editpasswd);

        btnlogin = (Button)findViewById(R.id.btnlogin);

        btnlogin.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                strname = editname.getText().toString();

                strpasswd = editpasswd.getText().toString();

                sh.save(strname,strpasswd);

            }

        });

    }

    @Override

    protected void onStart() {

        super.onStart();

        Map<String,String>data = sh.read();

        editname.setText(data.get("username"));

        editpasswd.setText(data.get("passwd"));

    }

}

上一篇 下一篇

猜你喜欢

热点阅读