1 package com.danale.mysharedpreferences; 2 3 import java.util.Map; 4 5 import com.danale.services.PreSharedPreferences; 6 7 import android.os.Bundle; 8 import android.app.Activity; 9 import android.view.Menu; 10 import android.view.View; 11 import android.widget.EditText; 12 import android.widget.Toast; 13 14 public class MainActivity extends Activity { 15 private EditText nameText; 16 private EditText ageText; 17 private PreSharedPreferences service; 18 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 24 nameText = (EditText) this.findViewById(R.id.nameedt); 25 ageText = (EditText) this.findViewById(R.id.ageedt); 26 service = new PreSharedPreferences(this); 27 28 Map<String, String> params = service.getPreferences(); 29 nameText.setText(params.get("name")); 30 ageText.setText(params.get("age")); 31 32 } 33 34 @Override 35 public boolean onCreateOptionsMenu(Menu menu) { 36 // Inflate the menu; this adds items to the action bar if it is present. 37 getMenuInflater().inflate(R.menu.main, menu); 38 return true; 39 } 40 41 public void save(View v) 42 { 43 String name = nameText.getText().toString(); 44 String age = ageText.getText().toString(); 45 46 service.save(name, Integer.valueOf(age)); 47 Toast.makeText(getApplicationContext(), R.string.success, 1).show(); 48 } 49 50 }
1 package com.danale.services; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 import android.content.Context; 7 import android.content.SharedPreferences; 8 import android.content.SharedPreferences.Editor; 9 10 public class PreSharedPreferences { 11 private Context context; 12 public PreSharedPreferences(Context context) { 13 this.context = context; 14 } 15 /** 16 * 保存参数,姓名,年龄 17 * @param name 18 * @param valueOf 19 */ 20 public void save(String name, Integer valueOf) { 21 // TODO Auto-generated method stub 22 SharedPreferences preferences = context.getSharedPreferences("danale", Context.MODE_PRIVATE); 23 Editor editor = preferences.edit(); 24 editor.putString("name", name); 25 editor.putInt("age", valueOf); 26 editor.commit(); 27 } 28 /** 29 * 获取各项配置参数 30 * @return 31 */ 32 public Map<String, String> getPreferences() 33 { 34 Map<String, String> params = new HashMap<String, String>(); 35 SharedPreferences preferences = context.getSharedPreferences("danale", Context.MODE_PRIVATE); 36 params.put("name", preferences.getString("name", "")); 37 params.put("age", String.valueOf(preferences.getInt("age", 0))); 38 return params; 39 } 40 41 }