简体   繁体   中英

How do I set an Async Task for this code?

I am having trouble with my listblogs=parseJSONResponse(result), result is underlined red and if I hover over it it says that, I cannot apply a parseJsonResponse JSONARRAY to a JSONARRAY[]. Does anyone know why this is being caused does it have something to do with the params?

class YourTask extends AsyncTask<JSONArray, String, ArrayList<Blogs> > {

    @Override
    protected ArrayList<Blogs> doInBackground(JSONArray... result) {
        listblogs.clear(); // here you clear the old data
        listblogs=parseJSONResponse(result);
        return listblogs;
    }

    @Override
    protected void onPostExecute(ArrayList<Blogs> blogs) {
        mAdapterDashBoard.setBloglist(listblogs);
    }
}



private void JsonRequestMethod() {
    final long start = SystemClock.elapsedRealtime();
            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) {
                    System.out.print(response);
                    listblogs = new YourTask().doInBackground();
                    listblogs.clear();
                             listblogs=parseJSONResponse(response);
                    try {
                        listblogs = new YourTask().execute().get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

                    System.out.println(response);
                            Log.d("Testing", "Time elapsed: " + (SystemClock.elapsedRealtime() - start));
                    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("")) {
        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;
}

you can run any code inside an async task like this:

public class YourTask extends AsyncTask<String, Void, ArrayList<Blogs> > {

    private static final String TAG = YourTask.class.getSimpleName();

    private JSONArray mResponse;
    private Activity mActivity;

    public YourTask(final Activity activity, final JSONArray response) {
        super();
        this.mActivity = activity;
        this.mResponse = response;
    }

    @Override
    protected ArrayList<Blogs>  doInBackground(String... params) {

        if (!mResponse.equals("")) {
               // Your Code
        }   
        return listblogs;

    }

    @Override
    protected void onPostExecute(final ArrayList<Blogs> blogs) {

            if (mActivity instanceOf YourActivity) {
                ((YourActivity) activity).finishTask(blogs);
            }
    }

    @Override
    protected void onCancelled() {}
}

call this Task from your activity like:

AsyncTask<String, Void, JSONArray> task = new YourTask(this, response);
        task.executeContent();

Basically just send the JSONArray you want to parse to the Async Task and handle all the UI in den finishTask method in your Activity. The advantage is that you can extract your task in an extra file and leave your activity to just handle controlling your views.

AsyncTask

public class MyAsyncTask extends AsyncTask<Void, Void, ArrayList> {
         JsonArray myJsonArray;
   @Override
    protected void onPreExecute() {
        super.onPreExecute();

            mVolleySingleton = VolleySingleton.getInstance();

            mRequestQueue = mVolleySingleton.getRequestQueue();

            listblogs.clear();

        }
        @Override
        protected ArrayList doInBackground(Void... params) {


            JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    myJsonArray = response;

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            mRequestQueue.add(request);
            return null;
        }

        @Override
        protected void onPostExecute(ArrayList arrayList) {
            super.onPostExecute(arrayList);

              ArrayList<Blogs> blogsArrayList = new ArrayList<>();
    try {
        StringBuilder data = new StringBuilder();
        for (int i = 0; i < myJsonArray.length(); i++) {
            JSONObject currentQuestions = myJsonArray.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");


            blogsArrayList.add(blogs);
            }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return blogsArrayList;

    }

ArrayList

synchronous:

  listblogs = new MyAsyncTask().execute().get();

asynchronous:

   ....
      } catch (JSONException e) {
            e.printStackTrace();
        }
        listblogs = blogsArrayList;
        return blogsArrayList;

        }
new MyAsyncTask().execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM