在我的应用程序中,我创建了一个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();
}
答案 0 :(得分:0)
您的实施完全取决于项目要求。 如果服务器上有不断变化,实现同步过程的正确方法是:
1。 实现同步过程,完全在后台运行。此同步将被自定义以调用特定的API调用/服务类,这将是同步所必需的。
2。 服务器将提示移动客户端进行数据更改。
3。 要获取服务器更新,将运行以某些预定义间隔连续运行的服务/同步并检查更新或实施GCM。
同步适配器将是同步服务的最佳选择。 哦,也不要忘记应用内容提供者,因为数据库调用将同时来自UI和后台。
希望它可能有助于决定。
答案 1 :(得分:0)
如果是更新表并且没有向表中插入新数据,则必须检查表中是否有类似数据