【0026】Android基础-13-sharedPreference的使用
【1】【sharedPreference】用来存储数据的
【注】在公司,使用sharedPreference的场合特别多;




【2】sharedPreference的使用


【数据的存储】

【数据的读取】

【3】sharedPreference的另外一种写法
1 package com.itheima.login.util; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.InputStreamReader; 8 import java.util.HashMap; 9 import java.util.Map; 10 11 import android.content.Context; 12 import android.content.SharedPreferences; 13 import android.content.SharedPreferences.Editor; 14 import android.preference.PreferenceManager; 15 16 public class UserInfoUtil { 17 18 //保存用户名密码 19 public static boolean saveUserInfo_android(Context context,String username, String password) { 20 21 try{ 22 23 24 //1.通过Context对象创建一个SharedPreference对象 25 //name:sharedpreference文件的名称 mode:文件的操作模式 26 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); 27 28 //2.通过sharedPreferences对象获取一个Editor对象 29 Editor editor = sharedPreferences.edit(); 30 //3.往Editor中添加数据 31 editor.putString("username", username); 32 editor.putString("password", password); 33 //4.提交Editor对象 34 editor.commit(); 35 36 return true; 37 }catch (Exception e) { 38 e.printStackTrace(); 39 } 40 41 return false; 42 } 43 44 45 //获取用户名密码 46 public static Map<String ,String> getUserInfo_android(Context context){ 47 48 try{ 49 50 //1.通过Context对象创建一个SharedPreference对象 51 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); 52 //2.通过sharedPreference获取存放的数据 53 //key:存放数据时的key defValue: 默认值,根据业务需求来写 54 String username = sharedPreferences.getString("username", ""); 55 String password = sharedPreferences.getString("password", ""); 56 57 58 HashMap<String, String> hashMap = new HashMap<String ,String>(); 59 hashMap.put("username",username); 60 hashMap.put("password", password); 61 return hashMap; 62 63 }catch (Exception e) { 64 e.printStackTrace(); 65 } 66 return null; 67 68 } 69 70 71 72 73 }
【新生成的文件】以包名命名的xml文件;

浙公网安备 33010602011771号