我已經能夠將一個條目保存到共享首選項,並且能夠在另一個視圖的列表視圖中顯示,但我希望添加多個條目並將它們也顯示在列表視圖中。我以爲我有正確的代碼,但它沒有看到任何改變。我的意圖是收藏夾列表,我從一個視圖中獲取條目數據並在另一個視圖中顯示它。如何將字符串集保存到共享首選項
SingleView活動:
SharedPreferences.Editor fd;
SharedPreferences FeedPref;
private ArrayList<String> addArray = new ArrayList<>();
txt = (TextView) findViewById(R.id.name);
add = (Button) findViewById(R.id.btnAdd);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String message = txt.getText().toString();
if (addArray.contains(message)) {
Toast.makeText((getBaseContext()), "Plant Already Added", Toast.LENGTH_LONG).show();
} else {
addArray.add(message);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
fd.putInt("array_size", addArray.size());
for (int i = 0; i < addArray.size(); i++) {
fd.putString("Status_" + i, addArray.get(i));
}
fd.commit();
Toast.makeText((getBaseContext()), "Plant Added", Toast.LENGTH_LONG).show();
}
}
});
}
mygarden活性:
public class mygardenMain extends Activity {
//String[] presidents;
ListView listView;
//ArrayAdapter<String> adapter;
SharedPreferences FeedPref;
SharedPreferences.Editor fd;
//private ArrayList<String> addArray;
//public static final String PREFS = "examplePrefs";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
listView = (ListView) findViewById(R.id.mygardenlist);
//addArray = new ArrayList<>();
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int size = FeedPref.getInt("array_size", 0);
for (int i = 0; i < size; i++) {
String mess = FeedPref.getString("Status_" + i, null);
String[] values = new String[]{mess};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
}
fd.commit();只要你把字符串,就會被調用。而這並不是理想的做法。 –
爲什麼不保存一個集合,我認爲它會更清晰,看看這篇文章:http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences,比onclick事件,你應該得到從共享偏好設置,添加新項目並保存。 – fdam
這是我用來從我到達今天的代碼的線程。 – user4682589