Лучший подход для вставки данных в БД SQLite, когда приложение работает в фоновом режиме? - PullRequest
0 голосов
/ 12 сентября 2018

Хорошо, поэтому я разрабатываю приложение, которое может получать push-сообщения от pushy.io и сохранять эти сообщения в БД SQLite, каждое сообщение имеет свою собственную функцию LOCK_OUT, UNLOCK, CHANGE_PIN и т. Д. Устройство получаетданные во время работы в фоновом режиме, но когда приложение открывается снова, оно не отображает внесенные изменения, однако, кажется, что оно не вставляет данные, пока приложение не будет убито и перезапущено?Пожалуйста, смотрите мой метод UpdateData ниже.

public class UpdateData {

    private final User user;
    private final List<CalendarInfo> calList;
    private final List<LockPlanChange>LockPlanList;
    private final List<TimeProfiles>timeProfilesList;
    private Context context;
    private final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.mainActivity);
    private final SharedPreferences.Editor editor = sp.edit();

    public UpdateData(Context con) {
        user = new User();
        calList = new ArrayList<>();
        LockPlanList = new ArrayList<>();
        timeProfilesList = new ArrayList<>();
        context = con;
    }
    public UpdateData() {
        user = new User();
        calList = new ArrayList<>();
        LockPlanList = new ArrayList<>();
        timeProfilesList = new ArrayList<>();
    }


    public void ParseAndCommit(String dataIn) throws JSONException {
        //starts everything off and then tries to commit
        dataParser(dataIn);
    }

    private void dataParser(String json) throws JSONException {



        //Remember it will be encrypted
        String firstSync;
        String messageid;
        String timeStamp;
        String type;
        JSONObject user;
        JSONObject key;
        JSONObject calendarinfo;
        JSONObject lockplanchg;
        JSONObject timeProfiles;

        //Selects the TYPE of Operation
        JSONObject jsonObjects = new JSONObject(json);

        messageid = jsonObjects.optString(JsonDataFields.MESSAGE_ID);
        timeStamp = jsonObjects.optString(JsonDataFields.TIME_STAMP);
        type = jsonObjects.optString(JsonDataFields.TYPE);
      //  type = "UPDATE";
        SharedPreferences sharedPref = context.getSharedPreferences("PUSH_DATA", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();


        switch (type)
        {

            case JsonDataFields.UPDATE:
                if(!timeStamp.isEmpty()) {
                    editor.putString("UPDATE_TIMESTAMP", timeStamp);
                    editor.apply();
                }
                ParseUpdateData(jsonObjects);
                SaveAck(messageid,JsonDataFields.UPDATE);
                SendAck(messageid,JsonDataFields.UPDATE);

                break;
            case JsonDataFields.NOTIFICATION:
                Log.d("eLOQ","NOTIFICATION");
                editor.putString(JsonDataFields.NOTIFICATION+"_TIMESTAMP", timeStamp);
                editor.commit();
                SaveAck(messageid,JsonDataFields.NOTIFICATION);
                SendAck(messageid,JsonDataFields.NOTIFICATION);
                break;
            case JsonDataFields.MESSAGE_TO_LONG:
                //perform full sync
                Log.d("eLOQ","MESSAGE_TO_LONG");
                editor.putString(JsonDataFields.MESSAGE_TO_LONG+"_TIMESTAMP", timeStamp);
                editor.commit();
                SaveAck(messageid,JsonDataFields.MESSAGE_TO_LONG);
                SendAck(messageid,JsonDataFields.MESSAGE_TO_LONG);
                break;
            case JsonDataFields.LOCK_OUT:


                //jsonObjects.getString(JsonDataFields.LOCK_OUT_INFO);
                Log.d("eLOQ","LOCK_OUT"+ jsonObjects.getString(JsonDataFields.LOCK_OUT_INFO));
                editor.putString(JsonDataFields.LOCK_OUT+"_TIMESTAMP", timeStamp);
                editor.commit();
                ParseLockOut(jsonObjects);
                android.os.Process.killProcess(android.os.Process.myPid());
                SaveAck(messageid,JsonDataFields.LOCK_OUT);
                SendAck(messageid,JsonDataFields.LOCK_OUT);


                break;
            case JsonDataFields.UNLOCK:
                Log.d("eLOQ","UNLOCK");
                editor.putString(JsonDataFields.UNLOCK+"_TIMESTAMP", timeStamp);
                editor.commit();
                AuthenticationOp auth = new AuthenticationOp(context);
                auth.updateLockOut("0","NULL");
                android.os.Process.killProcess(android.os.Process.myPid());
                SaveAck(messageid,JsonDataFields.UNLOCK);
                SendAck(messageid,JsonDataFields.UNLOCK);
                break;
            case JsonDataFields.KILL_SWITCH:
                Log.d("eLOQ","KILL_SWITCH");
                editor.putString(JsonDataFields.KILL_SWITCH+"_TIMESTAMP", timeStamp);
                editor.commit();
                SaveAck(messageid,JsonDataFields.KILL_SWITCH);
                SendAck(messageid,JsonDataFields.KILL_SWITCH);
                try {
                    // clearing app data
                    Runtime rt = Runtime.getRuntime();
                    rt.exec("pm clear com.dynamicaccesssolutions.eloq_app");

                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case JsonDataFields.REFRESH_SESSIONKEY:
                Log.d("eLOQS","REFRESH_SESSION_KEY");
                editor.putString(JsonDataFields.REFRESH_SESSIONKEY+"_TIMESTAMP", timeStamp);
                editor.commit();
                SaveAck(messageid,JsonDataFields.REFRESH_SESSIONKEY);
                SendAck(messageid,JsonDataFields.REFRESH_SESSIONKEY);
                break;
        }
        MainActivity.PushSyncing = false;

    }
    private void ParseLockOut(JSONObject job) throws JSONException {
        if(job.has(JsonDataFields.LOCK_OUT_INFO))
        {
            JSONObject causejson = job.getJSONObject(JsonDataFields.LOCK_OUT_INFO);
            String cause = causejson.getString(JsonDataFields.CAUSE);

            Log.d("LOCK_OUT","PIN_CHANGE");
            if(causejson.has(JsonDataFields.NEWPIN))
            {
                String newPin = causejson.getString(JsonDataFields.NEWPIN);
                AuthenticationOp auth = new AuthenticationOp(context);
                auth.updateLockOutandPin(newPin,"1",cause);
            }
            else
            {
                AuthenticationOp auth = new AuthenticationOp(context);
                auth.updateLockOut("1",cause);
            }


            //do stuff

           // if(job.has(JsonDataFields.))
        }
    }

    private void ParseUpdateData(JSONObject job) throws JSONException {
        percentUpdate(10);
        UserTableOp userOp = new UserTableOp(context);
        CalendarInfoOp calOp = new CalendarInfoOp(context);
        LockPlanChangeOp lockPlOp = new LockPlanChangeOp(context);
        TimeProfilesOp timeProOps = new TimeProfilesOp(context);
        AuthenticationOp authOp = new AuthenticationOp(context);

        String sysCode = job.optString(JsonDataFields.SYS_CODE);
        authOp.addSysCode(sysCode);
        if(job.has(JsonDataFields.USER) && job.has(JsonDataFields.KEY))
        {
            Log.d("eLOQ", "Storing user data");


            try {  percentUpdate(10);
                sleep(500);
                percentUpdate(20);
                sleep(500);
                percentUpdate(30);
                sleep(500);
                percentUpdate(40);
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            JSONObject userOb = job.getJSONObject(JsonDataFields.USER);
            user.set_user_id(userOb.getString(JsonDataFields.USER_ID));
            user.set_first_name(userOb.getString(JsonDataFields.FIRST_NAME));
            user.set_last_name(userOb.optString(JsonDataFields.LAST_NAME));
            user.set_phone(userOb.optString(JsonDataFields.PHONE));
            user.set_email(userOb.optString(JsonDataFields.EMAIL));
            user.set_key_id(userOb.getString(JsonDataFields.KEY_ID));
            user.set_key_mac(userOb.getString(JsonDataFields.KEY_MAC));

            JSONObject keyOb = job.getJSONObject(JsonDataFields.KEY);
            user.set_item_key_id(keyOb.getString(JsonDataFields.ITEM_KEY_ID));
            user.set_from_time(keyOb.getString(JsonDataFields.FROM_TIME));
            user.set_to_time(keyOb.getString(JsonDataFields.TO_TIME));
            user.set_validate_count(keyOb.getString(JsonDataFields.VALIDATE_COUNT));
            user.set_update_status(keyOb.getString(JsonDataFields.UPDATE_STATUS));
            user.set_calendar_id(keyOb.optString(JsonDataFields.CALENDAR_ID));

            if(!user.get_key_id().equals(keyOb.getString(JsonDataFields.KEY_ID)))
            {
                throw new JSONException("KeyID Miss-Match");
            }
            userOp.Update(user);
        }
        if(job.has(JsonDataFields.CALENDARS_INFO))
        {


            Log.d("eLOQ", "Storing calendar data");
            JSONObject calOb = job.getJSONObject(JsonDataFields.CALENDARS_INFO);
            String calID = calOb.getString(JsonDataFields.CALENDAR_ID);
            JSONArray days = new JSONArray(calOb.getString(JsonDataFields.DAYS));
            boolean drop_table = false;
            if(calID.equals("99999"))
            {
            //    drop_table = true;
                calOp.IsNullUpdate();
            }
            else {
                for (int i = 0; i < days.length(); i++) {
                    JSONObject subObject = days.optJSONObject(i);
                    String date_time = subObject.getString(JsonDataFields.DAY);
                    String setting = subObject.getString(JsonDataFields.SETTING);
                    calList.add(new CalendarInfo(calID, date_time, setting));
                }
                percentUpdate(50);

                calOp.Update(calList);
            }
        }
        if(job.has(JsonDataFields.LOCK_PLAN_CHG))
        {
            Log.d("eLOQ", "Storing lock data");
            JSONArray lockPlCh = new JSONArray(job.getString(JsonDataFields.LOCK_PLAN_CHG));
            boolean drop_table = false;
            percentUpdate(50);


            for(int i = 0; i < lockPlCh.length(); i++)
            {
                JSONObject subObject = lockPlCh.optJSONObject(i);
                String id = subObject.getString(JsonDataFields.LOCK_PLAN_ID);
                if(id.equals("99999")) {
                    drop_table = true;
                }else {
                    String flag = subObject.getString(JsonDataFields.FLAG);
                    String item_door_id = subObject.getString(JsonDataFields.ITEM_DOOR_ID);
                    String key_serial = subObject.getString(JsonDataFields.KEY_SERIAL);
                    String timezone_item_id = subObject.getString(JsonDataFields.TIMEZONE_ITEM_ID);
                    LockPlanList.add(new LockPlanChange(id,flag,item_door_id,key_serial,timezone_item_id));
                }
            }
            if(drop_table)
            {
                lockPlOp.NullUpdate();
            }else {

                lockPlOp.Update(LockPlanList);


            }
            //Add to db similar to this: lockPlanOperationHandler = new LockPlanOperationHandler(lockPlanList,db);
        }
        if(job.has(JsonDataFields.TIME_PROFILE))
        {
            Log.d("eLOQ", "Storing time profile data");
            JSONArray timeProfiles = new JSONArray(job.getString(JsonDataFields.TIME_PROFILE));
            for(int i = 0; i < timeProfiles.length(); i++)
            {

                String tziid = "";
                String serial = "";
                String to_time = "";
                String from_time = "";
                String monday = "";
                String tuesday = "";
                String wednesday = "";
                String thursday = "";
                String friday = "";
                String saturday = "";
                String sunday = "";
                String holiday = "";
                String special_day_one = "";
                String special_day_two = "";
                JSONObject subObject = timeProfiles.optJSONObject(i);
                String tzid = subObject.getString(JsonDataFields.TIMEZONE_ID);
                String tzitemid = subObject.getString(JsonDataFields.TIMEZONE_ITEM_ID);
                String tzname = subObject.getString(JsonDataFields.TIMEZONE_NAME);
                String colour = subObject.getString(JsonDataFields.COLOUR);
                if(subObject.has(JsonDataFields.TIME_PROFILE_SEGMENTS))
                {
                    JSONArray timeProfileSegments = new JSONArray(subObject.getString(JsonDataFields.TIME_PROFILE_SEGMENTS));
                    percentUpdate(60);
                    for(int x = 0; x < timeProfileSegments.length(); x++)
                    {
                        JSONObject arrayObject = timeProfileSegments.optJSONObject(x);
                        tziid = arrayObject.getString(JsonDataFields.TIMEZONE_IID);
                        serial = arrayObject.getString(JsonDataFields.SERIAL);
                        List<String> timeSegList = Arrays.asList(arrayObject.getString(JsonDataFields
                                .TIME_SLICE).split(";"));

                        for (int j = 0; j < timeSegList.size(); j++)
                        {

                            switch (j)
                            {
                                case 0:
                                    from_time = timeSegList.get(j);
                                    break;
                                case 1:
                                    to_time = timeSegList.get(j);
                                    break;
                                case 2:
                                    monday = timeSegList.get(j);
                                    break;
                                case 3:
                                    tuesday = timeSegList.get(j);
                                    break;
                                case 4:
                                    wednesday = timeSegList.get(j);
                                    break;
                                case 5:
                                    thursday = timeSegList.get(j);
                                    break;
                                case 6:
                                    friday = timeSegList.get(j);
                                    break;
                                case 7:
                                    saturday = timeSegList.get(j);
                                    break;
                                case 8:
                                    sunday = timeSegList.get(j);
                                    break;
                                case 9:
                                    holiday = timeSegList.get(j);
                                    break;
                                case 10:
                                    special_day_one = timeSegList.get(j);
                                    break;
                                case 11:
                                    special_day_two = timeSegList.get(j);
                                    break;
                            }
                            timeProfilesList.add(new TimeProfiles(tziid, tzid,  serial, from_time,
                                    to_time, monday, tuesday,  wednesday,  thursday,
                                    friday,saturday, sunday, holiday,  special_day_one,
                                    special_day_two, tzitemid, tzname,  colour));
                        }


                    }

                }
                else{
                    timeProfilesList.add(new TimeProfiles(tziid, tzid,  serial, from_time,
                            to_time, monday, tuesday,  wednesday,  thursday,
                            friday,saturday, sunday, holiday,  special_day_one,
                            special_day_two, tzitemid, tzname,  colour));



                }

            }
            timeProOps.Update(timeProfilesList);


        }

        Log.d("PARSE_AND_COMMIT", "COMPLETED");
    }
    private void SendAck(String messageID,String type)
    {

        percentUpdate(70);

        AuthenticationOp authOp = new AuthenticationOp(context);
        List<String> headers = authOp.getHeaders();

        //  SharedPreferences sharedPref = MainActivity.mainActivity.getPreferences(Context.MODE_PRIVATE);
         // String userid = sharedPref.getString("userid","");

        createTrustManager();
        HttpURLConnection urlConnection;
        String response;
        //createTrustManager();
        try {//https://eloqServerUKa.cloudapp.net/KMS_RESTful/Service.svc/json/Phone
            URL url = new URL(RestFUL_URLS.SEND_ACK+messageID);
            // Setting up the headers
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("projectid", headers.get(0));//////this is here for testing//headers.get(0)
            urlConnection.setRequestProperty("uniqueid",  headers.get(1));
            urlConnection.setRequestProperty("hardwareid",  headers.get(2));
            urlConnection.setRequestProperty("devicetype", headers.get(3));
            //   urlConnection.setRequestProperty("userid", "232cb28cb2f34f9e8175420b165a3700");
            try {
                sleep(500);
                percentUpdate(80);
                sleep(500);
                percentUpdate(90);
                sleep(500);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            urlConnection.setRequestMethod("POST");
            int statusCode = urlConnection.getResponseCode();

        /* 200 represents HTTP OK */



            if (statusCode == 200) {
                Log.i("Server Responce", "STATUS CREATED");
                ResetPrefs(context,type);
                //================================================================================
            } else if (statusCode == 406) {
                Log.i("Server Responce", "Server Error");

            }




        }catch (IOException e){e.printStackTrace();

        }

        percentUpdate(100);

    }
    private void SaveAck(String messageID,String type)
    {

        SharedPreferences sharedPref = context.getSharedPreferences("PUSH_DATA", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("SAVED_ACK_"+type, messageID);
        editor.apply();
    }
    private void ResetPrefs(Context _context,String type)
    {
        Log.d("eLOQ", "Reset prefs");
        SharedPreferences sharedPref = _context.getSharedPreferences("PUSH_DATA", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("SAVED_ACK_"+type, "");
        editor.apply();




    }
    private void createTrustManager() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {

            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {

            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }
        };

        // Install the all-trusting trust manager
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        try {
            assert sc != null;
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }


    private void percentUpdate(int per){

        editor.putInt("percent",  per);
        editor.commit();

      //  toast();
    }
   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...