0

I'm trying to get this data from a rest API and show on Recycler view. I try to convert my JSON Object into an ArrayList, but I don't have success. My code returns this: [] Currently, I'm using Retrofit with POJO classes.

My JSON

//Header

ArrayList<Model> carsModels=new ArrayList<>();
private Adapter carsAdapter;


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

    RequestInteface requestInteface = retrofit.create(RequestInteface.class);
    Call<Model> call = requestInteface.getInteressJson();

    call.enqueue(new Callback<Model>() {
        @Override
        public void onResponse(Call<Model> call, Response<Model> response) {
            if(response.isSuccessful()){
                carsModels = new ArrayList<>(response.body().getModelList()); 
                carsAdapter = new Adapter(home.this, carsModels);
                cars_recyclerview.setAdapter(carsAdapter);
                Toast.makeText(home.this,"Success",Toast.LENGTH_SHORT).show();
            }
        }

    });

Model Class:

public class Model {
@SerializedName("name")
@Expose
private String name;
@SerializedName("audience_size")
@Expose
private String audience_size;
@SerializedName("topic")
@Expose
private String topic;
@SerializedName("path")
@Expose
private String path;
@SerializedName("description")
@Expose
private String description;

private List<Model> modelList = new ArrayList<>();


//Getter and setter

Request interface:

interface RequestInteface {
@GET("search.json")
Call<Model> getInteressJson();
}

1 Answer 1

1

You need parse "data" first, inside "data" contain List<Model> Create class InteressResponse

public class InteressResponse {
@SerializedName("data")
@Expose
private List<Model> modelList;

//Getter and setter
}
interface RequestInteface {
@GET("search.json")
Call<InteressResponse> getInteressJson();
}
public void onResponse(Call<InteressResponse> call, Response<InteressResponse> response) {
      if(response.isSuccessful()){
          carsModels = new ArrayList<>(response.body().getModelList()); 
          carsAdapter = new Adapter(home.this, carsModels);
          cars_recyclerview.setAdapter(carsAdapter);
          Toast.makeText(home.this,"Success",Toast.LENGTH_SHORT).show();
      }
}

Remove private List<Model> modelList = new ArrayList<>(); inside class Model

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

1 Comment

return this error: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference

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.