iro*_*xxx 1 java sqlite android
美好的一天,基本上我正在寻找一种方法来检索和保存与 sqlite 数据库中的列项目相关的键值对,以便我可以更新列表视图。
示例:如果我有一个名为“group”的列,其中有一个名为“family”的条目;关于该项目,我希望能够为该项目“家庭”保存或检索联系人列表(姓名和号码)。另一个项目条目相同。
什么是最好的方法来做到这一点?我尝试通过 json 使用 Hashmap 的 ArrayList 将联系人详细信息保存在表格的一列中。但这样做有麻烦。我试过这个:
保存时:
//already have the name and number from using the android contacts api
final ArrayList<HashMap<String,String>> contacts = new ArrayList<HashMap<String,String>>();
HashMap<String, String> map = new HashMap<String,String>();
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();
Run Code Online (Sandbox Code Playgroud)
在我的 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<String,String> map = new LinkedHashMap<String, String>();
Iterator<String> 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;
}
}
Run Code Online (Sandbox Code Playgroud)
根本没有任何运气,并且不确定它是否是正确的方法。构建数据库表的最佳方法是什么。我应该创建一个联系人对象并存储它还是有更好的方法?谢谢
仅通过查看您的代码,a 中的多个HashMap
实例List
可能会造成内存过大,具体取决于您存储数据的大小。
由于您想要存储键值对,因此关系数据库(如 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 |
+----------+------------+--------+
Run Code Online (Sandbox Code Playgroud)
从该表中,您可以查询“James”和“Lukas”是“Work”组的成员。然后,您可以通过简单地搜索将group
-column 设置为group
-table(2
用于“Work”-group)中显示的值的条目来查询“Work”组的所有成员。
使用此系统,您可以添加新组和联系人,并将联系人放入(或多个)组中。
归档时间: |
|
查看次数: |
5350 次 |
最近记录: |