Search code examples
androidperformancebackground-process

Best approach to get data from server and save it to in local DB?


I am downloading data from server and storing it in local sqlite db.i want know which is the best approach to do this so that my app ui thread will not get freeze. Currently i m using volley and app gets freeze sometime and i get log too "skip frames". Thanks.


Solution

  • In Volley, onResponse and onErrorResponse is called on UI thread. So please move you parsing logic into parseNetworkResponse (as this is done in background thread) or you can use Executors (or ExecutorServices depending on your use case) or AsyncTask to switch the threads once you receive the response in OnResponse and save the data in the local DB like shown below.

    public void onResponse(JSONObject response) {
         Executor executor = Executors.newSingleThreadExecutor();
         executor.execute(() -> 
            // your database code 
         );       
    }
    

    or

    public void onResponse(JSONObject response) {
         AsyncTask.execute(new Runnable() {
            public void run() {
               // your database code 
           }
        });      
    }