如何保存列表项的状态,以便我可以在重新启动手机时将其恢复。目前在下面的代码中,您可以看到我有一个列表视图,其中包含一个列表项。现在我想在onDestroy和onPause期间保存“items”的状态,并在onCreate期间检索回来(这样做的原因是在重新启动手机时检索数据状态)。有人可以帮助代码。
public class LogListView extends ListActivity {
/** Called when the activity is first created. */
private static String newString;
private static EntryAdapter adapter;
int clickCounter = 0;
static ArrayList<Item> items = new ArrayList<Item>();
static SharedPreferences preferences = null;
private static Context context = null;
static StringTokenizer tokens;
private static String first;
private static String second;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
adapter = new EntryAdapter(this, items);
// items.add(new SectionItem("Log Report"));
setListAdapter(adapter);
if (adapter.getCount() != 0) {
// Do nothing Adapter has value
} else {
Toast.makeText(LogListView.this, "No Items Available",Toast.LENGTH_SHORT).show();
//Retrive Preference here when Adapter is null
}
}
// Method which will handle dynamic insertion
public static void addItems() {
preferences = context.getSharedPreferences("LOG",android.content.Context.MODE_PRIVATE);
newString = preferences.getString("log", "");
tokens = new StringTokenizer(newString, ",");
first = tokens.nextToken();
second = tokens.nextToken();
items.add(new EntryItem(first, second));
adapter.notifyDataSetChanged();
}
// Method which will handle dynamic insertion ends
@Override
public void onDestroy() {
super.onDestroy();
//Save preference here
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if (!items.get(position).isSection()) {
items.get(position);
// Toast.makeText(this, "You clicked " + item.title ,
// Toast.LENGTH_SHORT).show();
Toast.makeText(this, "You clicked " + position, Toast.LENGTH_SHORT)
.show();
}
if (position == 9) {
}
super.onListItemClick(l, v, position, id);
}
}
答案 0 :(得分:0)
如果我必须将List保存到SharedPreferences,我总是选择执行以下操作,但是你需要使用Gson库。
首先将列表转换为JSON字符串:
Type listOfObjects = new TypeToken<List<YourObject>>(){}.getType();
String json = gson.toJson(list, listOfObjects);
然后将String保存到首选项。要将json转换回列表,请执行以下操作:
Type listOfObjects = new TypeToken<List<YourObject>>(){}.getType();
List<YourObject> list = gson.fromJson(json, listOfObjects);