AsyncTask使我的应用程序变慢

时间:2017-11-29 12:38:38

标签: android android-asynctask

我正在使用loadRecycleViewData()函数调用API以便最初显示小数据。并AsyncTask在后​​台进程中调用整月数据。现在应用程序变得更慢,需要等待2-3秒,直到AsyncTask加载整月数据。提供解决方案此代码中需要进行哪些更改。

注意:loadRecycleViewData()函数执行的操作与AsyncTask相同。因为我需要在应用程序第一次打开时初始显示内容。

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_name);
    //CHECK NETWORK CONNECTION
    connectivityManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
    network = connectivityManager.getActiveNetworkInfo();
    if(network != null && network.isConnected()){
    loadRecycleViewData(getFirstDayDatesCurrentMonth(), getLastDayDatesCurrentMonth());
    new ApiRequest().execute(); //HERE ASYNCTASK CALLED TO FETCH DATA FROM API

}}

//loadRecycleViewData() function
private void loadRecycleViewData(final String start, final String end) {
    String URL_DATA = "https://api.example.com/calendar&f=json";
    //Log.e("URL_DATA",""+URL_DATA);
    realm = Realm.getDefaultInstance();
    final RealmHelperCalendar helper = new RealmHelperCalendar(realm);

    StringRequest stringRequest = new StringRequest(Request.Method.GET,
            URL_DATA,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        for(int i = 0; i < jsonArray.length(); i++){
                            //SET DATA
                            Calendar calendar = new Calendar();

                            JSONObject o = jsonArray.getJSONObject(i);
                            String CalendarId = o.getString("CalendarId");
                            String Date = o.getString("Date");

                            String[] separated = Date.split("T");
                            String inputDateFormat = separated[0] + " " + separated[1];
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                            Date result =  df.parse(inputDateFormat);
                            Long milisecond = getMiliSecondFromDate(inputDateFormat);

                            calendar.setId(CalendarId);
                            calendar.setDate(result);

                            helper.save(calendar)); //SAVE IN REALM DB
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener(){

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

//AsyncTask Background Function
@Override
protected String doInBackground(String... strings) {

    realm = Realm.getDefaultInstance();

    String URL_DATA = "https://api.example.com/calendarf=json";
    final RealmHelperCalendar helper = new RealmHelperCalendar(realm);
    try {

        URL url = new URL(URL_DATA);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.connect();

        BufferedReader bufR = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String response = bufR.readLine();


        JSONArray jsonArray = new JSONArray(response);
        for(int i = 0; i < jsonArray.length(); i++){

            Calendar calendar = new Calendar();
            JSONObject o = jsonArray.getJSONObject(i);
            String CalendarId = o.getString("CalendarId");
            String Date = o.getString("Date");

            String[] separated = Date.split("T");
            String inputDateFormat = separated[0] + " " + separated[1];
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
            java.util.Date result =  df.parse(inputDateFormat);
            Long milisecond = getMiliSecondFromDate(inputDateFormat);

            calendar.setId(CalendarId);
            calendar.setDate(result);

            helper.save(calendar)); //SAVE IN REALM DB
        }
    } catch (Exception e)
    {
        System.out.println(e);
    }
    return null;
}

0 个答案:

没有答案