我有一个名为DatabaseHandler的类,它基本上处理了一个Contacts数据库。当我打开我的Android模拟器时,我可以添加和删除联系人。然后,当我关闭模拟器并重新打开它时,它会保留联系人,因此数据库会存储联系人。
我的问题是这个。我的联系人类中有一个变量,如下所示:
public static int totalContacts = 0;
此变量记录数据库中的联系人总数,因此当我添加联系人时,它会递增,反之亦然。但是,当我关闭模拟器并重新打开它时,数据库仍然有4个联系人,但totalContacts变量显然仍为0。
有没有办法让totalContacts
等于数据库中的联系人数量,以便记住?
感谢您的时间。
答案 0 :(得分:2)
是。当您知道正确数量的联系人时,可以将其存储在SharedPreferences
。
Android文档中解释了一切:http://developer.android.com/guide/topics/data/data-storage.html
基本上,当您想保存该值时,请写下:
SharedPreferences settings = getSharedPreferences("NAME_OF_YOUR_CHOICE", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("numContacts", numContacts);
editor.commit(); // Save the changes
当你想加载它时:
SharedPreferences settings = getSharedPreferences("NAME_OF_YOUR_CHOICE", 0);
int numContacts = settings.getInt("numContacts", -1); // if there's no variable in SharedPreferences with name "numContacts", it will have -1 value
答案 1 :(得分:1)
如果要永久存储数据,则必须使用Sharedpreferences。它会将您的数据保存在设备RAM中,直到您清除数据或卸载应用程序数据将保留在内存中。使用以下代码。
//当您第一次获得价值时,这意味着当您获得价值并希望存储它时。
SharedPreferences preferences = getSharedPreferences("YOUR_IDENTIFIED_KEY_VALUE", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Contacts", CONTACTS VALUE);
editor.commit(); // Save the changes
// And when you want to get stored values, means when you need yo use that value:
SharedPreferences preferences = getSharedPreferences("YOUR_IDENTIFIED_KEY_VALUE", 0);
int contacts = preferences.getInt("Contacts", 0);