I'm implementing an app with Android Studio.
I have a use case as below:
When a user clicks on navigation drawer, I inflate a Fragment into main_activity.
So, I get the needed data from a server as JSON and insert it into SQLite and I finally populate the Fragment.
I used an AsyncTask Class to read the JSON and insert the data
public class AsyncTaskRunner extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
Log.i(TAG, "doInBackground");
queue = VolleySingleton.getInstance().getRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
Constants.URL_ADVERTISEMENTS,
new Response.Listener<String>() {
@Override
public void onResponse(final String response) {
try {
jsonArray = new JSONArray(response);
writeDataToDB();
loadDataFromLocalDataBase();
SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
SharedPreferences setting = getActivity().getSharedPreferences(Constants.SETTING_NAME, Context.MODE_PRIVATE);
Calendar calendar = Calendar.getInstance();
SharedPreferences.Editor editor = setting.edit();
String now = dateFormat.format(calendar.getTime());
editor.putString(Constants.LAST_ADVERTISEMENT_SYNC_DATE, now);
editor.commit();
} catch (Exception e) {
Log.e(TAG, "DEVELOPER:" + e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse occured :" + error.getMessage());
}
});
stringRequest.setTag(TAG);
queue.add(stringRequest);
} catch (Exception e) {
Log.e(TAG, "Load data has error:" + e.getMessage());
}
return null;
}
}`