簡體   English   中英

從URL提取JSON數據並反復更新SQLite數據庫

[英]Fetch JSON Data from URL and Repeatedly Update SQLite Database

在我的應用程序中,我創建一個SQLite數據庫。 然后,在我的主要活動中,使用HttpAsyncTask類的實例,使用從URL提取的JSON數據填充該數據。 效果很好,但我也想更新數據庫。 每天一次將新數據(數據庫中的一行)添加到URL頁面,我想在應用程序中實現一個“同步”按鈕,該按鈕僅用新信息更新數據庫。 我可以從中獲得一些建議嗎? 我的HttpAsyncTask在下面,如果有幫助的話-我認為我可能需要onPostExecute()方法中的if / else子句,僅在首次創建數據庫時才添加所有行。 我考慮過嘗試在我的DatabaseHelper中放置一個HttpAsyncTask類,但這沒有任何意義。

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String...urls) {
        return GET(urls[0]);
    }

    @Override
    protected void onPostExecute(String result) {

        try {
            JSONObject main = new JSONObject(result);
            JSONObject body = main.getJSONObject("body");
            JSONArray measuregrps = body.getJSONArray("measuregrps");

            // get measurements for date, unit, and value (weight)
            for (int i = 0; i < measuregrps.length(); i++) {
               JSONObject row = measuregrps.getJSONObject(i);
               // a lot of getting & parsing data happens
               db.addEntry(new Entry(date, weight, null, null)); 
               //adds all the lines every time this is run, but I only want to add all 
               //the lines once and then add new rows one by one from there
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

public static String GET(String url) {
    InputStream is = null;
    String result = "";
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse httpResponse = client.execute(get);
        is = httpResponse.getEntity().getContent();
        if (is != null)
            result = convertInputStream(is);
        else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("input stream", e.getLocalizedMessage());
    }

    return result;
}

private static String convertInputStream(InputStream is) throws IOException {
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line = "";
    while((line = reader.readLine()) != null)
        builder.append(line);
    is.close();
    return builder.toString();
}

您的實施完全取決於項目要求。 如果服務器上不斷發生變化,則實現同步過程的正確方法是:

1.實施同步過程,該過程完全在后台運行。 該同步將被定制以調用同步所需的特定API調用/服務類。

2.服務器將提示移動客戶端更改數據。

3.要獲取服務器更新,將以預定的時間間隔運行持續運行的服務/同步,並檢查更新或實施GCM。

同步適配器將是最好的同步服務。 哦,也不要忘記應用內容提供程序,因為數據庫調用將在UI和后台同時進行。

希望它可以幫助決定。

您必須檢查表中是否有類似數據,如果可以,請更新表,如果沒有,請向表中插入新數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM