仅在条目不退出时插入

时间:2014-08-21 23:27:40

标签: android json database sqlite insert

在我的Android应用程序中,我下载了一个JSON文件,我解析它,然后将JSONObject的每个条目写入本地SQLite数据库。这是我的代码:

public void myMethod() {
        JSONArray myJA = connectAndCreateJsonArray(url);
        localDB.beginTransaction();

        for (int i = 0; i < lenght; i++) {
            JSONObject jObj = (JSONObject) myJA.getJSONObject(i);
            localDB.insert("users", null, getParsedMerchantEntry(jObj));
        }

        localDB.setTransactionSuccessful();
}

这是connectAndCreateJsonArray()的主体:

    private JSONArray connectAndCreateJsonArray(String url) {
        JSONArray jsonArray = new JSONArray();

        try {   
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            request.addHeader("Cache-Control", "no-cache");
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            InputStreamReader in = new InputStreamReader(entity.getContent());
            BufferedReader reader = new BufferedReader(in);
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line=reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            jsonArray = new JSONArray(stringBuilder.toString());

        } catch (IllegalStateException e) {
            e.printStackTrace();                
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonArray;
    }

这是getParsedMerchantEntry()的主体:

    private ContentValues getParsedMerchantEntry(JSONObject entry) {
        ContentValues values = new ContentValues();

        values.put("id", entry.optString("id").toString());
        values.put("city", entry.optString("city").toString());
        values.put("name", entry.optString("firstname").toString());
        values.put("surname", entry.optString("lastname").toString());

        return values;
    }

如果该条目已存在于本地数据库中,是否可以避免调用localDB.insert()?

1 个答案:

答案 0 :(得分:1)

您必须使用查询

来处理此问题

以下是示例方式。

ContentValues insertValues = new ContentValues();
insertValues.put("id", qclass);
insertValues.put("question", question);

yourDbName.insertWithOnConflict(DATABASE_TABLE, null, insertValues, SQLiteDatabase.CONFLICT_IGNORE); 

确保您的Id字段创建为非空且唯一。