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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章