Android之SharedPreference轻量级数据存储
16lz
2021-12-04
android的配置文件
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android_sharedpreference" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="9" /> <instrumentation android:targetPackage="com.example.android_sharedpreference" android:name="android.test.InstrumentationTestRunner"></instrumentation> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <uses-library android:name="android.test.runner"></uses-library> <activity android:name="com.example.android_sharedpreference.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
下面是操作代码
package com.example.android_sharedpreference;import java.util.HashMap;import java.util.Map;import android.content.Context;import android.content.SharedPreferences;public class MySharedpreference {private Context context;public MySharedpreference(Context context) {// TODO Auto-generated constructor stubthis.context = context;}public boolean saveMessage(String name,String pswd){boolean flag=false;SharedPreferences sharedPreferences=context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);//对数据进行编辑SharedPreferences.Editor editor=sharedPreferences.edit();editor.putString("name",name);editor.putString("pswd", pswd);flag=editor.commit();//将数据持久化return flag;}public Map<String,Object>getMessage(){Map<String, Object>map=new HashMap<String, Object>();SharedPreferences sharedPreferences=context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);String name=sharedPreferences.getString("name","");String pswd=sharedPreferences.getString("pswd", "");map.put("name", name);map.put("pswd",pswd);return map;}}
测试代码
import java.util.Map;import android.content.Context;import android.test.AndroidTestCase;import android.util.Log;public class MyTest extends AndroidTestCase {private String TAG="MyTest";public void save(){Context context=getContext();MySharedpreference mySharedpreference=new MySharedpreference(context);boolean flag=mySharedpreference.saveMessage("admin", "password");Log.i(TAG,"-->"+flag);}public void find(){Context context=getContext();MySharedpreference mySharedpreference=new MySharedpreference(context); Map<String, Object> map=mySharedpreference.getMessage(); Log.i(TAG, map.toString());}}
在Android系统中, 其配置文件的数据文件 以XML文件的形式保存在/data/data/目录 /shared_prefs目录下
更多相关文章
- mybatisplus的坑 insert标签insert into select无参数问题的解决
- python起点网月票榜字体反爬案例
- Android语音识别
- 【Android】串口通信
- Android中JSON数据的读写方法
- Android全局捕获异常
- Android(安卓)文件储存
- Android--登录界面(demo)
- Android中在OnCreate时获得控件高度