【发布时间】:2012-08-22 13:22:01
【问题描述】:
正如标题所说,我想保存和检索某些字符串。但是我的代码在检索或存储中都不会通过第一行。 我试着点击这个链接:http://developer.android.com/guide/topics/data/data-storage.html
private void savepath(String pathtilsave, int i) {
String tal = null;
// doesn't go past the line below
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
tal = String.valueOf(i);
editor.putString(tal, pathtilsave);
editor.commit();
}
和我的检索方法:
public void getpaths() {
String tal = null;
// doesn't go past the line below
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
for (int i = 1; i <= lydliste.length - 1; i++) {
tal = String.valueOf(i);
String restoredText = settings.getString(tal, null);
if (restoredText != null) {
lydliste[i] = restoredText;
}
}
}
lydliste 是一个静态字符串数组。 PREFS_NAME 是
public static final String PREFS_NAME = "MyPrefsFile";
【问题讨论】:
-
有一个不错的library,如果您只存储和恢复一个特定活动中的值,它可以为您节省一些锅炉代码
-
使用 apply() 代替; commit() 是同步的,而 apply() 是异步的。 apply() 将在后台处理。