在sqlite数据库android中保存和检索键值对

美好的一天,基本上我正在寻找一种方法来检索和保存关于sqlite数据库中的列项的键值对,以便我可以更新列表视图。

示例:如果我有一个名为“group”的列,其项目条目名为“family”; 关于该项目,我希望能够保存或检索仅为该项目“家庭”的联系人列表(姓名和号码)。 同一个项目条目。

什么是最好的方法呢? 我尝试通过json使用Hashmap的ArrayList将联系人详细信息保存在表的列中。 但这样做有麻烦。 我试过这个:

保存时:

//already have the name and number from using the android contacts api final ArrayList<HashMap> contacts = new ArrayList<HashMap>(); HashMap map = new HashMap(); map.put(name, number); contacts.add(map); JSONObject json_contacts = new JSONObject(); try { json_contacts.put("contacts_Arrays", new JSONArray(contacts)); arraylist_to_string = json_contacts.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } ContentValues values = new ContentValues(); values.put(ContactDB.GROUP, groupname); values.put(ContactDB.GROUP_CONTACTS, arraylist_to_string); Log.d(TAG, "Successfully updating contacts for group"); dbadapter.updateGroup(rowId, values); cursoradapter.notifyDataSetChanged(); 

在我的bindview方法中检索时:

String contactDetails = cursor.getString(cursor.getColumnIndex(ContactDB.GROUP_CONTACTS));

  if(contactDetails != null){ try { JSONObject json = new JSONObject(contactDetails); JSONArray json_array = json.optJSONArray("contacts_Arrays"); for(int i=0; i < json_array.length(); i++){ LinkedHashMap map = new LinkedHashMap(); Iterator myIterator = map.keySet().iterator(); while(myIterator.hasNext()){ key = (String)myIterator.next(); value = (String)map.get(key); holder.contact_name.setText(key); holder.contact_number.setText(value); notifyDataSetChanged(); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ return; } } 

根本没有运气,也不确定它是否是正确的方法。 什么是构建数据库表的最佳方法。 我应该创建一个联系对象并存储它还是有更好的方法? 谢谢

只需查看代码, List多个HashMap实例可能是内存过量,具体取决于存储数据的大小。

由于您希望存储键值对,因此关系数据库(如SQLite就是其中之一)通常不是正确的决策。 Android具有“共享首选项”来存储简单的键值对(具有原始数据类型)。


如果你想/需要用SQLite实现它,你应该采用关系方式。 如果我理解你的问题是正确的,你会得到如下表格:

 Table "Groups" +----------+------------+ | group_ID | group_name | +----------+------------+ | 1 | Family | | 2 | Work | +----------+------------+ Table "Contacts" +----------+------------+--------+ | name | number | group | +----------+------------+--------+ | Jon | 0173401... | 1 | | James | 057123... | 2 | | Lukas | 012343... | 2 | +----------+------------+--------+ 

从该表中,您可以查询“James”和“Lukas”是“工作”组的成员。 然后,您可以通过简单地搜索条目来查询“工作”组的所有成员,其中group列设置为group -table中显示的值(“工作”组为2 )。

使用此系统,您可以添加新组和联系人,并将联系人放入(或多个)组。