标签:
public static String getPreferredLocation(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getString(context.getString(R.string.pref_location_key), context.getString(R.string.pref_location_default)); }有点区别,应该是Preference的问题,一会讨论。
public class MainActivity extends AppCompatActivity { SharedPreferences preferences; SharedPreferences.Editor editor; public static final String PRE_TAG = "sy.com"; public static final String KEY_TIME = "time"; public static final String KEY_RANDOM = "random"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); preferences = getSharedPreferences(PRE_TAG, MODE_PRIVATE); editor = preferences.edit(); Button read = (Button)findViewById(R.id.read); Button write = (Button)findViewById(R.id.write); read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String time = preferences.getString(KEY_TIME, null); int random = preferences.getInt(KEY_RANDOM, 0); String result = time == null ? "暂时未写入数据" : "上次写入时间" + time + "\n上次生成随机数" + random; Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); } }); write.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss"); editor.putString(KEY_TIME, sdf.format(new Date())); editor.putInt(KEY_RANDOM,(int)(Math.random() * 100)); editor.commit(); } }); } }
标签:
原文地址:http://blog.csdn.net/qingziguanjun1/article/details/51328781