Ошибка в привязке данных RecyclerView во фрагменте, и я использую два Recycleriew внутри фрагмента - PullRequest
0 голосов
/ 15 декабря 2018

У меня есть один фрагмент, включенный два утилита-ретранслятора, один статический, а другой динамический, первый - горизонтальный, а второй - вертикальный. Я использую модификацию и получаю сообщение об ошибке в методе onResponse при привязке списка к ответу.

  public void getBusinessList() {
    ApiInterface apiInterface = NetworkClient.getRetrofitClient().create(ApiInterface.class);
    Call<List<Businesses>> call = apiInterface.getMovie();
    call.enqueue(new Callback<List<Businesses>>() {
        @Override
        public void onResponse(Call<List<Businesses>> call, Response<List<Businesses>> response) {

            if (response==null){
                Toast.makeText(getActivity(), "Somthing Went Wrong...!!", Toast.LENGTH_SHORT).show();
            }else{

                businessesList.addAll(response.body());
                Log.i("RESPONSE: ", ""+response.toString());
            }
            productAdapter.notifyDataSetChanged();
        }

        @Override
        public void onFailure(Call<List<Businesses>> call, Throwable t) {
            Toast.makeText(getActivity(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
            Log.e("ERROR: ", t.getMessage());
        }
    });
}

Я получаю сообщение об ошибке:

 businessesList.addAll(response.body());

и ошибка Logcat:

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

мой класс модели:

public class Businesses {

@SerializedName("code")
private Integer code;
@SerializedName("long_message")
private String longMessage;
@SerializedName("short_message")
private String shortMessage;
@SerializedName("data")
private Data data;

public Integer getCode() {
    return code;
}

public void setCode(Integer code) {
    this.code = code;
}

public String getLongMessage() {
    return longMessage;
}

public void setLongMessage(String longMessage) {
    this.longMessage = longMessage;
}

public String getShortMessage() {
    return shortMessage;
}

public void setShortMessage(String shortMessage) {
    this.shortMessage = shortMessage;
}

public Data getData() {
    return data;
}

public void setData(Data data) {
    this.data = data;
}

}

и интерфейс:

public interface ApiInterface {
@GET("/businesses")
Call<List<Businesses>> getMovie();

}

мой ответ такой:

{
"code": 200,
"long_message": "The request was successful and the response body contains the representation requested.",
"short_message": "Record found successfully",
"data": {
    "status": true,
    "count": 8,
    "businesses": [
        {
            "id": 30,
            "title": "best auto body",
            "phone": "4104287884",
            "mobile": null,
            "address": "3600 Dolfield Avenue, Baltimore, MD, USA",
            "lat": "39.3364806",
            "lng": "-76.6752669",
            "category": "Painting",
            "review_ratings": null,
            "total_reviews": "0",
            "avg_rating": null,
            "already_fav": "0",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/9ICJ2FFTCwmYVWMsL4qAMXf9ZltREs5Ku1JsIrNK.jpeg"
        },
        {
            "id": 11,
            "title": "Corrib Moving & Storage",
            "phone": null,
            "mobile": null,
            "address": "Dallas, TX, USA",
            "lat": "32.7766642",
            "lng": "-96.79698789999998",
            "category": "Handyman",
            "review_ratings": null,
            "total_reviews": "0",
            "avg_rating": null,
            "already_fav": "1",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/s8SQG1Mm1gNLd4uOdU59OzFxDy51N7l7RaJtzbgu.png"
        },
        {
            "id": 10,
            "title": "NorthStar Moving Company",
            "phone": null,
            "mobile": null,
            "address": "Des Moines International Airport (DSM), Fleur Drive, Des Moines, IA, USA",
            "lat": "41.53413330000001",
            "lng": "-93.65879580000001",
            "category": "Handyman",
            "review_ratings": null,
            "total_reviews": "0",
            "avg_rating": null,
            "already_fav": "1",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/fVeQMzZvikHzzvkKwjkghsRKD7wPGC5D7xnIov9M.jpeg"
        },
        {
            "id": 9,
            "title": "Marcio",
            "phone": null,
            "mobile": null,
            "address": "United States Botanic Garden, Maryland Avenue Southwest, Washington, DC, USA",
            "lat": "38.8881451",
            "lng": "-77.0128833",
            "category": "Painting",
            "review_ratings": null,
            "total_reviews": "0",
            "avg_rating": null,
            "already_fav": "1",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/STnuOafrVQUM1z4hBDDUGTc7bnBNiEoZ6DVvQSaM.jpeg"
        },
        {
            "id": 8,
            "title": "Fast Response Plumbing & Rooter",
            "phone": null,
            "mobile": null,
            "address": "Des Moines International Airport (DSM), Fleur Drive, Des Moines, IA, USA",
            "lat": "41.53413330000001",
            "lng": "-93.65879580000001",
            "category": "Plumbing",
            "review_ratings": null,
            "total_reviews": "0",
            "avg_rating": null,
            "already_fav": "0",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/qFsye8cOx8kSeJH9kwHAZG2muf2q74BrTHYV9X80.jpeg"
        },
        {
            "id": 7,
            "title": "Apollo Heating & Ventilating",
            "phone": null,
            "mobile": null,
            "address": "Square One Shopping Centre, City Centre Drive, Mississauga, ON, Canada",
            "lat": "43.5926695",
            "lng": "-79.6427339",
            "category": "Electricity",
            "review_ratings": null,
            "total_reviews": "0",
            "avg_rating": null,
            "already_fav": "1",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/0NfvQ9689mjksRqw7ThjMGx7y73zyvScwTvEAsCX.jpeg"
        },
        {
            "id": 6,
            "title": "Ike’s Electric",
            "phone": null,
            "mobile": null,
            "address": "E.W.R. (EWR), Brewster Road, Newark, NJ, USA",
            "lat": "40.68953140000001",
            "lng": "-74.17446239999998",
            "category": "Electricity",
            "review_ratings": "1_5.0000",
            "total_reviews": "1",
            "avg_rating": "5.0000",
            "already_fav": "1",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/CH6XSVuiOD9rT7pS5XUAO4IPOST89jYtPcfiA9vT.jpeg"
        },
        {
            "id": 3,
            "title": "Associated Heating",
            "phone": null,
            "mobile": null,
            "address": "United States Capitol, Washington, DC, USA",
            "lat": "38.8899389",
            "lng": "-77.0090505",
            "category": "A/C",
            "review_ratings": null,
            "total_reviews": "0",
            "avg_rating": null,
            "already_fav": "1",
            "image": "http://karobarlist.xtechnos.com/storage/app/public/business/2mKtZEP82sNwfZx8UWuRnaDnAbDozWW75npRQ22k.jpeg"
        }
    ]
}

}

Яя получаю сообщение об ошибке в методе OnResponse, поэтому я надеюсь, что класс модели работает нормально, спасибо, заранее буду признателен за ваш ответ

1 Ответ

0 голосов
/ 15 декабря 2018

Вы проверяете, является ли ответ нулевым, но не является ли список предприятий, извлеченных из ответа, нулевым.Так что вам нужно также проверить список предприятий.Попробуйте это:

call.enqueue(new Callback<List<Businesses>>() {
    @Override
    public void onResponse(Call<List<Businesses>> call, Response<List<Businesses>> response) {

        if (response==null){
            Toast.makeText(getActivity(), "Somthing Went Wrong...!!", Toast.LENGTH_SHORT).show();
        } else if (response.body()==null){
            Toast.makeText(getActivity(), "Something Went Wrong. List is empty!!", Toast.LENGTH_SHORT).show();
        }else{
            businessesList.addAll(response.body());
            Log.i("RESPONSE: ", ""+response.toString());
        }
        productAdapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(Call<List<Businesses>> call, Throwable t) {
        Toast.makeText(getActivity(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
        Log.e("ERROR: ", t.getMessage());
    }
});
...