Когда я выключаю inte rnet, он хорошо сохраняет в sqlite, но при запуске сохраняет дублирующиеся записи в mysql. Как синхронизировать только данные, которые не были добавлены в mysql? (более подробно я закрываю net -> добавить строку-> активировать net -> добавить mysql .. если я закрою net и активирую его, а ранее сохраненные данные будут сохранены)
publi c класс MainActivity расширяет AppCompatActivity реализует LocationListener, View.OnClickListener {.............. registerReceiver (new NetworkStateChecker (), новый IntentFilter (ConnectivityManager.CONNECTIVITY_ACTION)) ;
//initializing views and objects
db = new DatabaseHelper(this);
names = new ArrayList<>();
button.setOnClickListener((View.OnClickListener) this);
loadNames();
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//loading the names again
loadNames();
}
};
registerReceiver(broadcastReceiver, new IntentFilter(DATA_SAVED_BROADCAST));
}
private void loadNames() {
names.clear();
Cursor cursor = db.getNames();
if (cursor.moveToFirst()) {
do {
Avize name = new Avize(
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Serie)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Numar)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Descarcare)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NrVehicul)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Lista)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_VolumTotal)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Latitudine)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Longitudine)),
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_STATUS))
);
names.add(name);
} while (cursor.moveToNext());
}
}
private void saveNameToServer() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final String serie = et_serie.getText().toString().trim();
final String nr = et_nr.getText().toString().trim();
final String desc = et_descarcare.getText().toString().trim();
final String nrVeh = et_numarVehicul.getText().toString().trim();
final String lista = list.toString();
final String volTot = et_volumTotal.getText().toString().trim();
final String lat = tv_textView.getText().toString().trim();
final String longi = tv_textView2.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, BASE_URL,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
saveNameToLocalStorage(serie, nr, desc, nrVeh, lista, volTot ,lat, longi, NAME_SYNCED_WITH_SERVER);
} else {
saveNameToLocalStorage(serie, nr, desc, nrVeh, lista, volTot ,lat, longi, NAME_NOT_SYNCED_WITH_SERVER);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
] saveNameToLocalStorage (ser ie, nr, des c, nrVeh, lista, volTot, lat, longi, NAME_NOT_SYNCED_WITH_SERVER);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Serie", serie);
params.put("Numar", nr);
params.put("Punct_descarcare", desc);
params.put("Numar_vehicul", nrVeh);
params.put("ListaAviz", lista);
params.put("Volum_total", volTot);
params.put("Latitudine", lat);
params.put("Longitudine", longi);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
//saving the name to local storage
private void saveNameToLocalStorage(String serie,String nr, String desc,String nrVeh,String lista,String volTot, String lat,
String longi, int status) {
et_serie.setText("");
db.addName(serie, nr, desc, nrVeh, lista, lat, longi, volTot, status);
Avize n = new Avize(serie, nr, desc, nrVeh, lista, lat, longi, volTot, status);
names.add(n);
// refreshList();
}
@Override
public void onClick(View view) {
saveNameToServer();
}
publi c класс NetworkStateChecker расширяет BroadcastReceiver {
//context and database helper object
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 (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
//getting all the unsynced names
Cursor cursor = db.getUnsyncedNames();
if (cursor.moveToFirst()) {
do {
saveName(
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Serie)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Numar)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Descarcare)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NrVehicul)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Lista)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_VolumTotal)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Latitudine)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_Longitudine))
);
} while (cursor.moveToNext());
}
}
}
}
private void saveName(final int id, final String serie
, final String nr, final String desc, final String nrVeh, final String lista
, final String volTot, final String lat, final String longi
) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MainActivity.BASE_URL,
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("Serie", serie);
params.put("Numar", nr);
params.put("Punct_descarcare", desc);
params.put("Numar_vehicul", nrVeh);
params.put("ListaAviz", lista);
params.put("Volum_total", volTot);
params.put("Latitudine", lat);
params.put("Longitudine", longi);
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
}