2016-04-28 91 views
-1

我對SharedPreferences有點麻煩。當我嘗試保存時,所有顯示的內容都是新的一行。我也有添加一行的麻煩。你可以幫我嗎?SharedPreferences問題

這裏是我的代碼:

public List displayData(){ 
    SharedPreferences sharedPref = MainActivity.this.getSharedPreferences("userInfo", Context 
      .MODE_PRIVATE); 
    Map<String, ?> allMap = sharedPref.getAll(); 
    all = new ArrayList<>(); 
    for (Map.Entry<String, ?> entry : allMap.entrySet()) { 
     all.add(entry.getKey().toString() + ":" + entry.getValue().toString()); 
    } 
    return all; 
} 

public void add(View view){ 
    SharedPreferences sharedPref = MainActivity.this.getSharedPreferences("userInfo", Context 
      .MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPref.edit(); 
    editor.putString(" ", " "); 
    editor.apply(); 
} 

private void save(String type, String content){ 
    editor.putString(type, content); 
    editor.apply(); 
} 

private void delete(String key){ 
    editor.remove(key); 
    editor.apply(); 
} 
+1

'editor.putString(「」,「」);'......你想在這裏做什麼? – codeMagic

+0

什麼是錯的? – Gorio

+0

老兄你真的把一個空的字符串。你怎麼了? – Vucko

回答

0

我測試過你的源和這個例子工程完美..

save("TESTE1", "Valor 1"); 
save("TESTE2", "Valor 2"); 

displayData(); 

delete("TESTE1"); 

displayData(); 

,並簡化你的代碼。

SharedPreferences sharedPref = SplashActivity.this.getSharedPreferences("userInfo", Context 
     .MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 

public List displayData(){ 

    Map<String, ?> allMap = sharedPref.getAll(); 
    List all = new ArrayList<>(); 
    for (Map.Entry<String, ?> entry : allMap.entrySet()) { 
     all.add(entry.getKey() + ":" + entry.getValue().toString()); 
    } 

    return all; 
} 

private void save(String type, String content){ 
    editor.putString(type, content); 
    editor.apply(); 
} 

private void delete(String key){ 
    editor.remove(key); 
    editor.apply(); 
}