我正在使用Android Studio实施应用。
我有一个用例如下:
当用户点击导航抽屉时,我将片段膨胀为main_activity
因此,我从服务器获取所需的数据作为JSON并将其插入到SQLite中,然后我最终填充了片段
我使用AsyncTask类来读取JSON并插入数据
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;
}
}`
答案 0 :(得分:0)
最后,我用AsyncTask包装了onResponse方法的主体,解决了我的问题。