SharedPreferences sd = this.getSharedPreferences("MainActivity", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sd.edit(); editor.putString("name", "dongbaoming"); editor.putString("age", "27"); editor.commit(); Log.i("MainActivity", sd.getString("name", "..") + sd.getString("age", "00")); editor.clear(); editor.commit(); Log.i("MainActivity", sd.getString("name", "..") + sd.getString("age", "00")); 结果:MainActivity: dongbaoming27 MainActivity: ..00
SharedPreferences sd = this.getSharedPreferences("MainActivity", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sd.edit(); editor.putString("name", "dongbaoming"); editor.putString("age", "27"); editor.commit(); Log.i("MainActivity", sd.getString("name", "..") + sd.getString("age", "00")); editor.putString("class", "class three"); editor.clear(); editor.commit(); Log.i("MainActivity", sd.getString("name", "..") + sd.getString("age", "00")+sd.getString("class","no"));
结果:03-28 15:57:54.791 12798-12798/? I/MainActivity: dongbaoming27
03-28 15:57:54.794 12798-12798/? I/MainActivity: ..00class three
SharedPreferences.Editor.clear()方法是把之前commit后保存的所有信息全部进行清空,同一次commit进行的操作如果含有clear()操作,则先执行clear()再执行其他,与代码前后顺序没有关系。