简体   繁体   中英

Can't update arraylist after API call in Android Studio

I am trying to sort an arraylist in alphabetical order after it has been retrieved from the API call:

StarWarsApi.init();
StarWars api = StarWarsApi.getApi();
m_vwPeopleLayout.setAdapter(m_peopleAdapter);

api.getAllPeople(i, new Callback<SWModelList<People>>() {
    @Override
    public void success(SWModelList<People> planetSWModelList, Response response) {
        for (People p : planetSWModelList.results) {
            peopleArrayList.add(p);
        }
    }

    @Override
    public void failure(RetrofitError error) {
        System.out.print("failure");
    }
});

//code to sort arrayList

m_peopleAdapter.notifyDataSetChanged();

The code to sort the list and update the Adapter gets ran, but before the API call is finished. I'm guessing this is caused by the thread not finishing in time. I've tried putting a sleep statement before sorting but it seems that pauses the entire activity. How can I wait until the API call is finished before running more code?

m_peopleAdapter.notifyDataSetChanged();

should be in your Api-Callback like this

api.getAllPeople(i, new Callback<SWModelList<People>>() {
@Override
public void success(SWModelList<People> planetSWModelList, Response response) {
    for (People p : planetSWModelList.results) {
        peopleArrayList.add(p);
    }
    m_peopleAdapter.notifyDataSetChanged();
}

@Override
public void failure(RetrofitError error) {
    System.out.print("failure");
}
});

You need to notify the adapter after the dataset was changed. Your code triggered the notification just after the call was started.

How can I wait until the API call is finished before running more code?

Use success method is called on UI Thread when request is finished. do all Adapter setting or call notifyDataSetChanged inside success method to update Adapter data after getting it from API:

@Override
    public void success(....) {
        for (People p : planetSWModelList.results) {
            peopleArrayList.add(p);
        }
        // call notifyDataSetChanged here
        m_peopleAdapter.notifyDataSetChanged();
    }

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