标签:
Android SharedPreferences一般用于轻量级的数据存储,比如用户名和密码等。
1 package com.lixu.testsharepreferences; 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.content.SharedPreferences; 6 import android.content.SharedPreferences.Editor; 7 import android.os.Bundle; 8 import android.widget.Toast; 9 10 public class MainActivity extends Activity { 11 12 private static final String USER_NAME = "username"; 13 private static final String USER_PWS = "userpws"; 14 private String NAME = "name"; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 writeSharedPreferences(); 21 readSharedPreferences(); 22 23 } 24 25 // Context.MODE_PRIVATE 这个是设置访问权限 意思是只有本app可以读写里面的数据 26 // 如果SharedPreferences里面没有写入数据 就返回"无值"; 27 private void readSharedPreferences() { 28 SharedPreferences sp = this.getSharedPreferences(NAME, Context.MODE_PRIVATE); 29 30 String str1 = sp.getString(USER_NAME, "无值"); 31 String str2 = sp.getString(USER_PWS, "无值"); 32 33 Toast.makeText(getApplicationContext(), "用户名是:" + str1, 1).show(); 34 35 Toast.makeText(getApplicationContext(), "用户密码是:" + str2, 1).show(); 36 37 } 38 39 private void writeSharedPreferences() { 40 SharedPreferences sp = this.getSharedPreferences(NAME, Context.MODE_PRIVATE); 41 42 Editor edt = sp.edit(); 43 edt.putString(USER_NAME, "lixu"); 44 edt.putString(USER_PWS, "123456789"); 45 // 提交 46 edt.commit(); 47 48 } 49 50 }
运行效果:
Android SharedPreferences一般的读写 的用法。
标签:
原文地址:http://www.cnblogs.com/labixiaoxin/p/4979910.html