Francesca Infranca
Francesca Infranca

Reputation: 9

JSON onResponse - List will not populate with data

I am getting a working app (kinda). It is meant to populate the screen from a request for JSON data. I thought what I have so far would work but I guess not. onResponse does not seem to ever be called so the data is never assigned to a variable to be processed and I don't know how to fix this. Any and all help is very much appreciated.

Below is my relevant code:

My JSON data is:

{
   "popular":[
      {
         "name":"Pizza",
         "imageURL":"https://static4.depositphotos.com/1016418/315/i/600/depositphotos_3158962-stock-photo-pepperoni-pizza-isolated.jpg",
         "rating":"4.8",
         "deliveryTime":"45 min",
         "deliveryCharges":"Free Delivery",
         "price":"15",
         "note":"Delicious"
      },
      {
         "name":"Chick-Fil-A",
         "imageURL":"https://media.istockphoto.com/photos/chicken-bacon-club-sandwich-picture-id585602032?k=6&m=585602032&s=612x612&w=0&h=DzlMVMOaqC25Zf78NPGzr9nLOf7wANEgv9u_vScu4d8=",
         "rating":"5.0",
         "deliveryTime":"15 min",
         "deliveryCharges":"3",
         "price":"7",
         "note":"Classic"
      },
      {
         "name":"Mac & Cheese",
         "imageURL":"https://media.istockphoto.com/photos/homemade-baked-creamy-macaroni-and-cheese-picture-id483485720?k=6&m=483485720&s=612x612&w=0&h=u2Wb4hR0cIqNAm8q_4j-oFPrtC4hT_YXaq2srA2zmqI=",
         "rating":"4.7",
         "deliveryTime":"20 min",
         "deliveryCharges":"1",
         "price":"4",
         "note":"Homestyle"
      }
   ],
   "recommended":[
      {
         "name":"Chicken Tikka Masala",
         "imageURL":"https://media.istockphoto.com/photos/chicken-tikka-masala-curry-with-rice-and-naan-bread-picture-id1143530019?k=6&m=1143530019&s=612x612&w=0&h=aOCxTVcwi88NHCX9-xgNu7cmPX9rq5AGtEVYblNTnGc=",
         "rating":"4.8",
         "deliveryTime":"25 min",
         "deliveryCharges":"2",
         "price":"14",
         "note":"Fan Favorite"
      },
      {
         "name":"Strawberry Milkshake",
         "imageURL":"https://thumbs.dreamstime.com/b/strawberry-milkshake-covered-whipped-cream-plastic-glass-isolated-white-background-44432579.jpg",
         "rating":"4.5",
         "deliveryTime":"10 min",
         "deliveryCharges":"0",
         "price":"4",
         "note":"Chilly"
      },
      {
         "name":"3 Tacos",
         "imageURL":"https://previews.123rf.com/images/gdolgikh/gdolgikh1703/gdolgikh170300221/74432760-mexican-tacos-with-beef.jpg",
         "rating":"4.6",
         "deliveryTime":"17 min",
         "deliveryCharges":"1",
         "price":"12",
         "note":"Hard or Soft Shell"
      }
   ],
   "allmenu":[
      {
         "name":"Pizza",
         "imageURL":"https://static4.depositphotos.com/1016418/315/i/600/depositphotos_3158962-stock-photo-pepperoni-pizza-isolated.jpg",
         "rating":"4.8",
         "deliveryTime":"45 min",
         "deliveryCharges":"Free Delivery",
         "price":"15",
         "note":"Delicious"
      },
      {
         "name":"Chick-Fil-A",
         "imageURL":"https://media.istockphoto.com/photos/chicken-bacon-club-sandwich-picture-id585602032?k=6&m=585602032&s=612x612&w=0&h=DzlMVMOaqC25Zf78NPGzr9nLOf7wANEgv9u_vScu4d8=",
         "rating":"5.0",
         "deliveryTime":"15 min",
         "deliveryCharges":"3",
         "price":"7",
         "note":"Classic"
      },
      {
         "name":"Mac & Cheese",
         "imageURL":"https://media.istockphoto.com/photos/homemade-baked-creamy-macaroni-and-cheese-picture-id483485720?k=6&m=483485720&s=612x612&w=0&h=u2Wb4hR0cIqNAm8q_4j-oFPrtC4hT_YXaq2srA2zmqI=",
         "rating":"4.7",
         "deliveryTime":"20 min",
         "deliveryCharges":"1",
         "price":"4",
         "note":"Homestyle"
      },
      {
         "name":"Chicken Tikka Masala",
         "imageURL":"https://media.istockphoto.com/photos/chicken-tikka-masala-curry-with-rice-and-naan-bread-picture-id1143530019?k=6&m=1143530019&s=612x612&w=0&h=aOCxTVcwi88NHCX9-xgNu7cmPX9rq5AGtEVYblNTnGc=",
         "rating":"4.8",
         "deliveryTime":"25 min",
         "deliveryCharges":"2",
         "price":"14",
         "note":"Fan Favorite"
      },
      {
         "name":"Strawberry Milkshake",
         "imageURL":"https://thumbs.dreamstime.com/b/strawberry-milkshake-covered-whipped-cream-plastic-glass-isolated-white-background-44432579.jpg",
         "rating":"4.5",
         "deliveryTime":"10 min",
         "deliveryCharges":"0",
         "price":"4",
         "note":"Chilly"
      },
      {
         "name":"3 Tacos",
         "imageURL":"https://previews.123rf.com/images/gdolgikh/gdolgikh1703/gdolgikh170300221/74432760-mexican-tacos-with-beef.jpg",
         "rating":"4.6",
         "deliveryTime":"17 min",
         "deliveryCharges":"1",
         "price":"12",
         "note":"Hard or Soft Shell"
      }
   ]
}

