0

I have a List<Contact> and I'ld like to put it into a SQLite database.

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
}

Then in my sqlite database I say:

ContentValues values = new ContentValues();
        values.put(KEY_CONTACTS, group.toJSON());

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.

4

1 回答 1

1

有一个示例代码,希望它可以帮助你。

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.
于 2013-10-17T02:54:18.783 回答