将列表放入 android 中的 SQLite 数据库 [英] Putting a list into a SQLite database in android
问题描述
我有一个 List
,我想把它放到 SQLite 数据库中.
I have a List<Contact>
and I'ld like to put it into a SQLite database.
我读过一些其他帖子,说您需要将 List 转换为 JSONArray 并将其作为 TEXT 字段存储在数组中,但我是初学者,这一切都非常令人困惑.
I've read some other posts saying you need to convert the List to a JSONArray and store it as a TEXT field in the array but I'm a beginner and this is all very confusing.
到目前为止我有一个方法如下:
So far I have a method as follows:
public JSONArray void toJSON() {
JSONArray jsonArray = new JSONArray(myList);
return jsonArray
}
然后在我的 sqlite 数据库中我说:
Then in my sqlite database I say:
ContentValues values = new ContentValues();
values.put(KEY_CONTACTS, group.toJSON());
但我收到一个错误消息,说ContentValues 类型中的 put(String, String) 方法不适用于参数 (String, JSONArray).我不知道如何正确地把它变成一个字符串.任何帮助将不胜感激.
But I am getting an error saying The method put(String, String) in the type ContentValues is not applicable for the arguments (String, JSONArray). I dont know how to properly get it to a string though. Any help would be appreciated.
推荐答案
有一个示例代码,希望对你有帮助.
there is one sample code, hope it could help u.
class Contact {
public int id,
public String name;
public String phone;
}
class ContactColumns {
public static final String ID = "_id";
public static final String NAME = "name";
public static final String PHONE = "phone";
}
private List<ContentValues> buildContentValueList(String jsonStr) {
if (TextUtils.isEmpty(jsonStr)) {
return null;
}
List<ContentValues> list = new ArrayList<ContentValues>();
JSONArray jsonArray = new JSONArray(jsonStr);
for (i = 0; i< jsonArray.length(); i++) {
JSONObject jb = jsonArray.optJSONObject(i);
if (jb == null) {
continue;
}
ContentValues values = new ContentValues();
values.put(ContactColumns.ID, jb.optInt("ID_KEY"));
values.put(ContactColumns.NAME, jb.optString("NAME_KEY"));
values.put(ContactColumns.PHONE, jb.optString("PHONE_KEY"));
list.add(contact);
}
return list;
}
public void insertContact(List<ContentValues> valueList) {
if (valueList.size() > 0) {
ContentValues[] valueArray = new ContentValues[valueList.size()];
valueArray = valueList.toArray(valueArray);
getContentResolver().bulkInsert(ContactTable.URI, valueArray);
}
}
you can call insertContact(buildContentValueList(jsonString)) to complete, that's all.
这篇关于将列表放入 android 中的 SQLite 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!