SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长整形、Int整形、String字符串型的保存,它是什么样的处理方式呢?下面就是了,不多说了 里面很详细:
界面:
新建类Preferences:
package lk.service;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class Preferences {
private Context context;
public Preferences(Context context) {
super();
this.context = context;
}
/**
* 保持参数
* @param name姓名
* @param valueOf年龄
*/
public void save(String name, Integer valueOf) {
// TODO Auto-generated method stub
//1.文件名称2.操作模式
//检索和保存参数文件的内容的“名字”,返回一个SharedPreferences通过它可以检索和修改它的值。
SharedPreferences preferences=context.getSharedPreferences("xxxx", Context.MODE_PRIVATE);
//通过编辑器存放数据
Editor editor=preferences.edit();
editor.putString("name", name);
editor.putInt("age", valueOf);
//提交方法
editor.commit();
}
/**
* 获取各项配置参数
* @return
*/
public Map<String, String> getPreferences(){
Map<String, String> params=new HashMap<String, String>();
SharedPreferences preferences=context.getSharedPreferences("xxxx", Context.MODE_PRIVATE);
params.put("name", preferences.getString("name", ""));
params.put("age",String.valueOf(preferences.getInt("age",0)));
return params;
}
}
SharedPreferencesActivity.java
package lk.n;
import java.util.Map;
import lk.service.Preferences;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class SharedPreferencesActivity extends Activity {
/** Called when the activity is first created. */
private EditText nametext;
private EditText agetext;
private Preferences servie;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//EditText nametext=(EditText) findViewById(R.id.name);
nametext=(EditText) this.findViewById(R.id.name);
//EditText agetext=(EditText) findViewById(R.id.age);
agetext=(EditText) this.findViewById(R.id.age);
servie=new Preferences(this);
Map<String, String> params=servie.getPreferences();
nametext.setText(params.get("name"));
agetext.setText(params.get("age"));
}
public void save(View v){
String name=nametext.getText().toString();
String age=agetext.getText().toString();
servie.save(name,Integer.valueOf(age));
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
}
}