android中的sharedPreferences应用与理解

1.sharedPreferences中文件的存储格式是xml文件格式

2.新增加的相同键名的记录会覆盖原来的同键名的记录

3.可以存储json格式的数据

一、sharedPreferences封装好的操作代码:

package com.example.text;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class FileDB {

	
	private SharedPreferences m_preferences;
	private Editor m_editor;
	public FileDB() {
		super();
	}

	public boolean setTable(Context context_in, String strTableName) {
		
		if (strTableName == null) {
			return false;
		}
		
		m_preferences = context_in.getSharedPreferences(strTableName,Context.MODE_PRIVATE);
		m_editor = m_preferences.edit();
		
		return true;
	}
	
	public void put(String strAttributeName, String strValue) {	
		m_editor.putString(strAttributeName, strValue);
		m_editor.commit();
	}

	public String get(String strAttributeName) {	
		return new String (m_preferences.getString(strAttributeName, "NULL"));
	}
}
activity中调用示例:

		//建表
		fileDB.setTable(MainActivity.this,"user");
		
		//存数据
		fileDB.put("name", "zhangsan");
		//取数据
		String result = fileDB.get("name");
		
		
		fileDB.put("name", "lisi");
		String result2 = fileDB.get("name");
		tv1.setText(result);
		tv2.setText(result2);
二、在sharedPreferences中存储json格式数据

存数据:

public static void saveApkEnalbleArray(Context context,boolean[] booleanArray) {
	    SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);
	    JSONArray jsonArray = new JSONArray();
	    for (boolean b : booleanArray) {
	      jsonArray.put(b);
	    }
	    SharedPreferences.Editor editor = prefs.edit();
	    editor.putString(APK_ENABLE_ARRAY,jsonArray.toString());
	    editor.commit();
	  }

取数据:

public static boolean[] getApkEnableArray(Context context,int arrayLength)
	  {
	    SharedPreferences prefs = context.getSharedPreferences(APK_ENABLE_ARRAY, Context.MODE_PRIVATE);
	    boolean[] resArray=new boolean[arrayLength]; 
	    Arrays.fill(resArray, true);
	    try {
	        JSONArray jsonArray = new JSONArray(prefs.getString(APK_ENABLE_ARRAY, "[]"));
	        for (int i = 0; i < jsonArray.length(); i++) {
	        	resArray[i] = jsonArray.getBoolean(i);
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    
	   return resArray;
	  }
调用示例:

boolean[] booleanArray = {true,true,false,false};
		saveApkEnalbleArray(this,booleanArray);
		boolean[] resArray = getApkEnableArray(this,2);
		tv1.setText(resArray[0]+"");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值