android sharedPreference的用法

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="white-space:pre">	</span>sharedPreference可以將一些簡單的信息以xml形式保存到SD卡上,比如登陸時的用戶名和密碼,這樣在下次登陸時,用戶不必再從數據庫或網絡獲取數據了。提升系統性能。下面簡單記錄一下sharedpreference的用法。</span>

package com.example.sharedpreferences;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;

public class MySharedPreference {

	private Context context;

	public MySharedPreference(Context context) {
		// TODO Auto-generated constructor stub
		this.context = context;
	}

	public boolean saveMessage(String name, String pwd) {
		boolean flag = false;
		SharedPreferences  sharedPreferences = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
		
		//對數據編輯
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("name", name);
		editor.putString("pwd", pwd);
		flag = editor.commit();
		return flag;
	}

	public Map<String, Object> getMessage(){
		SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo",Context.MODE_PRIVATE);
		
		String name = sharedPreferences.getString("name","");
		String pwd = sharedPreferences.getString("pwd","");
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("name", name);
		map.put("pwd", pwd);
		return map;
	}
}


發佈了41 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章