简体   繁体   中英

Fill an ArrayList with object from response.body

I'm using retrofit to get list of data from api. I want to save the data which I get in body.response to arrayList. I can do that and I get the items from new arrayList, but it seems that the new list are not saved. When I try to use it outside of method onResponse, I get an error

Unable to start activity... IndexOutOfBoundsException: Index 0, Size 0

The interface

 public interface ServerApi {
        @Headers("Accept: application/json")
        @GET("cities")
        Call<ArrayList<City>> getCities();
    }

The activity

public class SomeActivity extends AppCompatActivity {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://url")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ServerApi serverApi = retrofit.create(ServerApi.class);

    ArrayList<City> cityList = new ArrayList<City>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parkings);

        final TextView tv1 = findViewById(R.id.tv1);

        final Call<ArrayList<City>> cities = serverApi.getCities();

        cities.enqueue(new Callback<ArrayList<City>>() {
            @Override
            public void onResponse(Call<ArrayList<City>> call, Response<ArrayList<City>> response) {
                for(int i=0; i<response.body().size(); i++){
                    City ct = new City(response.body().get(i).getId(), response.body().get(i).getName());
                    cityList.add(ct);
                    tv1.setText(cityList.get(i).getName());
                }
            }
            @Override
            public void onFailure(Call<ArrayList<City>> call, Throwable t) {
                tv1.setText("failure " + t);
            }
        });

      TextView c1 = findViewById(R.id.c1);
      c1.setText(cityList.get(0).getName());
    }
}

The string tv1.setText(cityList.get(i).getName()); inside the method onResponse works well. But when I write it out of the method, the aplication fall

As it can be seen you run your code in a background thread and a few lines below you try to update your textview on the UI thread.
The background operation will take some time, therefore, by the time you try to update the TextView the cityList is empty.
Consider reading a bit more here: Consuming apis with retrofit

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