前段时间傻乎乎的用sqllite来保存用户的记住密码,用sqlite是可以保存,但当时用时就感觉怪怪的,那时候还不知道SharedPreferences,我们在网頁上的话,一般都是用cookies来保存的,Android的话应该用这个来保存的比较多。我的个人感觉SharedPreferences要比我之前那个要好的多了。
MainActivity.java
public class MainActivity extends Activity { PreferencesService service; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); service=new PreferencesService(this); save(); } void save(){ service.save("caibinsong",21); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
PreferencesService.java
package com.example.sharedpreferences; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PreferencesService { private Context context; public PreferencesService(Context context){ this.context=context; } /* * 保存name和age * */ public void save(String name,Integer age){ SharedPreferences preferences =context.getSharedPreferences("itcast", Context.MODE_PRIVATE); Editor editor =preferences.edit(); editor.putString("name",name); editor.putInt("age", age); editor.commit(); } /* * 获取值 * */ public Map<String ,String> getPreferences(){ Map<String,String> params=new HashMap<String,String>(); SharedPreferences preferences=context.getSharedPreferences("itcast", Context.MODE_PRIVATE); params.put("name", preferences.getString("name", "")); params.put("age", String.valueOf(preferences.getInt("age", 0))); return params; } }