0

I am trying to create an async task for my JsonArray, as it is skipping frames and lagging. I created an asyncTask class put in the parameters and i called my Json request in the do in background , however, how do I now reference my Json onresponse in my postexecute method?

class MyTask extends AsyncTask<URL,String,JSONArray> {
        @Override
        protected JSONArray doInBackground(URL... params) {
            JsonRequestMethod();

            return null;
        }

        @Override
        protected void onPostExecute(JSONArray response) {

        }
    }
}


private void JsonRequestMethod() {
            mVolleySingleton = VolleySingleton.getInstance();
            //intitalize Volley Singleton request key
            mRequestQueue = mVolleySingleton.getRequestQueue();
            //2 types of requests an Array request and an Object Request
            JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    listblogs.clear();
                    listblogs=parseJSONResponse(response);
                    mAdapterDashBoard.setBloglist(listblogs);


                    System.out.println("it worked!!!");
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            mRequestQueue.add(request);
    }
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
    if (!response.equals("")) {
        ArrayList<Blogs> blogsArrayList = new ArrayList<>();
        try {
            StringBuilder data = new StringBuilder();
            for (int i = 0; i < response.length(); i++) {
                JSONObject currentQuestions = response.getJSONObject(i);
                String text = currentQuestions.getString("text");
                String points = currentQuestions.getString("points");
                String ID=currentQuestions.getString("id");
                String studentId = currentQuestions.getString("studentId");
                String DateCreated=currentQuestions.getString("created");
                long time=Long.parseLong(DateCreated.trim());
                data.append(text + "\n" + points + "\n");
                System.out.println(data);
                Blogs blogs = new Blogs();
                blogs.setId(ID);
                blogs.setMstudentId(studentId);
                blogs.setMtext(text);
                blogs.setPoints(points);
                //The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
                blogs.setDateCreated(getTimeAgo(time));
                System.out.println(time+"time");


                listblogs.add(blogs);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return listblogs;
}
Eli
  • 827
  • 1
  • 7
  • 21

1 Answers1

3

Your volley request is already asynchronous, that's why it has listener interfaces like onResponse() and onErrorResponse(). You don't need it in the AsyncTask at all. Call your volley request from the UI thread, and use your AsyncTask to parse the JSON. For example:

  1. Call your volley request.
  2. In onResponse() from your volley request, create your AsyncTask to handle parsing.
  3. Parse the JSON in your doInBackground() method, "return" the result of the parsing.
  4. Your onPostExecute() will receive the parsing "result," and you can do what you want with it there.

To go even further, you could implement a listener interface for your AsyncTask as well, something like onJSONParsed(), then you could set logic in your UI thread (where you called your volley request), to handle the 100% finished response. For example:

class MyTask extends AsyncTask<URL,String,ArrayList<Blogs>> {
    // Listener member variable.
    private OnJSONParsedListener mOnJSONParsedListener;

    @Override
    protected ArrayList<Blog> doInBackground(URL... params) {
        // Parse JSON.
        ArrayList<Blogs> blogsList = parseJSON(response);

        // Pass the blogs list to the onPostExecute method.
        return blogsList;
    }

    @Override
    protected void onPostExecute(ArrayList<Blogs> blogsList) {
        // Invoke listener, if present.
        if (mOnJSONParsedListener != null)
            mOnJSONParsedListener.onJSONParsed(blogsList);
    }

    // Listener interface.
    public interface OnJSONParsedListener {
        void onJSONParsed(ArrayList<Blogs> blogsList);
    }

    // Setter for listener interface member variable.
    public void setOnJSONParsedListener(OnJSONParsedListener listener) {
        mOnJSONParsedListener = listener;
    }
}

Then in your UI thread.

// Call your volley request.
mVolleySingleton = VolleySingleton.getInstance();

//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();

//2 types of requests an Array request and an Object Request
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {
        // Create AsyncTask.
        MyTask parseJSONTask = new MyTask();

        // Set listener interface.
        parseJSONTask.setOnJSONParsedListener(new MyTask.OnJSONParsedListener() {
            @Override
            public void onJSONParsed(ArrayList<Blogs> blogsList) {
                // Do stuff with your blogs list.
                mAdapterDashBoard.setBloglist(blogsList);

                // It worked!
                System.out.println("it worked!!!");
            }
        }

        // Execute.
        parseJSONTask.execute(response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    }
});
mRequestQueue.add(request);

Hope this helps.

Andrew Senner
  • 2,479
  • 1
  • 18
  • 24