我正在开发将数据保存到SQLite并将其同步到mysql数据库的android应用。 Internet可用时,代码运行良好,但是当没有Internet可用时,它将在MySQL数据库中插入4次。请参阅下面的代码 请帮助谢谢。我指的是此link的代码。请帮助您。
public class NetworkStateChecker extends BroadcastReceiver {
private Context context;
private DatabaseHelper db;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
db = new DatabaseHelper(context);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
//if there is a network
if (activeNetwork != null) {
//if connected to wifi or mobile data plan
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
//getting all the unsynced names
Cursor cursor = db.getUnsyncedNames();
if (cursor.moveToFirst()) {
do {
//calling the method to save the unsynced name to MySQL
saveName(
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_POS)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_CODE))
);
} while (cursor.moveToNext());
}
}
}
}
private void saveName(final int id, final String name, final String code, final String pos) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MainActivity.URL_SAVE_NAME,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//updating the status in sqlite
db.updateNameStatus(id, MainActivity.NAME_SYNCED_WITH_SERVER);
//sending the broadcast to refresh the list
context.sendBroadcast(new Intent(MainActivity.DATA_SAVED_BROADCAST));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("code", code);
params.put("pos", pos);
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
}