package com.example.sharedpreferences;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
private final String SharedPreferences_Name = "SharedPreferences_name";
private final String USER_NAME = "user_name";
private final String USER_PASSWORD = "user_password";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wrtieSharedPreferences();
readSharedPreferences();
}
// 读出记录
private void readSharedPreferences() {
SharedPreferences sp = this.getSharedPreferences(
SharedPreferences_Name, Context.MODE_PRIVATE);
String username = sp.getString(USER_NAME, "无值");
Log.d("存储到本地的用户名", username);
}
// 写入记录到本地
private void wrtieSharedPreferences() {
SharedPreferences shared = this.getSharedPreferences(
SharedPreferences_Name, Context.MODE_PRIVATE);
Editor edit = shared.edit();
edit.putString(USER_NAME, "zhangphil");
edit.putString(USER_PASSWORD, "12345678");
// 提交
edit.commit();
}
}