0

I send POST request and get JSON object. I have parsed it, but when I'm trying to add it to the ArrayList for RecyclerView, I get 0 size of ArrayList. My AsyncTask:

new AsyncTask<Void, Void, Void>() {
            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(LectorsListActivity.this, null, "Please Wait", true, false);
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    LoginLectorUtils httpUtils = new LoginLectorUtils();
                    String name, uniqueId, photoUrl;
                    JSONArray array = new JSONArray(httpUtils.sendPostRequest(REQUEST_URL));

                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);

                        name = jsonObject.getString("name");
                        uniqueId = jsonObject.getString("unique_id");
                        photoUrl = jsonObject.getString("photo_url");

                        //if (!name.equals("") && !uniqueId.equals("") && !photoUrl.equals("")) {
                            data.add(new LectorsDataModel(name, uniqueId, photoUrl)); // Here i'm adding new items
                        //}
                    }

                } catch (Exception e) {
                    Log.e("LectorsListActivity", "Can't create JSONArray");
                }

                return null;
            }

            @Override
            protected void onPostExecute(final Void str) {
                super.onPostExecute(str);
                loading.dismiss();
            }
        }.execute();

        //data = new ArrayList<LectorsDataModel>();
        //data.add(new LectorsDataModel("", "", ""));

        Toast.makeText(LectorsListActivity.this, Integer.toString(data.size()), Toast.LENGTH_SHORT).show(); // Shows 0

        adapter = new LectorsAdapter(data, this);
        recyclerView.setAdapter(adapter);
1
  • you need to get familiar with what async means in asynctask. Commented Feb 4, 2016 at 23:13

2 Answers 2

1

You code is being executed before you get the result because you are finding the size before data is available.

You have two solutions here

Solution 1

Add

Toast.makeText(LectorsListActivity.this, Integer.toString(data.size()), Toast.LENGTH_SHORT).show(); // Shows 0
adapter = new LectorsAdapter(data, this);
recyclerView.setAdapter(adapter);

inside onPostExecute() method.

Solution 2

Add

adapter.notifyDataSetChanged();

inside onPostExecute() method.

And put

adapter = new LectorsAdapter(data, this);

before calling the AsyncTask

Sign up to request clarification or add additional context in comments.

2 Comments

You can as I have mentioned in Solution 2, but you will have to tell the adapter that data is available and now you can refresh.
@Rohit5k2, Solution 2 not working, I am getting NullPointer
0

You can also try use RxAndroid (+optional Retrolambda). Check below example which should target yout problem aswell.

Create observable which will emit your items:

    rx.Observable<List<Item>> fetchItems() {
    return Observable.create(
        subscriber -> {
            try {
                Thread.sleep(2000); //simulate long operation
                subscriber.onNext(yourItems());
            } catch (InterruptedException e) {
                subscriber.onError(e);
            }
        }
    );
}

and subscribe to it:

    Subscription subscription = fetchItems()
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSubscribe(() -> mProgressDialog = ProgressDialog.show(getContext(), "Progress", "Please Wait", true))
        .doOnTerminate(this::dismissProgressDialog)
        .subscribe(
            items -> {
                recyclerView.setAdapter(new SimpleAdapter(items));
                dismissProgressDialog();
            },
            e -> Log.e("onError", e.getMessage())
        );

Code in 'Observable.create' will be executed in new thread, rest in Android UI thread.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.