· 6 years ago · Jun 10, 2019, 01:16 PM
1package br.com.tarcisiofl.supply.presentation;
2
3import android.content.ContentValues;
4import android.content.Context;
5import android.content.Intent;
6import android.content.OperationApplicationException;
7import android.content.SharedPreferences;
8import android.database.Cursor;
9import android.graphics.Color;
10import android.net.ConnectivityManager;
11import android.net.NetworkInfo;
12import android.os.Bundle;
13import android.os.RemoteException;
14import android.support.design.widget.FloatingActionButton;
15import android.util.Log;
16import android.view.View;
17import android.widget.EditText;
18import android.widget.TextView;
19import android.widget.Toast;
20
21import com.crashlytics.android.Crashlytics;
22import com.loopj.android.http.AsyncHttpClient;
23import com.loopj.android.http.AsyncHttpResponseHandler;
24import com.loopj.android.http.RequestParams;
25import com.loopj.android.http.TextHttpResponseHandler;
26
27import org.json.JSONArray;
28import org.json.JSONException;
29
30import java.io.IOException;
31import java.util.HashMap;
32import java.util.Map;
33
34import br.com.tarcisiofl.supply.R;
35import br.com.tarcisiofl.supply.domain.Building;
36import br.com.tarcisiofl.supply.domain.Carrier;
37import br.com.tarcisiofl.supply.domain.Company;
38import br.com.tarcisiofl.supply.domain.Contributor;
39import br.com.tarcisiofl.supply.domain.Service;
40import br.com.tarcisiofl.supply.domain.Shift;
41import br.com.tarcisiofl.supply.domain.Vehicle;
42import br.com.tarcisiofl.supply.repository.basicsyncadapter.parse.ParseObjects;
43import br.com.tarcisiofl.supply.repository.localstorage.BuildingEntry;
44import br.com.tarcisiofl.supply.repository.localstorage.CarrierEntry;
45import br.com.tarcisiofl.supply.repository.localstorage.CompanyEntry;
46import br.com.tarcisiofl.supply.repository.localstorage.ContributorEntry;
47import br.com.tarcisiofl.supply.repository.localstorage.ServiceEntry;
48import br.com.tarcisiofl.supply.repository.localstorage.ShiftEntry;
49import br.com.tarcisiofl.supply.repository.localstorage.VehicleEntry;
50import br.com.tarcisiofl.wizardpager.SingletonStepSaver;
51import cn.pedant.SweetAlert.SweetAlertDialog;
52import cz.msebera.android.httpclient.Header;
53import io.fabric.sdk.android.Fabric;
54
55import static br.com.tarcisiofl.supply.repository.basicsyncadapter.SupplySyncAdapter.performSync;
56
57public class LoginActivity extends BaseActivity {
58
59 private EditText enrollmentNumber;
60 private TextView txtBotaoIniciar;
61 private FloatingActionButton btnSync;
62 private Boolean firstAccess = null;
63 SweetAlertDialog pDialog;
64
65 @Override
66 protected void onCreate(Bundle savedInstanceState) {
67 if (!isFirstAccess()) {
68 performSync();
69 }
70 setTheme(R.style.AppTheme);
71 super.onCreate(savedInstanceState);
72
73 final Fabric fabric = new Fabric.Builder(this)
74 .kits(new Crashlytics())
75 .debuggable(true)
76 .build();
77 Fabric.with(fabric);
78
79 setContentView(R.layout.activity_login);
80
81 init();
82 }
83
84 private void init() {
85 enrollmentNumber = findViewById(R.id.edt_matricula);
86 txtBotaoIniciar = findViewById(R.id.botao_iniciar);
87 btnSync = findViewById(R.id.btn_sync);
88
89 txtBotaoIniciar.setOnClickListener(getClickBotaoIniciar());
90 btnSync.setOnClickListener(getForceSync());
91 }
92
93 private View.OnClickListener getClickBotaoIniciar() {
94 return new View.OnClickListener() {
95 @Override
96 public void onClick(View view) {
97 clickBotaoIniciar();
98 }
99 };
100 }
101
102 private View.OnClickListener getForceSync() {
103 return new View.OnClickListener() {
104 @Override
105 public void onClick(View view) {
106 ConnectivityManager cm =
107 (ConnectivityManager)LoginActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
108
109 assert cm != null;
110 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
111 boolean isConnected = activeNetwork != null &&
112 activeNetwork.isConnectedOrConnecting();
113
114 if(isConnected) {
115 pDialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.PROGRESS_TYPE);
116 pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
117 pDialog.setTitleText("Sincronizando");
118 pDialog.setCancelable(false);
119 pDialog.show();
120 forceSync();
121 } else {
122 new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
123 .setTitleText("Problema de Conexão!")
124 .setContentText("Não foi possível se conectar com a rede.")
125 .show();
126 }
127 }
128 };
129 }
130
131 private void clickBotaoIniciar() {
132 if (validateEnrollmentNumber(String.valueOf(enrollmentNumber.getText()))) {
133 Intent intent = new Intent(this, MainActivity.class);
134 startActivity(intent);
135 } else {
136 new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
137 .setTitleText("Oops...")
138 .setContentText("Matrícula de Operador não encontrada!")
139 .show();
140 }
141 }
142
143 private boolean validateEnrollmentNumber(String enrollmentNumber) {
144 String[] mSelectionArgs = {enrollmentNumber, "Operador"};
145 String mSelectionClause = ContributorEntry.COLUMN_ENROLLMENT + " = ? AND " + ContributorEntry.COLUMN_ROLE + " LIKE ?";
146 Cursor c = getContentResolver().query(ContributorEntry.CONTENT_URI, null, mSelectionClause, mSelectionArgs, null);
147 if(c != null && c.getCount() > 0) {
148 c.moveToFirst();
149 Contributor contributor = new Contributor();
150 contributor.setId(Integer.parseInt(c.getString(c.getColumnIndex(ContributorEntry.COLUMN_ID))));
151 contributor.setName(c.getString(c.getColumnIndex(ContributorEntry.COLUMN_NAME)));
152 SingletonStepSaver.getInstance().setContributor(contributor);
153 return true;
154 }
155 return false;
156 }
157
158 private boolean isFirstAccess() {
159 if (firstAccess == null) {
160 SharedPreferences mPreferences = this.getSharedPreferences("myprefs", Context.MODE_PRIVATE);
161 firstAccess = mPreferences.getBoolean("firstAccess", true);
162 if (firstAccess) {
163 SharedPreferences.Editor editor = mPreferences.edit();
164 editor.putBoolean("firstAccess", false);
165 editor.apply();
166 }
167 }
168
169 return firstAccess;
170 }
171
172 private void forceSync() {
173 syncImport("carriers");
174 syncImport("users");
175 syncImport("companies");
176 syncImport("buildings");
177 syncImport("services");
178 syncImport("shifts");
179 syncImport("vehicles");
180 pDialog.dismiss();
181 }
182
183 public void syncImport(final String model) {
184 AsyncHttpClient client = new AsyncHttpClient();
185 RequestParams params = new RequestParams();
186
187 String url = "http://srv206.teste.website/~supply/api/"+model;
188 Log.d("Teste", url);
189
190 client.post(url, params, new TextHttpResponseHandler() {
191
192 @Override
193 public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
194 if (statusCode == 404) {
195 Toast.makeText(LoginActivity.this, "Requested resource not found", Toast.LENGTH_LONG).show();
196 } else if (statusCode == 500) {
197 Toast.makeText(LoginActivity.this, "Something went wrong at server end", Toast.LENGTH_LONG).show();
198 } else {
199 Toast.makeText(LoginActivity.this, "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
200 Toast.LENGTH_LONG).show();
201 }
202 }
203
204 @Override
205 public void onSuccess(int statusCode, Header[] headers, String responseBody) {
206 update(model, responseBody);
207 }
208
209 });
210 }
211
212 public void update(String model, String response) {
213 try {
214 JSONArray jsonArray = new JSONArray(response);
215
216 if(model.equals("carriers")) {
217 syncCarriers(jsonArray);
218 } else if(model.equals("users")) {
219 syncContributors(jsonArray);
220 } else if(model.equals("companies")) {
221 syncCompanies(jsonArray);
222 } else if(model.equals("buildings")) {
223 syncBuilding(jsonArray);
224 } else if(model.equals("services")) {
225 syncServices(jsonArray);
226 } else if(model.equals("shifts")) {
227 syncShifts(jsonArray);
228 } else {
229 syncVehicles(jsonArray);
230 }
231 } catch (JSONException e) {
232 e.printStackTrace();
233 }
234 }
235
236 private void syncCarriers(JSONArray jsonArray) throws JSONException {
237 Map<Integer, Carrier> networkEntries = new HashMap<>();
238 JSONArray jsonCarriers = new JSONArray(jsonArray);
239 for (int i = 0; i < jsonCarriers.length(); i++) {
240 Carrier carrier = ParseObjects.parseCarrier(jsonCarriers.optJSONObject(i));
241 networkEntries.put(carrier.getId(), carrier);
242 }
243
244 Cursor c = getContentResolver().query(CarrierEntry.CONTENT_URI, null, null, null, null, null);
245 assert c != null;
246 c.moveToFirst();
247
248 int id;
249 String name;
250 Carrier found;
251
252 for (int i = 0; i < c.getCount(); i++) {
253
254 // Create local carrier entry
255 id = c.getInt(c.getColumnIndex(CarrierEntry.COLUMN_ID));
256 name = c.getString(c.getColumnIndex(CarrierEntry.COLUMN_NAME));
257
258 // Try to retrieve the local entry from network entries
259 found = networkEntries.get(id);
260 if (found != null) {
261 // The entry exists, remove from hash table to prevent re-inserting it
262 networkEntries.remove(id);
263
264 // Check to see if it needs to be updated
265 if (!name.equals(found.getName())) {
266 // Batch an update for the existing record
267 ContentValues carrier = new ContentValues();
268 carrier.put(CarrierEntry.COLUMN_NAME, found.getName());
269
270 String[] mSelectionArgs = {String.valueOf(id)};
271 String mSelectionClause = CarrierEntry.COLUMN_ID + " = ?";
272 getContentResolver().update(CarrierEntry.CONTENT_URI, carrier, mSelectionClause, mSelectionArgs);
273 }
274 } else {
275 // Entry doesn't exist, remove it from the local database
276 String[] mSelectionArgs = {String.valueOf(id)};
277 String mSelectionClause = CarrierEntry.COLUMN_ID + " = ?";
278 getContentResolver().delete(CarrierEntry.CONTENT_URI, mSelectionClause, mSelectionArgs);
279 }
280 c.moveToNext();
281 }
282 c.close();
283
284 // Add all the new entries
285 for (Carrier carrier : networkEntries.values()) {
286 ContentValues values = new ContentValues();
287
288 values.put(CarrierEntry.COLUMN_ID, carrier.getId());
289 values.put(CarrierEntry.COLUMN_NAME, carrier.getName());
290 getContentResolver().insert(CarrierEntry.CONTENT_URI, values);
291 }
292 }
293
294 private void syncContributors(JSONArray jsonArray) throws JSONException {
295 Map<Integer, Contributor> networkEntries = new HashMap<>();
296 JSONArray jsonContributors = new JSONArray(jsonArray);
297
298 for (int i = 0; i < jsonContributors.length(); i++) {
299 Contributor contributor = ParseObjects.parseContributor(jsonContributors.optJSONObject(i));
300 networkEntries.put(contributor.getId(), contributor);
301 }
302
303 Cursor c = getContentResolver().query(ContributorEntry.CONTENT_URI, null, null, null, null, null);
304 assert c != null;
305 c.moveToFirst();
306
307 int id;
308 String name;
309 String role;
310 String enrollment;
311 Contributor found;
312
313 for (int i = 0; i < c.getCount(); i++) {
314 // Create local contributor entry
315 id = c.getInt(c.getColumnIndex(ContributorEntry.COLUMN_ID));
316 name = c.getString(c.getColumnIndex(ContributorEntry.COLUMN_NAME));
317 role = c.getString(c.getColumnIndex(ContributorEntry.COLUMN_ROLE));
318 enrollment = c.getString(c.getColumnIndex(ContributorEntry.COLUMN_ENROLLMENT));
319
320 found = networkEntries.get(id);
321 if (found != null) {
322 networkEntries.remove(id);
323 if (!name.equals(found.getName()) || !role.equals(found.getRole()) || !enrollment.equals(found.getEnrollment())) {
324 ContentValues contributor = new ContentValues();
325 contributor.put(ContributorEntry.COLUMN_NAME, found.getName());
326 contributor.put(ContributorEntry.COLUMN_ROLE, found.getRole());
327 contributor.put(ContributorEntry.COLUMN_ENROLLMENT, found.getEnrollment());
328
329 String[] mSelectionArgs = {String.valueOf(id)};
330 String mSelectionClause = ContributorEntry.COLUMN_ID + " = ?";
331 getContentResolver().update(ContributorEntry.CONTENT_URI, contributor, mSelectionClause, mSelectionArgs);
332 }
333 } else {
334 String[] mSelectionArgs = {String.valueOf(id)};
335 String mSelectionClause = ContributorEntry.COLUMN_ID + " = ?";
336 getContentResolver().delete(ContributorEntry.CONTENT_URI, mSelectionClause, mSelectionArgs);
337 }
338 c.moveToNext();
339 }
340 c.close();
341
342 for (Contributor contributor : networkEntries.values()) {
343 ContentValues values = new ContentValues();
344
345 values.put(ContributorEntry.COLUMN_ID, contributor.getId());
346 values.put(ContributorEntry.COLUMN_NAME, contributor.getName());
347 values.put(ContributorEntry.COLUMN_ROLE, contributor.getRole());
348 values.put(ContributorEntry.COLUMN_ENROLLMENT, contributor.getEnrollment());
349 getContentResolver().insert(ContributorEntry.CONTENT_URI, values);
350 }
351 }
352
353 private void syncCompanies(JSONArray jsonArray) throws JSONException {
354 Map<Integer, Company> networkEntries = new HashMap<>();
355 JSONArray jsonCompanies = new JSONArray(jsonArray);
356 for (int i = 0; i < jsonCompanies.length(); i++) {
357 Company company = ParseObjects.parseCompany(jsonCompanies.optJSONObject(i));
358 networkEntries.put(company.getId(), company);
359 }
360
361 Cursor c = getContentResolver().query(CompanyEntry.CONTENT_URI, null, null, null, null, null);
362 assert c != null;
363 c.moveToFirst();
364
365 int id;
366 String name;
367 String color;
368 String city;
369 String state;
370 Company found;
371
372 for (int i = 0; i < c.getCount(); i++) {
373
374 // Create local company entry
375 id = c.getInt(c.getColumnIndex(CompanyEntry.COLUMN_ID));
376 name = c.getString(c.getColumnIndex(CompanyEntry.COLUMN_NAME));
377 color = c.getString(c.getColumnIndex(CompanyEntry.COLUMN_COLOR));
378 city = c.getString(c.getColumnIndex(CompanyEntry.COLUMN_CITY));
379 state = c.getString(c.getColumnIndex(CompanyEntry.COLUMN_STATE));
380
381 // Try to retrieve the local entry from network entries
382 found = networkEntries.get(id);
383 if (found != null) {
384 // The entry exists, remove from hash table to prevent re-inserting it
385 networkEntries.remove(id);
386
387 // Check to see if it needs to be updated
388 if (!name.equals(found.getName()) || !color.equals(found.getColor()) || !city.equals(found.getCity()) || !state.equals(found.getState())) {
389 // Batch an update for the existing record
390 ContentValues company = new ContentValues();
391 company.put(CompanyEntry.COLUMN_NAME, found.getName());
392 company.put(CompanyEntry.COLUMN_COLOR, found.getColor());
393 company.put(CompanyEntry.COLUMN_CITY, found.getCity());
394 company.put(CompanyEntry.COLUMN_STATE, found.getState());
395
396 String[] mSelectionArgs = {String.valueOf(id)};
397 String mSelectionClause = CompanyEntry.COLUMN_ID + " = ?";
398 getContentResolver().update(CompanyEntry.CONTENT_URI, company, mSelectionClause, mSelectionArgs);
399 }
400 } else {
401 // Entry doesn't exist, remove it from the local database
402 String[] mSelectionArgs = {String.valueOf(id)};
403 String mSelectionClause = CompanyEntry.COLUMN_ID + " = ?";
404 getContentResolver().delete(CompanyEntry.CONTENT_URI, mSelectionClause, mSelectionArgs);
405 }
406 c.moveToNext();
407 }
408 c.close();
409
410 // Add all the new entries
411 for (Company company : networkEntries.values()) {
412 ContentValues values = new ContentValues();
413
414 values.put(CompanyEntry.COLUMN_ID, company.getId());
415 values.put(CompanyEntry.COLUMN_NAME, company.getName());
416 values.put(CompanyEntry.COLUMN_COLOR, company.getColor());
417 values.put(CompanyEntry.COLUMN_CITY, company.getCity());
418 values.put(CompanyEntry.COLUMN_STATE, company.getState());
419 getContentResolver().insert(CompanyEntry.CONTENT_URI, values);
420 }
421 }
422
423 private void syncBuilding(JSONArray jsonArray) throws JSONException {
424 Map<Integer, Building> networkEntries = new HashMap<>();
425 JSONArray jsonBuildings = new JSONArray(jsonArray);
426
427 for (int i = 0; i < jsonBuildings.length(); i++) {
428 Building building = ParseObjects.parseBuilding(jsonBuildings.optJSONObject(i));
429 networkEntries.put(building.getId(), building);
430 }
431
432 Cursor c = getContentResolver().query(BuildingEntry.CONTENT_URI, null, null, null, null, null);
433 assert c != null;
434 c.moveToFirst();
435
436 int id;
437 String name;
438 int company_id;
439 Building found;
440
441 for (int i = 0; i < c.getCount(); i++) {
442 // Create local building entry
443 id = c.getInt(c.getColumnIndex(BuildingEntry.COLUMN_ID));
444 name = c.getString(c.getColumnIndex(BuildingEntry.COLUMN_NAME));
445 company_id = c.getInt(c.getColumnIndex(BuildingEntry.COLUMN_COMPANY));
446
447 // Try to retrieve the local entry from network entries
448 found = networkEntries.get(id);
449 if (found != null) {
450 // The entry exists, remove from hash table to prevent re-inserting it
451 networkEntries.remove(id);
452
453 // Check to see if it needs to be updated
454 if (!name.equals(found.getName()) || company_id != found.getCompany_id()) {
455 ContentValues building = new ContentValues();
456 building.put(BuildingEntry.COLUMN_NAME, found.getName());
457 building.put(BuildingEntry.COLUMN_COMPANY, found.getCompany_id());
458
459 String[] mSelectionArgs = {String.valueOf(id)};
460 String mSelectionClause = BuildingEntry.COLUMN_ID + " = ?";
461 getContentResolver().update(BuildingEntry.CONTENT_URI, building, mSelectionClause, mSelectionArgs);
462 }
463 } else {
464 String[] mSelectionArgs = {String.valueOf(id)};
465 String mSelectionClause = BuildingEntry.COLUMN_ID + " = ?";
466 getContentResolver().delete(BuildingEntry.CONTENT_URI, mSelectionClause, mSelectionArgs);
467 }
468 c.moveToNext();
469 }
470 c.close();
471
472 for (Building building : networkEntries.values()) {
473 ContentValues values = new ContentValues();
474
475 values.put(BuildingEntry.COLUMN_ID, building.getId());
476 values.put(BuildingEntry.COLUMN_NAME, building.getName());
477 values.put(BuildingEntry.COLUMN_COMPANY, building.getCompany_id());
478 getContentResolver().insert(BuildingEntry.CONTENT_URI, values);
479 }
480 }
481
482 private void syncServices(JSONArray jsonArray) throws JSONException {
483 Map<Integer, Service> networkEntries = new HashMap<>();
484 JSONArray jsonServices = new JSONArray(jsonArray);
485 for (int i = 0; i < jsonServices.length(); i++) {
486 Service service = ParseObjects.parseService(jsonServices.optJSONObject(i));
487 networkEntries.put(service.getId(), service);
488 }
489
490 Cursor c = getContentResolver().query(ServiceEntry.CONTENT_URI, null, null, null, null, null);
491 assert c != null;
492 c.moveToFirst();
493
494 int id;
495 String name;
496 Service found;
497
498 for (int i = 0; i < c.getCount(); i++) {
499
500 // Create local service entry
501 id = c.getInt(c.getColumnIndex(ServiceEntry.COLUMN_ID));
502 name = c.getString(c.getColumnIndex(ServiceEntry.COLUMN_NAME));
503
504 // Try to retrieve the local entry from network entries
505 found = networkEntries.get(id);
506 if (found != null) {
507 // The entry exists, remove from hash table to prevent re-inserting it
508 networkEntries.remove(id);
509
510 // Check to see if it needs to be updated
511 if (!name.equals(found.getName())) {
512 // Batch an update for the existing record
513 ContentValues service = new ContentValues();
514 service.put(ServiceEntry.COLUMN_NAME, found.getName());
515
516 String[] mSelectionArgs = {String.valueOf(id)};
517 String mSelectionClause = ServiceEntry.COLUMN_ID + " = ?";
518 getContentResolver().update(ServiceEntry.CONTENT_URI, service, mSelectionClause, mSelectionArgs);
519 }
520 } else {
521 // Entry doesn't exist, remove it from the local database
522 String[] mSelectionArgs = {String.valueOf(id)};
523 String mSelectionClause = ServiceEntry.COLUMN_ID + " = ?";
524 getContentResolver().delete(ServiceEntry.CONTENT_URI, mSelectionClause, mSelectionArgs);
525 }
526 c.moveToNext();
527 }
528 c.close();
529
530 // Add all the new entries
531 for (Service service : networkEntries.values()) {
532 ContentValues values = new ContentValues();
533
534 values.put(ServiceEntry.COLUMN_ID, service.getId());
535 values.put(ServiceEntry.COLUMN_NAME, service.getName());
536 getContentResolver().insert(ServiceEntry.CONTENT_URI, values);
537 }
538 }
539
540 private void syncShifts(JSONArray jsonArray) throws JSONException {
541 Map<Integer, Shift> networkEntries = new HashMap<>();
542 JSONArray jsonShifts = new JSONArray(jsonArray);
543 for (int i = 0; i < jsonShifts.length(); i++) {
544 Shift shift = ParseObjects.parseShift(jsonShifts.optJSONObject(i));
545 networkEntries.put(shift.getId(), shift);
546 }
547
548 Cursor c = getContentResolver().query(ShiftEntry.CONTENT_URI, null, null, null, null, null);
549 assert c != null;
550 c.moveToFirst();
551
552 int id;
553 String name;
554 Shift found;
555
556 for (int i = 0; i < c.getCount(); i++) {
557
558 // Create local shift entry
559 id = c.getInt(c.getColumnIndex(ShiftEntry.COLUMN_ID));
560 name = c.getString(c.getColumnIndex(ShiftEntry.COLUMN_NAME));
561
562 // Try to retrieve the local entry from network entries
563 found = networkEntries.get(id);
564 if (found != null) {
565 // The entry exists, remove from hash table to prevent re-inserting it
566 networkEntries.remove(id);
567
568 // Check to see if it needs to be updated
569 if (!name.equals(found.getName())) {
570 // Batch an update for the existing record
571 ContentValues shift = new ContentValues();
572 shift.put(ShiftEntry.COLUMN_NAME, found.getName());
573
574 String[] mSelectionArgs = {String.valueOf(id)};
575 String mSelectionClause = ShiftEntry.COLUMN_ID + " = ?";
576 getContentResolver().update(ShiftEntry.CONTENT_URI, shift, mSelectionClause, mSelectionArgs);
577 }
578 } else {
579 // Entry doesn't exist, remove it from the local database
580 String[] mSelectionArgs = {String.valueOf(id)};
581 String mSelectionClause = ShiftEntry.COLUMN_ID + " = ?";
582 getContentResolver().delete(ShiftEntry.CONTENT_URI, mSelectionClause, mSelectionArgs);
583 }
584 c.moveToNext();
585 }
586 c.close();
587
588 // Add all the new entries
589 for (Shift shift : networkEntries.values()) {
590 ContentValues values = new ContentValues();
591
592 values.put(ShiftEntry.COLUMN_ID, shift.getId());
593 values.put(ShiftEntry.COLUMN_NAME, shift.getName());
594 getContentResolver().insert(ShiftEntry.CONTENT_URI, values);
595 }
596 }
597
598 private void syncVehicles(JSONArray jsonArray) throws JSONException {
599 Map<Integer, Vehicle> networkEntries = new HashMap<>();
600 JSONArray jsonVehicles = new JSONArray(jsonArray);
601 for (int i = 0; i < jsonVehicles.length(); i++) {
602 Vehicle vehicle = ParseObjects.parseVehicle(jsonVehicles.optJSONObject(i));
603 networkEntries.put(vehicle.getId(), vehicle);
604 }
605
606 Cursor c = getContentResolver().query(VehicleEntry.CONTENT_URI, null, null, null, null, null);
607 assert c != null;
608 c.moveToFirst();
609
610 int id;
611 String name;
612 Boolean cart;
613 Vehicle found;
614
615 for (int i = 0; i < c.getCount(); i++) {
616
617 // Create local vehicle entry
618 id = c.getInt(c.getColumnIndex(VehicleEntry.COLUMN_ID));
619 name = c.getString(c.getColumnIndex(VehicleEntry.COLUMN_NAME));
620 cart = c.getInt(c.getColumnIndex(VehicleEntry.COLUMN_CART)) != 0;
621
622 // Try to retrieve the local entry from network entries
623 found = networkEntries.get(id);
624 if (found != null) {
625 // The entry exists, remove from hash table to prevent re-inserting it
626 networkEntries.remove(id);
627
628 // Check to see if it needs to be updated
629 if (!name.equals(found.getName()) || !cart.equals(found.getCart())) {
630 // Batch an update for the existing record
631 ContentValues vehicle = new ContentValues();
632 vehicle.put(VehicleEntry.COLUMN_NAME, found.getName());
633 vehicle.put(VehicleEntry.COLUMN_CART, found.getCart());
634
635 String[] mSelectionArgs = {String.valueOf(id)};
636 String mSelectionClause = VehicleEntry.COLUMN_ID + " = ?";
637 getContentResolver().update(VehicleEntry.CONTENT_URI, vehicle, mSelectionClause, mSelectionArgs);
638 }
639 } else {
640 // Entry doesn't exist, remove it from the local database
641 String[] mSelectionArgs = {String.valueOf(id)};
642 String mSelectionClause = VehicleEntry.COLUMN_ID + " = ?";
643 getContentResolver().delete(VehicleEntry.CONTENT_URI, mSelectionClause, mSelectionArgs);
644 }
645 c.moveToNext();
646 }
647 c.close();
648
649 // Add all the new entries
650 for (Vehicle vehicle : networkEntries.values()) {
651 ContentValues values = new ContentValues();
652
653 values.put(VehicleEntry.COLUMN_ID, vehicle.getId());
654 values.put(VehicleEntry.COLUMN_NAME, vehicle.getName());
655 values.put(VehicleEntry.COLUMN_CART, vehicle.getCart());
656 getContentResolver().insert(VehicleEntry.CONTENT_URI, values);
657 }
658 }
659}