I have models for Allmenu, FoodData, Popular, and Recommended.

AllMenu:

package com.example.bearcateats.model;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class Allmenu {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("imageURL")
    @Expose
    private String imageURL;
    @SerializedName("rating")
    @Expose
    private String rating;
    @SerializedName("deliveryTime")
    @Expose
    private String deliveryTime;
    @SerializedName("deliveryCharges")
    @Expose
    private String deliveryCharges;
    @SerializedName("price")
    @Expose
    private String price;
    @SerializedName("note")
    @Expose
    private String note;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public String getRating() {
        return rating;
    }

    public void setRating(String rating) {
        this.rating = rating;
    }

    public String getDeliveryTime() {
        return deliveryTime;
    }

    public void setDeliveryTime(String deliveryTime) {
        this.deliveryTime = deliveryTime;
    }

    public String getDeliveryCharges() {
        return deliveryCharges;
    }

    public void setDeliveryCharges(String deliveryCharges) {
        this.deliveryCharges = deliveryCharges;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

}

FoodData:

package com.example.bearcateats.model;

import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class FoodData {

    @SerializedName("popular")
    @Expose
    private List<Popular> popular = null;
    @SerializedName("recommended")
    @Expose
    private List<Recommended> recommended = null;
    @SerializedName("allmenu")
    @Expose
    private List<Allmenu> allmenu = null;

    public List<Popular> getPopular() {
        return popular;
    }

    public void setPopular(List<Popular> popular) {
        this.popular = popular;
    }

    public List<Recommended> getRecommended() {
        return recommended;
    }

    public void setRecommended(List<Recommended> recommended) {
        this.recommended = recommended;
    }

    public List<Allmenu> getAllmenu() {
        return allmenu;
    }

    public void setAllmenu(List<Allmenu> allmenu) {
        this.allmenu = allmenu;
    }

}

Popular:

package com.example.bearcateats.model;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class Popular {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("imageURL")
    @Expose
    private String imageURL;
    @SerializedName("rating")
    @Expose
    private String rating;
    @SerializedName("deliveryTime")
    @Expose
    private String deliveryTime;
    @SerializedName("deliveryCharges")
    @Expose
    private String deliveryCharges;
    @SerializedName("price")
    @Expose
    private String price;
    @SerializedName("note")
    @Expose
    private String note;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public String getRating() {
        return rating;
    }

    public void setRating(String rating) {
        this.rating = rating;
    }

    public String getDeliveryTime() {
        return deliveryTime;
    }

    public void setDeliveryTime(String deliveryTime) {
        this.deliveryTime = deliveryTime;
    }

    public String getDeliveryCharges() {
        return deliveryCharges;
    }

    public void setDeliveryCharges(String deliveryCharges) {
        this.deliveryCharges = deliveryCharges;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

}

Recommended:

package com.example.bearcateats.model;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class Recommended {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("imageURL")
    @Expose
    private String imageURL;
    @SerializedName("rating")
    @Expose
    private String rating;
    @SerializedName("deliveryTime")
    @Expose
    private String deliveryTime;
    @SerializedName("deliveryCharges")
    @Expose
    private String deliveryCharges;
    @SerializedName("price")
    @Expose
    private String price;
    @SerializedName("note")
    @Expose
    private String note;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public String getRating() {
        return rating;
    }

    public void setRating(String rating) {
        this.rating = rating;
    }

    public String getDeliveryTime() {
        return deliveryTime;
    }

    public void setDeliveryTime(String deliveryTime) {
        this.deliveryTime = deliveryTime;
    }

    public String getDeliveryCharges() {
        return deliveryCharges;
    }

    public void setDeliveryCharges(String deliveryCharges) {
        this.deliveryCharges = deliveryCharges;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

}

Main:

package com.example.bearcateats;

import android.os.Bundle;
import android.widget.Toast;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bearcateats.adapters.PopularAdapter;
import com.example.bearcateats.adapters.RecommendedAdapter;
import com.example.bearcateats.model.Allmenu;
import com.example.bearcateats.model.FoodData;
import com.example.bearcateats.model.Popular;
import com.example.bearcateats.model.Recommended;
import com.example.bearcateats.retrofit.ApiInterface;
import com.example.bearcateats.retrofit.RetrofitClient;
import com.example.bearcateats.adapters.AllMenuAdapter;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    ApiInterface apiInterface;

    RecyclerView popularRecyclerView, recommendedRecyclerView, allMenuRecyclerView;

    PopularAdapter popularAdapter;
    RecommendedAdapter recommendedAdapter;
    AllMenuAdapter allMenuAdapter;


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

        apiInterface = RetrofitClient.getRetrofitInstance().create(ApiInterface.class);

        Call<List<FoodData>> call = apiInterface.getAllData();
        call.enqueue(new Callback<List<FoodData>>() {
            @Override
            public void onResponse(Call<List<FoodData>> call, Response<List<FoodData>> response) {
                System.out.println("TEST!!!!!!!!!!!!!!");
                List<FoodData> MenuList;
                MenuList = response.body();
                if(MenuList == null) {
                    System.out.println("MenuList!!!!!!!!!!!!!!");
                }

                List <FoodData> test1 = (List<FoodData>) MenuList.get(0);

                List<Popular> popular = ((FoodData) test1).getPopular();

                getPopularData(popular);
                System.out.println("GET POPULAR RAN!!!!!!!!!!!!!!");

                getRecommendedData(MenuList.get(0).getRecommended());
            }

            @Override
            public void onFailure(Call<List<FoodData>> call, Throwable t) {
                Toast.makeText(MainActivity.this, "Server is not responding.", Toast.LENGTH_SHORT).show();
            }
        });




    }

    private void  getPopularData(List<Popular> popularList){

        popularRecyclerView = findViewById(R.id.popular_recycler);
        popularAdapter = new PopularAdapter(this, popularList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        popularRecyclerView.setLayoutManager(layoutManager);
        popularRecyclerView.setAdapter(popularAdapter);

    }

    private void  getRecommendedData(List<Recommended> recommendedList){

        recommendedRecyclerView = findViewById(R.id.recommended_recycler);
        recommendedAdapter = new RecommendedAdapter(this, recommendedList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recommendedRecyclerView.setLayoutManager(layoutManager);
        recommendedRecyclerView.setAdapter(recommendedAdapter);

    }

    private void  getAllMenu(List<Allmenu> allmenuList){

        allMenuRecyclerView = findViewById(R.id.all_menu_recycler);
        allMenuAdapter = new AllMenuAdapter(this, allmenuList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        allMenuRecyclerView.setLayoutManager(layoutManager);
        allMenuRecyclerView.setAdapter(allMenuAdapter);
        allMenuAdapter.notifyDataSetChanged();

    }
}

FoodDetails

{

    // now we will get data from intent and set to UI

    ImageView imageView;
    TextView itemName, itemPrice, itemRating;
    RatingBar ratingBar;

    String name, price, rating, imageUrl;

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

        Intent intent = getIntent();

        name = intent.getStringExtra("name");
        price = intent.getStringExtra("price");
        rating = intent.getStringExtra("rating");
        imageUrl = intent.getStringExtra("image");

        imageView = findViewById(R.id.imageView5);
        itemName = findViewById(R.id.name);
        itemPrice = findViewById(R.id.price);
        itemRating = findViewById(R.id.rating);
        ratingBar = findViewById(R.id.ratingBar);

        Glide.with(getApplicationContext()).load(imageUrl).into(imageView);
        itemName.setText(name);
        itemPrice.setText("$ "+price);
        itemRating.setText(rating);
        ratingBar.setRating(Float.parseFloat(rating));

    }
}

Upvotes: 0

Views: 124

Answers (2)

NRUSINGHA MOHARANA
NRUSINGHA MOHARANA

Reputation: 1559

Couple of silly mistakes are there. I have fixed all your bugs. Nothing wrong with your JSON or Response data classes. Correct response is received inside onResponse() callback. Issues are present other parts of your code. Just follow step by step.

Step-1

Replace below code while parsing response data from api call like:

        call.enqueue(new Callback<List<FoodData>>() {
        @Override
        public void onResponse(Call<List<FoodData>> call, Response<List<FoodData>> response) {
            if (response.isSuccessful()){
                if (response.body() != null){
                    List<Popular> popular = response.body().get(0).getPopular();

                    getPopularData(popular);

                    getRecommendedData(response.body().get(0).getRecommended());
                }
            }
        }

        @Override
        public void onFailure(Call<List<FoodData>> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Server is not responding.", Toast.LENGTH_SHORT).show();
        }
    });

Step-2

Inside PopularAdapter class replace getItemCount() method as below:

    @Override
public int getItemCount() {
    //return 0;   // Returning 0 will show nothing in RecyclerView.
   return popularList.size();
}

Step-3:

Inside RecommendedAdapter class you have used wrong xml for ViewHolder. Replace like below:

    @NonNull
@Override
public RecommendedViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    //View view = LayoutInflater.from(context).inflate(R.layout.popular_recycler_items, parent, false);
    View view = LayoutInflater.from(context).inflate(R.layout.recommended_recyvler_items, parent, false);
    return new RecommendedViewHolder(view);
}

And also replace getItemCount() method like below:

    @Override
public int getItemCount() {
    return recommendedList.size();
}

UPDATE:-

Why are you calling same api inside onSuccess() of api call ? I have update your onCreate() method like below:

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

    apiInterface = RetrofitClient.getRetrofitInstance().create(ApiInterface.class);

    Call<List<FoodData>> call = apiInterface.getAllData();
    call.enqueue(new Callback<List<FoodData>>() {
        @Override
        public void onResponse(Call<List<FoodData>> call, Response<List<FoodData>> response) {
            if (response.isSuccessful()) {
                if (response.body() != null) {
                    getPopularData(response.body().get(0).getPopular());
                    getRecommendedData(response.body().get(0).getRecommended());
                    getAllMenu(response.body().get(0).getAllmenu());
                }
            }
        /*              
     call.clone().enqueue(new Callback<List<FoodData>>() {
                @Override
                public void onResponse(Call<List<FoodData>> call, Response<List<FoodData>> response) {
                    if (response.isSuccessful()) {
                        if (response.body() != null) {
                            response.code();
                            getPopularData(response.body().get(0).getPopular());
                            getRecommendedData(response.body().get(0).getRecommended());
                            getAllMenu(response.body().get(0).getAllmenu());
                        }
                    }
                }

                @Override
                public void onFailure(Call<List<FoodData>> call, Throwable t) {
                    response.code();
                    Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            });*/
        }

        @Override
        public void onFailure(Call<List<FoodData>> call, Throwable t) {
            Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

Upvotes: 1

Arjun Nemical
Arjun Nemical

Reputation: 47

I see your JSON in https://francescainfranca.github.io/menuJSON/index.json is an Single FoodData JSON Object and Not an JSONArray.

This is causing the following exception when we run the application. So either Change the JSON structure or Make the application use FoodData directly instead of List<FoodData>.enter image description here

Also the Toast Message (Server is not responding) is being shown on run which you have added on Failure Response.

Hope this helps you. Thanks.

Upvotes: 0

Related Questions