Sharepreference:轻量级的数据存储方式,主要存储一些简单的配置信息,如:默认欢迎语,登陆用户名和密码等。以键值对的方式存储,便于读取和存储。
代码中写的很清楚,不在另外说明了:
main.xml文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:hint="name" /> <EditText android:id="@+id/et_pwd" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword" android:hint="password"/> </LinearLayout>
MainActivity.java文件:
package com.jjw.jjwan.sharepreferencetest; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private EditText etName,etPwd; //键值 String name = "name"; String pwd = "pwd"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etName = (EditText) findViewById(R.id.et_name); //得到SharedPreferences SharedPreferences shared = getSharedPreferences("test",MainActivity.MODE_PRIVATE); ///也可以用这种方式得到SharedPreference,参数是Context //SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); //判断是否有记录过的name和pwd,有就显示 if(!shared.getString("test","").equals(null)){ etName.setText(shared.getString(name,"")); etPwd.setText(shared.getString(pwd,"")); } } @Override protected void onStop() { super.onStop(); //得到SharedPreferences SharedPreferences shared = getSharedPreferences("test",MainActivity.MODE_PRIVATE); //记录当前的对象数据 SharedPreferences.Editor editor = shared.edit(); if (!etName.getText().equals(null) && !etPwd.getText().equals(null)){ //写进去 editor.putString(name,etName.getText().toString()); editor.putString(pwd,etPwd.getText().toString()); //保存 editor.commit(); } } }