Popular Listview with Retrofit2 Data

Asked

Viewed 169 times

1

I’m trying to pupate a listview with information I get from WS through Retrofit2. But error somewhere and nothing is presented, neither error nor listview. can give me a strength for kindness.

Follow the code section.

    //inicio um Array list vazio
    list = new ArrayList<Course>();

    //configuro o Retrofit
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(CoursesInterface.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    CoursesInterface service = retrofit.create(CoursesInterface.class);


    Call<UdacityCatelog> requestCatalog =  service.listCatalog();


    //Metodo Assicrono
    requestCatalog.enqueue(new Callback<UdacityCatelog>() {
        @Override
        public void onResponse(Call<UdacityCatelog> call, Response<UdacityCatelog> response) {
            //verifico se esta tendo resposta
            if(!response.isSuccessful()){
                Log.i("Code", "Codigo: "+ response.code());
            }else{
                UdacityCatelog catalogo = response.body();
                for(Course c : catalogo.courses ){
                    //Verifico no log se as informações estão ok!
                    Log.i("Code", "course: "+ c.title);
                    //Adiciono a uma ListView
                    list.add(c);


                }
            }
        }

        @Override
        public void onFailure(Call<UdacityCatelog> call, Throwable t) {
            //Case de erro!
            Log.i("Code", "Codigo: "+ t.getMessage());
        }
    });


    //Vinculo a ListView
    listaItem = (ListView) findViewById(R.id.listItem);
    //configuro o adapter
    adapter = new ArrayAdapter<>(
            this,
            android.R.layout.simple_list_item_1,
            list
    );
    //Seto o Adapter
    listaItem.setAdapter(adapter);

1 answer

2


Try it this way:

public void onResponse(Call<UdacityCatelog> call, Response<UdacityCatelog> response) {
            //verifico se esta tendo resposta
            if(!response.isSuccessful()){
                Log.i("Code", "Codigo: "+ response.code());
            }else{
                UdacityCatelog catalogo = response.body();
                for(Course c : catalogo.courses ){
                    //Verifico no log se as informações estão ok!
                    Log.i("Code", "course: "+ c.title);
                    //ADICIONE NO ADAPTER
                    adapter.add(c);


                }
              //NOTIFIQUE AS ALTERACOES
              adapter.notifyDataSetChanged();
            }
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.