Unable to fetch the data from Firebase Database - android

I am trying to retrive values from firebase database. But when I am trying to run the app it crashes. Here is the java file:
package com.example.fresh24;
import android.content.Context;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class DBqueries {
public static FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
public static List<MachineCategoryModel> machineCategoryModelList = new ArrayList<>();
public static List<HomePageModel> homePageModelList = new ArrayList<>();
public static void loadCategories(final MachineCategoryAdapter machineCategoryAdapter, final Context context){
firebaseFirestore.collection("CATEGORIES").orderBy("index").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for(QueryDocumentSnapshot documentSnapshot : task.getResult()){
machineCategoryModelList.add(new MachineCategoryModel(documentSnapshot.get("categoryName").toString()));
}
machineCategoryAdapter.notifyDataSetChanged();
} else{
String error = task.getException().getMessage();
Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
}
}
});
}
public static void loadFragmentData(final HomePageAdapter adapter, final Context context){
firebaseFirestore.collection("CATEGORIES")
.document("CoolingCabinet")
.collection("TRAYS").orderBy("index").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for(QueryDocumentSnapshot documentSnapshot : task.getResult()){
if((long)documentSnapshot.get("view_type") == 0){
List<WishlistModel>viewAllProductList = new ArrayList<>();
List<HorizontalProductScrollModel> horizontalProductScrollModelList = new ArrayList<>();
long no_of_products= (long)documentSnapshot.get("no_of_products");
for(long x = 1; x < no_of_products; x++){
horizontalProductScrollModelList.add(new HorizontalProductScrollModel(documentSnapshot.get("product_ID_"+x).toString(),
documentSnapshot.get("product_location_"+x).toString(),
documentSnapshot.get("product_image_"+x).toString(),
documentSnapshot.get("product_title_"+x).toString(),
documentSnapshot.get("product_stock_"+x).toString(),
documentSnapshot.get("product_price_"+x).toString()));
viewAllProductList.add(new WishlistModel(
documentSnapshot.get("product_image_"+x).toString(),
documentSnapshot.get("product_title_"+x).toString(),
(long)documentSnapshot.get("free_coupons_"+x),
documentSnapshot.get("average_rating_"+x).toString(),
(long)documentSnapshot.get("tol_rating_"+x),
documentSnapshot.get("product_price_"+x).toString(),
documentSnapshot.get("product_cut_price_"+x).toString()
));
}
homePageModelList.add(new HomePageModel(0,documentSnapshot.get("layout_title").toString(),documentSnapshot.get("layout_background").toString(),horizontalProductScrollModelList,viewAllProductList));
}
}
adapter.notifyDataSetChanged();
} else{
String error = task.getException().getMessage();
Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is my Model class
package com.example.fresh24;
public class WishlistModel {
private String productImage;
private String productTitle;
private long freeCoupon;
private String rating;
private long totalRatings;
private String productPrice;
private String cutPrice;
public WishlistModel(String productImage, String productTitle, long freeCoupon, String rating, long totalRatings, String productPrice, String cutPrice) {
this.productImage = productImage;
this.productTitle = productTitle;
this.freeCoupon = freeCoupon;
this.rating = rating;
this.totalRatings = totalRatings;
this.productPrice = productPrice;
this.cutPrice = cutPrice;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getProductTitle() {
return productTitle;
}
public void setProductTitle(String productTitle) {
this.productTitle = productTitle;
}
public long getFreeCoupon() {
return freeCoupon;
}
public void setFreeCoupon(long freeCoupon) {
this.freeCoupon = freeCoupon;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public long getTotalRatings() {
return totalRatings;
}
public void setTotalRatings(long totalRatings) {
this.totalRatings = totalRatings;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getCutPrice() {
return cutPrice;
}
public void setCutPrice(String cutPrice) {
this.cutPrice = cutPrice;
}
}
Here is the the adapter file:
package com.example.fresh24;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
public class WishlistAdapter extends RecyclerView.Adapter<WishlistAdapter.ViewHolder> {
private List<WishlistModel> wishlistModelList;
private Boolean wishlist;
public WishlistAdapter(List<WishlistModel> wishlistModelList, Boolean wishlist) {
this.wishlistModelList = wishlistModelList;
this.wishlist = wishlist;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.wishlist_item_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WishlistAdapter.ViewHolder viewHolder, int position) {
String resource = wishlistModelList.get(position).getProductImage();
String title = wishlistModelList.get(position).getProductTitle();
long freeCoupon = wishlistModelList.get(position).getFreeCoupon();
String rating = wishlistModelList.get(position).getRating();
long totalRatings = wishlistModelList.get(position).getTotalRatings();
String productPrice = wishlistModelList.get(position).getProductPrice();
String cutPrice = wishlistModelList.get(position).getCutPrice();
viewHolder.setData(resource, title, freeCoupon, rating, totalRatings, productPrice, cutPrice);
}
#Override
public int getItemCount() {
return wishlistModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView productImage;
private TextView productTitle;
private TextView freeCoupons;
private TextView rating;
private TextView totalRatings;
private View priceCut;
private ImageView couponIcon;
private TextView productPrice;
private TextView cutPrice;
private ImageView deleteBtn;
public ViewHolder(#NonNull View itemView) {
super(itemView);
productImage = itemView.findViewById(R.id.product_image);
productTitle = itemView.findViewById(R.id.product_title);
freeCoupons = itemView.findViewById(R.id.free_coupon);
rating = itemView.findViewById(R.id.tv_product_rating_miniview);
totalRatings = itemView.findViewById(R.id.total_ratings);
priceCut = itemView.findViewById(R.id.price_cut);
couponIcon = itemView.findViewById(R.id.coupon_icon);
productPrice = itemView.findViewById(R.id.product_price);
cutPrice = itemView.findViewById(R.id.cut_price);
deleteBtn = itemView.findViewById(R.id.delete_btn);
}
private void setData(String resource, String title, long freeCouponsNo, String averageRate, long totalRatingsNo, String price, String cutPriceValue) {
Glide.with(itemView.getContext()).load(resource).apply(new RequestOptions().placeholder(R.drawable.home_icon_green)).into(productImage);
productTitle.setText(title);
if (freeCouponsNo != 0) {
couponIcon.setVisibility(View.VISIBLE);
if (freeCouponsNo == 1) {
freeCoupons.setText("free " + freeCouponsNo + " coupon");
} else {
freeCoupons.setText("free " + freeCouponsNo + " coupons");
}
}else{
couponIcon.setVisibility(View.INVISIBLE);
freeCoupons.setVisibility(View.INVISIBLE);
}
rating.setText(averageRate);
totalRatings.setText(totalRatingsNo+"(ratings)");
productPrice.setText(price);
cutPrice.setText(cutPriceValue);
if(wishlist){
deleteBtn.setVisibility(View.VISIBLE);
}else{
deleteBtn.setVisibility(View.GONE);
}
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(),"Testing Deleted",Toast.LENGTH_SHORT).show();
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent productDetailsIntent = new Intent(itemView.getContext(),ProductDetailsActivity.class);
itemView.getContext().startActivity(productDetailsIntent);
}
});
}
}
}
Here is the logcat error:
Process: com.example.fresh24, PID: 9413
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at com.example.fresh24.DBqueries$2.onComplete(DBqueries.java:68)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
The error is on this line in the java file - (long)documentSnapshot.get("free_coupons_"+x). I have selected numbers for the 'free coupons' and 'total ratings' field in the Firebase database. I have read that the number fields are converted to Long when fetched from the firebase database and hence I have casted them to long. I am unable to locate the source of my error. Please help. Thanks in advance.

This is due to the fact you are not checking if the value if null or not.So just put the whole code which fetches the long value inside a if loop with condition that it is != null this will solve the issue.Hope it is helpful.

Related

A movie app like the Amazon prime, I would display the movie category using the CategoryItem. I want to display all category with Recycler

I mixed things up. The initial error I had was this MainActivity.java:130: error: incompatible types: List<com.kuroniczstudio.splashscreen.CategoryItem> cannot be converted to List<com.kuroniczstudio.splashscreen.model.CategoryItem>
allCategoryList.add(new AllCategory(1,"VIP Hour", homeCatListItem1)); While try to fix it that was when things started getting confusing. So I am still having this error
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.kuroniczstudio.splashscreen.adapter.BannerMoviesPagerAdapter;
import com.kuroniczstudio.splashscreen.adapter.MainRecyclerAdapter;
import com.kuroniczstudio.splashscreen.model.AllCategory;
import com.kuroniczstudio.splashscreen.model.BannerMovies;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
BannerMoviesPagerAdapter bannerMoviesPagerAdapter;
TabLayout indicatorTab, categoryTab;
ViewPager bannerMoviesViewPager;
List<BannerMovies> homeBannerList;
List<BannerMovies> vipHourBannerList;
List<BannerMovies> prophecyBannerList;
List<BannerMovies> testimonyBannerList;
Timer sliderTimer;
MainRecyclerAdapter mainRecyclerAdapter;
RecyclerView mainRecycler;
List<AllCategory> allCategoryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
indicatorTab = findViewById(R.id.tab_indicator);
categoryTab = findViewById(R.id.tablayout);
homeBannerList = new ArrayList<>();
homeBannerList.add(new BannerMovies(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeBannerList.add(new BannerMovies(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeBannerList.add(new BannerMovies(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
vipHourBannerList = new ArrayList<>();
vipHourBannerList.add(new BannerMovies(1, "I will be better than my father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/ymIUteex694"));
vipHourBannerList.add(new BannerMovies(3, "I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/Sbbu536E9vA"));
vipHourBannerList.add(new BannerMovies(4, "My Hair Will Grow Again", "https://img.yts.mx/assets/images/movies/sharkula_2022/medium-cover.jpg", "https://youtu.be/yau5eQH1K_I"));
prophecyBannerList = new ArrayList<>();
prophecyBannerList.add(new BannerMovies(2, "Looking for Jackie", "https://img.yts.mx/assets/images/movies/looking_for_jackie_2009/medium-cover.jpg", "https://www.youtube.com/watch?v=ByYWL1SEe-k"));
prophecyBannerList.add(new BannerMovies(3, "Khuda Haafiz Chapter II", "https://sdmoviespoint.mba/wp-content/uploads/2022/07/Khuda-Haafiz-Chapter-II-Agni-Pariksha-2022-Full-Movie-Download-Free.jpg", "https://www.youtube.com/watch?v=ByYWL1SEe-k"));
prophecyBannerList.add(new BannerMovies(4, "Sharkula", "https://img.yts.mx/assets/images/movies/sharkula_2022/medium-cover.jpg", "https://youtu.be/6SOEYXZK6Q4"));
prophecyBannerList.add(new BannerMovies(5, "Looking for Jackie", "https://img.yts.mx/assets/images/movies/looking_for_jackie_2009/medium-cover.jpg", "https://www.youtube.com/watch?v=ByYWL1SEe-k"));
testimonyBannerList = new ArrayList<>();
testimonyBannerList.add(new BannerMovies(1, "See how this little boy survived under the water for 2 hours", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/rRFkBLGQIs8"));
testimonyBannerList.add(new BannerMovies(2, "Testimony Blessing Nsikak Saved from spiritual attack", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/TdYn24MdD1Q"));
testimonyBannerList.add(new BannerMovies(3, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/HNjxxk3eWKk"));
//this is default tab selected
setBannerMoviesPagerAdapter(homeBannerList);
categoryTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
setBannerMoviesPagerAdapter(vipHourBannerList);
return;
case 2:
setBannerMoviesPagerAdapter(prophecyBannerList);
return;
case 3:
setBannerMoviesPagerAdapter(testimonyBannerList);
return;
default:
setBannerMoviesPagerAdapter(homeBannerList);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
List<CategoryItem> homeCatListItem1 = new ArrayList<>();
homeCatListItem1.add(new CategoryItem(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeCatListItem1.add(new CategoryItem(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeCatListItem1.add(new CategoryItem(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
homeCatListItem1.add(new CategoryItem(4, "My Hair Will Grow Again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/yau5eQH1K_I"));
homeCatListItem1.add(new CategoryItem(5, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/HNjxxk3eWKk"));
List<CategoryItem> homeCatListItem2 = new ArrayList<>();
homeCatListItem2.add(new CategoryItem(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeCatListItem2.add(new CategoryItem(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeCatListItem2.add(new CategoryItem(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
homeCatListItem2.add(new CategoryItem(4, "My Hair Will Grow Again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/yau5eQH1K_I"));
homeCatListItem2.add(new CategoryItem(5, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/HNjxxk3eWKk"));
List<CategoryItem> homeCatListItem3 = new ArrayList<>();
homeCatListItem3.add(new CategoryItem(1, "Trailer - I cannot give up now!!!", "https://i.pinimg.com/originals/1a/5e/c6/1a5ec63c50513055ac7674ad65c2e1a1.jpg", "https://youtu.be/7w1YKrHW85c"));
homeCatListItem3.add(new CategoryItem(2, "Trailer - I must cross the Red Sea", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/88dHJdCyyBA"));
homeCatListItem3.add(new CategoryItem(3, "Trailer - I must be better than my Father", "https://i.pinimg.com/originals/ec/60/46/ec604668771e8916466be6835d2ea588.jpg", "https://youtu.be/GsNrJgLSTAM"));
homeCatListItem3.add(new CategoryItem(4, "My Hair Will Grow Again", "https://i.pinimg.com/originals/14/f1/5c/14f15cc3bbc780abdfecafa0f94024e1.jpg", "https://youtu.be/yau5eQH1K_I"));
homeCatListItem3.add(new CategoryItem(5, "See how this man got back his transformer working again", "https://i.pinimg.com/originals/7f/8f/02/7f8f02fdfc2b09de9d01d86395d128b1.jpg", "https://youtu.be/HNjxxk3eWKk"));
allCategoryList = new ArrayList<>();
allCategoryList.add(new AllCategory(1,"VIP Hour", homeCatListItem1));
allCategoryList.add(new AllCategory(2,"VIP Hour", homeCatListItem2));
allCategoryList.add(new AllCategory(3,"VIP Hour", homeCatListItem3));
setMainRecycler(allCategoryList);
}
private void setBannerMoviesPagerAdapter(List<BannerMovies> bannerMoviesList) {
bannerMoviesViewPager = findViewById(R.id.banner_viewPager);
bannerMoviesPagerAdapter = new BannerMoviesPagerAdapter(this, bannerMoviesList);
bannerMoviesViewPager.setAdapter(bannerMoviesPagerAdapter);
indicatorTab.setupWithViewPager(bannerMoviesViewPager);
sliderTimer = new Timer();
sliderTimer.scheduleAtFixedRate(new AutoSlider(), 4000, 6000);
indicatorTab.setupWithViewPager(bannerMoviesViewPager, true);
}
class AutoSlider extends TimerTask {
#Override
public void run() {
MainActivity.this.runOnUiThread(() ->{
if (bannerMoviesViewPager.getCurrentItem() < homeBannerList.size() - 1) {
bannerMoviesViewPager.setCurrentItem(bannerMoviesViewPager.getCurrentItem() + 1);
}
else{
bannerMoviesViewPager.setCurrentItem(0);
}
});
}
}
public void setMainRecycler(List<AllCategory> allCategoryList) {
mainRecycler = findViewById(R.id.main_recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
mainRecycler.setLayoutManager(layoutManager);
mainRecyclerAdapter = new MainRecyclerAdapter(this, allCategoryList);
mainRecycler.setAdapter(mainRecyclerAdapter);
}
}
//Items in the model directory//
CategoryItem
public class CategoryItem {
Integer id;
String movieName;
String imageUrl;
String fileUrl;
public CategoryItem(Integer id, String movieName, String imageUrl, String fileUrl) {
this.id = id;
this.movieName = movieName;
this.imageUrl = imageUrl;
this.fileUrl = fileUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
}
AllCategory.Class
import java.util.List;
public class AllCategory {
String categoryTitle;
Integer categoryId;
private List<CategoryItem> categoryItemList = null;
public AllCategory(Integer categoryId, String categoryTitle, List<CategoryItem> categoryItemList) {
this.categoryTitle = categoryTitle;
this.categoryId = categoryId;
this.categoryItemList = categoryItemList;
}
public List<CategoryItem> getCategoryItemList() {
return categoryItemList;
}
public void setCategoryItemList(List<CategoryItem> categoryItemList) {
this.categoryItemList = categoryItemList;
}
public String getCategoryTitle(){
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle){
this.categoryTitle = categoryTitle;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
}
BannerMovies
package com.kuroniczstudio.splashscreen.model;
public class BannerMovies {
Integer id;
String movieName;
String imageUrl;
String fileUrl;
public BannerMovies(Integer id, String movieName, String imageUrl, String fileUrl) {
this.id = id;
this.movieName = movieName;
this.imageUrl = imageUrl;
this.fileUrl = fileUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
}
_____________________________________
**MainRecyclerAdapter**
package com.kuroniczstudio.splashscreen.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.kuroniczstudio.splashscreen.CategoryItem;
import com.kuroniczstudio.splashscreen.R;
import com.kuroniczstudio.splashscreen.model.AllCategory;
import java.util.List;
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {
Context context;
List<AllCategory> allCategoryList;
public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
this.context = context;
this.allCategoryList = allCategoryList;
}
#NonNull
#Override
public MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent));
}
#Override
public void onBindViewHolder(#NonNull MainViewHolder holder, int position) {
holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());
}
#Override
public int getItemCount() {
return allCategoryList.size();
}
public static final class MainViewHolder extends RecyclerView.ViewHolder{
TextView categoryName;
RecyclerView itemRecycler;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.item_category);
itemRecycler = itemView.findViewById(R.id.item_recycler);
}
}
private void setItemRecycler(RecyclerView recyclerView, List<CategoryItem> categoryItemList){
ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context, categoryItemList);
recyclerView.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
recyclerView.setAdapter(itemRecyclerAdapter);
}
}
ItemRecyclerAdapter
package com.kuroniczstudio.splashscreen.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.kuroniczstudio.splashscreen.CategoryItem;
import com.kuroniczstudio.splashscreen.R;
import java.util.List;
public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ItemViewHolder> {
Context context;
List<CategoryItem> categoryItemList;
public ItemRecyclerAdapter(Context context, List<CategoryItem> categoryItemList) {
this.context = context;
this.categoryItemList = categoryItemList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cat_recycler_row_items,parent, false));
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Glide.with(context).load(categoryItemList.get(position).getImageUrl()).into(holder.itemImage);
}
#Override
public int getItemCount() {
return categoryItemList.size();
}
public static final class ItemViewHolder extends RecyclerView.ViewHolder{
ImageView itemImage;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
itemImage = itemView.findViewById(R.id.item_image);
}
}
}
BannerMoviesPagerAdapter
package com.kuroniczstudio.splashscreen.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import com.bumptech.glide.Glide;
import com.kuroniczstudio.splashscreen.R;
import com.kuroniczstudio.splashscreen.model.BannerMovies;
import java.util.List;
public class BannerMoviesPagerAdapter extends PagerAdapter {
Context context;
List<BannerMovies> bannerMoviesList;
public BannerMoviesPagerAdapter(Context context, List<BannerMovies> bannerMoviesList) {
this.context = context;
this.bannerMoviesList = bannerMoviesList;
}
#Override
public int getCount() {
return bannerMoviesList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view = LayoutInflater.from(context).inflate(R.layout.banner_movie_layout, null);
ImageView bannerImage = view.findViewById(R.id.banner_image);
Glide.with(context).load(bannerMoviesList.get(position).getImageUrl()).into(bannerImage);
container.addView(view);
return view;
}
}
The error itself is telling you where you are messing up. You have 2 CategoryItem classes in your project with the following hierarchies:
com.kuroniczstudio.splashscreen.CategoryItem
com.kuroniczstudio.splashscreen.model.CategoryItem
You're trying to use both these which is creating this conflict. Make sure you are using only one class.
In your application you have TWO classes called CategoryItem. One has the full name:
com.kuroniczstudio.splashscreen.CategoryItem
The other has the full name:
com.kuroniczstudio.splashscreen.model.CategoryItem
They are different classes, and you cannot convert from one class to the other one.
We cannot tell from the code that you have shown us why this is happening. For a start, you haven't show us both versions of CategoryItem. And you have left out all of the package statements. (So we can't tell which version of CategoryItem the AllCategory constructor expects ...)
But the compilation error message clearly proves that it is happening.
You probably shouldn't have two CategoryItem classes at all ...

I'm using retrofit to parse data in android but keep getting a null pointer exception

Here's the code:
Request Interface class
import retrofit2.Call;
import retrofit2.http.GET;
public interface RequestInterface {
String BASE_URL = "https://newsapi.org/v2/";
#GET("top-headlines?sources=google-news&apiKey=3709c816cdcb4eb38b7e45c9829a37d7\n")
Call<NewsList> getJSON();
}
Ojbect class
public class News {
private Source source;
private String author;
private String title;
private String description;
private String url;
private String urlToImage;
private String publishedAt;
public class Source{
private String id;
private String name;
public Source(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
public News(Source source, String author, String title, String description, String url, String urlToImage, String publishedAt) {
this.source = source;
this.author = author;
this.title = title;
this.description = description;
this.url = url;
this.urlToImage = urlToImage;
this.publishedAt = publishedAt;
}
public Source getSource() {
return source;
}
public String getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public String getUrlToImage() {
return urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setSource(Source source) {
this.source = source;
}
public void setAuthor(String author) {
this.author = author;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setUrl(String url) {
this.url = url;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
Object list class
import java.util.ArrayList;
public class NewsList {
private ArrayList<News> news = new ArrayList<>();
public ArrayList<News> getNews() {
return news;
}
public void setNews(ArrayList<News> news) {
this.news = news;
}
}
Adapter class
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private ArrayList<News> news;
private Context context;
public MyAdapter(Context context, ArrayList<News> news){
this.news = news;
this.context = context;
}
public News getItem(int i){
return news.get(i);
}
#NonNull
#Override
public MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.news_card, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.ViewHolder viewHolder, int i) {
// viewHolder.article_source.setText(news.get(i).getSource());
viewHolder.article_author.setText(news.get(i).getAuthor());
viewHolder.article_title.setText(news.get(i).getTitle());
viewHolder.article_description.setText(news.get(i).getDescription());
viewHolder.article_url.setText(news.get(i).getUrl());
viewHolder.article_urlToImage.setText(news.get(i).getUrlToImage());
viewHolder.article_publishedAt.setText(news.get(i).getPublishedAt());
Picasso.with(context).load(news.get(i).getUrlToImage()).resize(120,60).into(viewHolder.article_image);
}
#Override
public int getItemCount() {
return news.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView article_image;
TextView article_source, article_author, article_title,
article_description, article_url, article_urlToImage,
article_publishedAt;
public ViewHolder (#NonNull View itemView) {
super(itemView);
article_image = (ImageView) itemView.findViewById(R.id.article_image);
article_source = (TextView) itemView.findViewById(R.id.article_source);
article_author = (TextView) itemView.findViewById(R.id.article_author);
article_title = (TextView) itemView.findViewById(R.id.article_title);
article_description = (TextView) itemView.findViewById(R.id.article_description);
article_url = (TextView) itemView.findViewById(R.id.article_url);
article_urlToImage = (TextView) itemView.findViewById(R.id.article_urlToImage);
article_publishedAt = (TextView) itemView.findViewById(R.id.article_publishedAt);
}
}
}
Main activity
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<News> newsArrayList;
private MyAdapter myAdapter;
private Context context;
NewsList newsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initviews();
}
private void initviews(){
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON(){
newsArrayList = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RequestInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface =retrofit.create(RequestInterface.class);
Call<NewsList> call = requestInterface.getJSON();
call.enqueue(new Callback<NewsList>() {
#Override
public void onResponse(Call<NewsList> call, Response<NewsList> response) {
// newsArrayList = response.body().getNews();
// Log.i(MainActivity.class.getSimpleName().toString(),"#########ArrayList: "+newsArrayList);
newsArrayList = new ArrayList<>((newsList.getNews()));
myAdapter = new MyAdapter(context, newsArrayList);
recyclerView.setAdapter(myAdapter);
}
#Override
public void onFailure(Call<NewsList> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
What am I doing wrong? I keep getting a null pointer exception in the line:
newsArrayList = new ArrayList<>((newsList.getNews()))
Error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.dell.myapi.NewsList.getNews()' on a null object reference
at com.example.dell.myapi.MainActivity$1.onResponse(MainActivity.java:57)
You haven't initialized newsList and trying to fetch the data.
Try to assign the result to newsList and then try.
#Override
public void onResponse(Call<NewsList> call, Response<NewsList> response) {
Log.i(MainActivity.class.getSimpleName().toString(),"Response : "+response.body().toString());
newsList = response.body().getNews();// assign the value from response
newsArrayList = new ArrayList<>((newsList.getNews()));
myAdapter = new MyAdapter(context, newsArrayList);
recyclerView.setAdapter(myAdapter);
}
Try this you have pass wrong url at end (\n) remove and try as below
#GET("top-headlines?sources=google-news&apiKey=3709c816cdcb4eb38b7e45c9829a37d7")
change hear also
call.enqueue(new Callback<NewsList>() {
#Override
public void onResponse(Call<NewsList> call, Response<NewsList> response) {
newsArrayList = new ArrayList<>();
newsArrayList.add(response.body().getNews());
myAdapter = new MyAdapter(context, newsArrayList);
recyclerView.setAdapter(myAdapter);
}
#Override
public void onFailure(Call<NewsList> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
First your url isn't correct. Remove \n at the end of url.
Second your models isn't correct. For example NewsList.java doesn't have fields like articles. Use this link to create your models. Your NewsList.java must be like this
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NewsList {
#SerializedName("status")
#Expose
private String status;
#SerializedName("totalResults")
#Expose
private Integer totalResults;
#SerializedName("articles")
#Expose
private List<News> articles = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getTotalResults() {
return totalResults;
}
public void setTotalResults(Integer totalResults) {
this.totalResults = totalResults;
}
public List<News> getArticles() {
return articles;
}
public void setArticles(List<News> articles) {
this.articles = articles;
}
}

ExpandableList View from Json

Currently working on a ExpandableListView in android using RecyclerView. I have done almost all the thing but somehow I am getting a NullpointerException which I can not sort out.Any help will be appreciated.
I am sharing the code snippet and also the git link
Used Library
Code I have tried
The app is crasing at this line in the apadter class
public DriverScheduleExpandableAdapter(Context mContext, #NonNull
List<DriverSchedule.Schedules> parentList) {
super(parentList);//////**this is where the app is crashing**
mRecipeList = parentList;
mInflater = LayoutInflater.from(mContext);
}
Error coming is :
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper.generateChildItemList(ExpandableWrapper.java:99)
at com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper.<init>(ExpandableWrapper.java:33)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.generateParentWrapper(ExpandableRecyclerAdapter.java:1357)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.generateFlattenedParentChildList(ExpandableRecyclerAdapter.java:1326)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.<init>(ExpandableRecyclerAdapter.java:120)
at com.rtstl.expandablelistview.adapter.DriverScheduleExpandableAdapter.<init>(DriverScheduleExpandableAdapter.java:23)
at com.rtstl.expandablelistview.MainActivity.inflateadapter(MainActivity.java:50)
at com.rtstl.expandablelistview.MainActivity.initview(MainActivity.java:41)
at com.rtstl.expandablelistview.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6357)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2515) 
at android.app.ActivityThread.access$1000(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:157) 
at android.app.ActivityThread.main(ActivityThread.java:5571) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635) 
MainActivity.java
package com.rtstl.expandablelistview;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rtstl.expandablelistview.adapter.DriverScheduleAdapter;
import com.rtstl.expandablelistview.adapter.DriverScheduleExpandableAdapter;
import com.rtstl.expandablelistview.databinding.ActivityMainBinding;
import com.rtstl.expandablelistview.model.DriverSchedule;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
Context mContext;
DriverSchedule list_driver;
DriverScheduleAdapter adapter;
DriverScheduleExpandableAdapter adapterExp;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext=this;
gson=new Gson();
initview();
}
private void initview() {
binding= DataBindingUtil.setContentView(this, R.layout.activity_main);
inflateadapter();
}
private void inflateadapter() {
////for reading file from raw folder otherwise it's not required
list_driver= gson.fromJson(readFileFromRawDirectory(R.raw.driverschedule), new TypeToken<DriverSchedule>(){}.getType());
////////////////////////////////////////
Toast.makeText(mContext,""+list_driver.getData().getSclist().size(),Toast.LENGTH_SHORT).show();
adapterExp = new DriverScheduleExpandableAdapter(mContext, list_driver.getData().getSclist());
binding.rvRecycle.setLayoutManager(new LinearLayoutManager(this));
binding.rvRecycle.setAdapter(adapter);
}
private String readFileFromRawDirectory(int resourceId){
InputStream iStream = this.getResources().openRawResource(resourceId);
ByteArrayOutputStream byteStream = null;
try {
byte[] buffer = new byte[iStream.available()];
iStream.read(buffer);
byteStream = new ByteArrayOutputStream();
byteStream.write(buffer);
byteStream.close();
iStream.close();
//inflateadapter();
} catch (IOException e) {
e.printStackTrace();
}
return byteStream.toString();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_Recycle"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</layout>
Adapter class
package com.rtstl.expandablelistview.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
import java.util.List;
public class DriverScheduleExpandableAdapter extends ExpandableRecyclerAdapter<DriverSchedule.Schedules, DriverSchedule.Alloted_kids, RouteViewHolder, KidViewHolder> {
private LayoutInflater mInflater;
private List<DriverSchedule.Schedules> mRecipeList;
private static final int PARENT_NORMAL = 1;
private static final int CHILD_NORMAL = 3;
public DriverScheduleExpandableAdapter(Context mContext, #NonNull List<DriverSchedule.Schedules> parentList) {
super(parentList);//////**this is where the app is crashing**
mRecipeList = parentList;
mInflater = LayoutInflater.from(mContext);
}
#NonNull
#Override
public RouteViewHolder onCreateParentViewHolder(#NonNull ViewGroup parentViewGroup, int viewType) {
View recipeView;
switch (viewType) {
default:
case PARENT_NORMAL:
recipeView = mInflater.inflate(R.layout.group_item, parentViewGroup, false);
break;
}
return new RouteViewHolder(recipeView);
}
#NonNull
#Override
public KidViewHolder onCreateChildViewHolder(#NonNull ViewGroup childViewGroup, int viewType) {
View ingredientView;
switch (viewType) {
default:
case CHILD_NORMAL:
ingredientView = mInflater.inflate(R.layout.child_item, childViewGroup, false);
break;
}
return new KidViewHolder(ingredientView);
}
#Override
public void onBindParentViewHolder(#NonNull RouteViewHolder parentViewHolder, int parentPosition, #NonNull DriverSchedule.Schedules parent) {
parentViewHolder.bind(parent);
}
#Override
public void onBindChildViewHolder(#NonNull KidViewHolder childViewHolder, int parentPosition, int childPosition, #NonNull DriverSchedule.Alloted_kids child) {
childViewHolder.bind(child);
}
#Override
public int getParentViewType(int parentPosition) {
return PARENT_NORMAL;
}
#Override
public int getChildViewType(int parentPosition, int childPosition) {
return CHILD_NORMAL;
}
#Override
public boolean isParentViewType(int viewType) {
return viewType == PARENT_NORMAL;
}
}
DriverSchedule.java
package com.rtstl.expandablelistview.model;
import android.databinding.BaseObservable;
import com.bignerdranch.expandablerecyclerview.model.Parent;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by User1 on 09-03-2018.
*/
public class DriverSchedule extends BaseObservable {
#SerializedName("status")
#Expose
public String status;
#SerializedName("msg")
#Expose
public String msg;
#SerializedName("data")
#Expose
public Data data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
#SerializedName("schedules")
#Expose
List<Schedules> sclist;
#SerializedName("driver_details")
#Expose
Driver_details driver_details;
public List<Schedules> getSclist() {
return sclist;
}
public void setSclist(List<Schedules> sclist) {
this.sclist = sclist;
}
public Driver_details getDriver_details() {
return driver_details;
}
public void setDriver_details(Driver_details driver_details) {
this.driver_details = driver_details;
}
}
public class Schedules implements Parent<Alloted_kids> {
#SerializedName("is_active")
#Expose
public String is_active;
#SerializedName("route_details")
#Expose
public Route_details route_details;
#SerializedName("alloted_kids")
#Expose
public List<Alloted_kids> alloted_kids;
public String getIs_active() {
return is_active;
}
public void setIs_active(String is_active) {
this.is_active = is_active;
}
public Route_details getRoute_details() {
return route_details;
}
public void setRoute_details(Route_details route_details) {
this.route_details = route_details;
}
public List<Alloted_kids> getAlloted_kids() {
return alloted_kids;
}
public void setAlloted_kids(List<Alloted_kids> alloted_kids) {
this.alloted_kids = alloted_kids;
}
#Override
public List<Alloted_kids> getChildList() {
return null;
}
#Override
public boolean isInitiallyExpanded() {
return false;
}
}
public class Driver_details {
#SerializedName("driver_details")
#Expose
public Driver_details1 driver_details;
public Driver_details1 getDriver_details() {
return driver_details;
}
public void setDriver_details(Driver_details1 driver_details) {
this.driver_details = driver_details;
}
}
public class Route_details {
#SerializedName("ds_id")
#Expose
public String ds_id;
#SerializedName("kidpool_route_id")
#Expose
public String kidpool_route_id;
public String getDs_id() {
return ds_id;
}
public void setDs_id(String ds_id) {
this.ds_id = ds_id;
}
public String getKidpool_route_id() {
return kidpool_route_id;
}
public void setKidpool_route_id(String kidpool_route_id) {
this.kidpool_route_id = kidpool_route_id;
}
}
public class Alloted_kids {
#SerializedName("kid_name")
#Expose
public String kid_name;
#SerializedName("kid_image")
#Expose
public String kid_image;
public String getKid_name() {
return kid_name;
}
public void setKid_name(String kid_name) {
this.kid_name = kid_name;
}
public String getKid_image() {
return kid_image;
}
public void setKid_image(String kid_image) {
this.kid_image = kid_image;
}
}
public class Driver_details1 {
#SerializedName("driver_id")
#Expose
public String driver_id;
#SerializedName("driver_name")
#Expose
public String driver_name;
public String getDriver_id() {
return driver_id;
}
public void setDriver_id(String driver_id) {
this.driver_id = driver_id;
}
public String getDriver_name() {
return driver_name;
}
public void setDriver_name(String driver_name) {
this.driver_name = driver_name;
}
}
}
KidViewHolder.java
package com.rtstl.expandablelistview.adapter;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ChildViewHolder;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
class KidViewHolder extends ChildViewHolder{
private TextView mIngredientTextView;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
mIngredientTextView = (TextView) itemView.findViewById(R.id.tv_childname);
}
public void bind(#NonNull DriverSchedule.Alloted_kids ingredient) {
mIngredientTextView.setText(ingredient.getKid_name());
}
}
RouteViewHolder.java
package com.rtstl.expandablelistview.adapter;
import android.annotation.SuppressLint;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ParentViewHolder;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
class RouteViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
#NonNull
private final ImageView mArrowExpandImageView;
private TextView mRecipeTextView;
public RouteViewHolder(#NonNull View itemView) {
super(itemView);
mRecipeTextView = (TextView) itemView.findViewById(R.id.group_name);
mArrowExpandImageView = (ImageView) itemView.findViewById(R.id.iv_exp);
}
public void bind(#NonNull DriverSchedule.Schedules recipe) {
mRecipeTextView.setText(recipe.getRoute_details().getKidpool_route_id());
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (expanded) {
mArrowExpandImageView.setRotation(ROTATED_POSITION);
} else {
mArrowExpandImageView.setRotation(INITIAL_POSITION);
}
}
}
#Override
public void onExpansionToggled(boolean expanded) {
super.onExpansionToggled(expanded);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
RotateAnimation rotateAnimation;
if (expanded) { // rotate clockwise
rotateAnimation = new RotateAnimation(ROTATED_POSITION,
INITIAL_POSITION,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
} else { // rotate counterclockwise
rotateAnimation = new RotateAnimation(-1 * ROTATED_POSITION,
INITIAL_POSITION,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
}
rotateAnimation.setDuration(200);
rotateAnimation.setFillAfter(true);
mArrowExpandImageView.startAnimation(rotateAnimation);
}
}
}
See this issue it seems that your list has some null values
https://github.com/bignerdranch/expandable-recycler-view/issues/321
I ran your code and logged your list you have null values in a list
check this method
#Override
public List<Alloted_kids> getChildList() {
return null;
}
this method should return non null value this method only causing problem
use return Collections.emptyList(); instead of return null there

Why is my ListView not showing anything?

// I have a Custom ListView in android and have set a adapter . My problem is //that the list view does not show anything, regardless of the adapter, note I'm //retrieving information from a Backendless services . please help
// adapter Code
package za.ac.cut.afinal;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by User on 2017/09/12.
*/
public class StudentAdapter extends ArrayAdapter<Student_Class> {
private final Context context;
private final List<Student_Class> values;
TextView tvName, tvSurname,tvGender,tvRace;
public StudentAdapter(Context context, List<Student_Class> list)
{
super(context,R.layout.custom_student_row_layout);
this.context = context;
this.values = list;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Nullable
#Override
public Student_Class getItem(int position) {
return values.get(position);
}
#Override
public int getCount() {
return values == null ? 0 : values.size();
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.custom_student_row_layout,parent,false);
tvName = (TextView) rowView.findViewById(R.id.customSNmae);
tvSurname = (TextView) rowView.findViewById(R.id.tv_customSSurname);
tvGender = (TextView) rowView.findViewById(R.id.customSGender);
tvRace = (TextView) rowView.findViewById(R.id.customSRace);
Toast.makeText(context, "help" + values.get(position).getL_fname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help2" + values.get(position).getL_lname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help3" + values.get(position).getL_gender(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help4" + values.get(position).getL_race(), Toast.LENGTH_SHORT).show();
tvName.setText(values.get(position).getL_fname());
tvSurname.setText(values.get(position).getL_lname());
tvGender.setText(values.get(position).getL_gender());
tvRace.setText(values.get(position).getL_race());
return rowView ;
}
}
// class Listview
package za.ac.cut.afinal;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.persistence.BackendlessDataQuery;
import com.backendless.persistence.DataQueryBuilder;
import com.backendless.persistence.QueryOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import weborb.client.ant.wdm.View;
public class Student_List extends AppCompatActivity {
ListView lv;
List<Student_Class> StudentsList;
Student_Class student ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
lv = (ListView)findViewById(R.id.lvStudentDetails1);
retrieveStudent();
}
#Override
protected void onResume() {
super.onResume();
retrieveStudent();
}
private void retrieveStudent()
{
// progressBar.setVisibility(android.view.View.VISIBLE);
if(StudentsList != null)
{
StudentsList.clear();
}
String whereClause = "u_Name = '12'";
DataQueryBuilder queryBuilder = DataQueryBuilder.create();
queryBuilder.setWhereClause(whereClause);
queryBuilder.setPageSize(100);
queryBuilder.setSortBy("l_fname");
Backendless.Persistence.of(Student_Class.class).find(queryBuilder, new AsyncCallback<List<Student_Class>>() {
#Override
public void handleResponse(List<Student_Class> response) {
for (int x = 0; x < response.size(); x++) {
student = new Student_Class(response.get(x).getL_IDNo(), response.get(x).getL_fname(), response.get(x).getL_lname(),
response.get(x).getL_className(), response.get(x).getL_gender(),
response.get(x).getL_race(), response.get(x).getL_DOB(),
response.get(x).getL_classLang(), response.get(x).getL_fullOrhalfday(),
response.get(x).getL_DOE(), response.get(x).getL_address(),
response.get(x).getL_mGardian(), response.get(x).getL_fGardian(),
response.get(x).getL_mGardianEmail(), response.get(x).getL_fGardianEmail(),
response.get(x).getL_mGardianCell(), response.get(x).getL_fGardianCell(),
response.get(x).getL_doc(),
response.get(x).getL_doctCell(), response.get(x).getL_medicalAid(),
response.get(x).getL_medicalAidPlan(), response.get(x).getL_medicalAidPlanNo(),
response.get(x).getL_allergies(), response.get(x).getL_tuckshopBalance()
, response.get(x).getCreated(), response.get(x).getUpdated(),
response.get(x).getObjectID());
}
StudentsList.add(student);
if (StudentsList != null) {
StudentAdapter adapter = new StudentAdapter(Student_List.this,StudentsList);
lv.setAdapter(adapter);
Helper_Class.ShowToast(Student_List.this,"WTF");
}else {
// tv_emptyList.setVisibility(View.VISIBLE);
Helper_Class.ShowToast(Student_List.this,"No Learners enrolled for this class");
}
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
}
}
// Student Class
package za.ac.cut.afinal;
import java.util.Date;
/**
* Created by User on 2017/09/10.
*/
public class Student_Class {
private Date created;
private Date updated;
private String objectID;
private String l_IDNo;
private String l_fname;
private String l_lname;
private String l_className;
private String l_gender;
private String l_race;
private String l_DOB;
private String l_classLang;
private String l_fullOrhalfday;
private String l_DOE;
private String l_address;
private String l_mGardian;
private String l_fGardian;
private String l_mGardianEmail;
private String l_fGardianEmail;
private String l_mGardianCell;
private String l_fGardianCell;
private String l_doc;
private String l_doctCell;
private String l_medicalAid;
private String l_medicalAidPlan;
private String l_medicalAidPlanNo;
private String l_allergies;
private String l_tuckshopBalance;
public Student_Class(String l_fname, String l_lname, String l_gender, String l_race) {
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_gender = l_gender;
this.l_race = l_race;
}
public Student_Class() {
l_IDNo = null;
l_fname = null;
l_lname = null;
l_className = null;
l_gender = null;
l_race = null;
l_DOB = null;
l_classLang = null;
l_fullOrhalfday = null;
l_DOE = null;
l_address = null;
l_mGardian = null;
l_fGardian = null;
l_mGardianEmail = null;
l_fGardianEmail = null;
l_mGardianCell = null;
l_fGardianCell = null;
l_doc = null;
l_doctCell = null;
l_medicalAid = null;
l_medicalAidPlan = null;
l_medicalAidPlanNo = null;
l_allergies = null;
l_tuckshopBalance = null;
created = null;
updated = null;
objectID = null;
}
public Student_Class(String l_IDNo, String l_fname, String l_lname, String l_className, String l_gender, String l_race, String l_DOB, String l_classLang, String l_fullOrhalfday, String l_DOE, String l_address, String l_mGardian, String l_fGardian, String l_mGardianEmail, String l_fGardianEmail, String l_mGardianCell, String l_fGardianCell, String l_doc, String l_doctCell, String l_medicalAid, String l_medicalAidPlan, String l_medicalAidPlanNo, String l_allergies, String l_tuckshopBalance,Date created, Date updated, String objectID) {
this.created = created;
this.updated = updated;
this.objectID = objectID;
this.l_IDNo = l_IDNo;
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_className = l_className;
this.l_gender = l_gender;
this.l_race = l_race;
this.l_DOB = l_DOB;
this.l_classLang = l_classLang;
this.l_fullOrhalfday = l_fullOrhalfday;
this.l_DOE = l_DOE;
this.l_address = l_address;
this.l_mGardian = l_mGardian;
this.l_fGardian = l_fGardian;
this.l_mGardianEmail = l_mGardianEmail;
this.l_fGardianEmail = l_fGardianEmail;
this.l_mGardianCell = l_mGardianCell;
this.l_fGardianCell = l_fGardianCell;
this.l_doc = l_doc;
this.l_doctCell = l_doctCell;
this.l_medicalAid = l_medicalAid;
this.l_medicalAidPlan = l_medicalAidPlan;
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
this.l_allergies = l_allergies;
this.l_tuckshopBalance = l_tuckshopBalance;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getObjectID() {
return objectID;
}
public void setObjectID(String objectID) {
this.objectID = objectID;
}
public String getL_IDNo() {
return l_IDNo;
}
public void setL_IDNo(String l_IDNo) {
this.l_IDNo = l_IDNo;
}
public String getL_fname() {
return l_fname;
}
public void setL_fname(String l_fname) {
this.l_fname = l_fname;
}
public String getL_lname() {
return l_lname;
}
public void setL_lname(String l_lname) {
this.l_lname = l_lname;
}
public String getL_className() {
return l_className;
}
public void setL_className(String l_className) {
this.l_className = l_className;
}
public String getL_gender() {
return l_gender;
}
public void setL_gender(String l_gender) {
this.l_gender = l_gender;
}
public String getL_race() {
return l_race;
}
public void setL_race(String l_race) {
this.l_race = l_race;
}
public String getL_DOB() {
return l_DOB;
}
public void setL_DOB(String l_DOB) {
this.l_DOB = l_DOB;
}
public String getL_classLang() {
return l_classLang;
}
public void setL_classLang(String l_classLang) {
this.l_classLang = l_classLang;
}
public String getL_fullOrhalfday() {
return l_fullOrhalfday;
}
public void setL_fullOrhalfday(String l_fullOrhalfday) {
this.l_fullOrhalfday = l_fullOrhalfday;
}
public String getL_DOE() {
return l_DOE;
}
public void setL_DOE(String l_DOE) {
this.l_DOE = l_DOE;
}
public String getL_address() {
return l_address;
}
public void setL_address(String l_address) {
this.l_address = l_address;
}
public String getL_mGardian() {
return l_mGardian;
}
public void setL_mGardian(String l_mGardian) {
this.l_mGardian = l_mGardian;
}
public String getL_fGardian() {
return l_fGardian;
}
public void setL_fGardian(String l_fGardian) {
this.l_fGardian = l_fGardian;
}
public String getL_mGardianEmail() {
return l_mGardianEmail;
}
public void setL_mGardianEmail(String l_mGardianEmail) {
this.l_mGardianEmail = l_mGardianEmail;
}
public String getL_fGardianEmail() {
return l_fGardianEmail;
}
public void setL_fGardianEmail(String l_fGardianEmail) {
this.l_fGardianEmail = l_fGardianEmail;
}
public String getL_mGardianCell() {
return l_mGardianCell;
}
public void setL_mGardianCell(String l_mGardianCell) {
this.l_mGardianCell = l_mGardianCell;
}
public String getL_fGardianCell() {
return l_fGardianCell;
}
public void setL_fGardianCell(String l_fGardianCell) {
this.l_fGardianCell = l_fGardianCell;
}
public String getL_doc() {
return l_doc;
}
public void setL_doc(String l_doc) {
this.l_doc = l_doc;
}
public String getL_doctCell() {
return l_doctCell;
}
public void setL_doctCell(String l_doctCell) {
this.l_doctCell = l_doctCell;
}
public String getL_medicalAid() {
return l_medicalAid;
}
public void setL_medicalAid(String l_medicalAid) {
this.l_medicalAid = l_medicalAid;
}
public String getL_medicalAidPlan() {
return l_medicalAidPlan;
}
public void setL_medicalAidPlan(String l_medicalAidPlan) {
this.l_medicalAidPlan = l_medicalAidPlan;
}
public String getL_medicalAidPlanNo() {
return l_medicalAidPlanNo;
}
public void setL_medicalAidPlanNo(String l_medicalAidPlanNo) {
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
}
public String getL_allergies() {
return l_allergies;
}
public void setL_allergies(String l_allergies) {
this.l_allergies = l_allergies;
}
public String getL_tuckshopBalance() {
return l_tuckshopBalance;
}
public void setL_tuckshopBalance(String l_tuckshopBalance) {
this.l_tuckshopBalance = l_tuckshopBalance;
}
}
set adapter.notifyDataSetChanged(); after retrieving data from backend.
Info data variable must be same reference adress, I mean do not malloc again etc. after retrieving data.
there are some errors:
1) StudentsList is never istanciated (always null)
2) StudentsList.add(student); cannot work because SutendList is null
3) StudentsList.add(student); should be called inside for loop, why are you calling it outside?
Everything was working fine, i mistakenly typed in the wrong string here "String whereClause = "u_Name = '12'";"
36 hours when the problem was a string!

post array inside json object in retrofit?

I m working with retrofit and sending to request to server via post method i am getting response currectly for this json see this is post i m sending to server .
adreess class for post i m using this object
{
"years":"1855",
"months":"6",
"skills":1
}
now i have to implement array inside object in skills how to post this
{
"years":"1",
"months":"6",
"skills":["1","2","3"],
}
how to get array inside object in retrofit
i m using interface like this
Call<AddressResponce> address(#Body Adreess adreess);
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("years")
#Expose
private String years;
#SerializedName("months")
#Expose
private String months;
#SerializedName("skills")
#Expose
private List<String> skills = null;
public String getYears() {
return years;
}
public void setYears(String years) {
this.years = years;
}
public String getMonths() {
return months;
}
public void setMonths(String months) {
this.months = months;
}
public List<String> getSkills() {
return skills;
}
public void setSkills(List<String> skills) {
this.skills = skills;
}
}
I hope it's useful to you ..!
Roughly it would look like this:
RequestBody class should have an array to hold that Skills list
class RequestBody {
int years;
int months;
int[] skills;
}
#POST(“url”)
Call<AddressResponce> address(#Body RequestBody requestbody);
See if it works.
#SerializedName("skills")
#Expose
private List<Integer> skills= new ArrayList<Integer>();
Hit URl in Get Mode
https://api.themoviedb.org/3/movie/top_rated?api_key=ec01f8c2eb6ac402f2ca026dc2d9b8fd&language=en_US&page=1
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUUy00M2RCSERvMWc
package com.keshav.retroft2arrayinsidearrayexamplekeshav.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class TopRatedMovies {
#SerializedName("page")
#Expose
private Integer page;
#SerializedName("results")
#Expose
private List<Result> results = new ArrayList<Result>();
#SerializedName("total_results")
#Expose
private Integer totalResults;
#SerializedName("total_pages")
#Expose
private Integer totalPages;
/**
*
* #return
* The page
*/
public Integer getPage() {
return page;
}
/**
*
* #param page
* The page
*/
public void setPage(Integer page) {
this.page = page;
}
/**
*
* #return
* The results
*/
public List<Result> getResults() {
return results;
}
/**
*
* #param results
* The results
*/
public void setResults(List<Result> results) {
this.results = results;
}
/**
*
* #return
* The totalResults
*/
public Integer getTotalResults() {
return totalResults;
}
/**
*
* #param totalResults
* The total_results
*/
public void setTotalResults(Integer totalResults) {
this.totalResults = totalResults;
}
/**
*
* #return
* The totalPages
*/
public Integer getTotalPages() {
return totalPages;
}
/**
*
* #param totalPages
* The total_pages
*/
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}
}
package com.keshav.retroft2arrayinsidearrayexamplekeshav.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Result {
#SerializedName("poster_path")
#Expose
private String posterPath;
#SerializedName("adult")
#Expose
private Boolean adult;
#SerializedName("overview")
#Expose
private String overview;
#SerializedName("release_date")
#Expose
private String releaseDate;
#SerializedName("genre_ids")
#Expose
private List<Integer> genreIds = new ArrayList<Integer>();
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("original_title")
#Expose
private String originalTitle;
#SerializedName("original_language")
#Expose
private String originalLanguage;
#SerializedName("title")
#Expose
private String title;
#SerializedName("backdrop_path")
#Expose
private String backdropPath;
#SerializedName("popularity")
#Expose
private Double popularity;
#SerializedName("vote_count")
#Expose
private Integer voteCount;
#SerializedName("video")
#Expose
private Boolean video;
#SerializedName("vote_average")
#Expose
private Double voteAverage;
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public Boolean getAdult() {
return adult;
}
public void setAdult(Boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public List<Integer> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public Double getPopularity() {
return popularity;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
public Integer getVoteCount() {
return voteCount;
}
public void setVoteCount(Integer voteCount) {
this.voteCount = voteCount;
}
public Boolean getVideo() {
return video;
}
public void setVideo(Boolean video) {
this.video = video;
}
public Double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(Double voteAverage) {
this.voteAverage = voteAverage;
}
}
package com.keshav.retroft2arrayinsidearrayexamplekeshav;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.adapters.RetrofitArrayInsideArrayAdapter;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.api.MovieApi;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.api.MovieService;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.models.Result;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.models.TopRatedMovies;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.utils.PaginationScrollListener;
import java.util.List;
import java.util.concurrent.TimeoutException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivityArrayInsideArray extends AppCompatActivity
{
private static final String TAG = "ArrayInsideArray";
RetrofitArrayInsideArrayAdapter adapter;
LinearLayoutManager linearLayoutManager;
RecyclerView recyclerView;
ProgressBar progressBar;
LinearLayout errorLayout;
Button btnRetry;
TextView txtError;
private static final int PAGE_START = 1; // TODO Important Role Here
// private static final int PAGE_START = 2; // TODO Important Role Here
// private static final int PAGE_START = 3; // TODO Important Role Here
// private static final int PAGE_START = 4; // TODO Important Role Here
// private static final int PAGE_START = 5; // TODO Important Role Here
private int currentPage = PAGE_START;
private MovieService movieService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
progressBar = (ProgressBar) findViewById(R.id.main_progress);
errorLayout = (LinearLayout) findViewById(R.id.error_layout);
btnRetry = (Button) findViewById(R.id.error_btn_retry);
txtError = (TextView) findViewById(R.id.error_txt_cause);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Array Inside Array Retrofit 2");
adapter = new RetrofitArrayInsideArrayAdapter(this);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
//init service and load data
movieService = MovieApi.getClient().create(MovieService.class);
loadFirstPage();
btnRetry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadFirstPage();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void loadFirstPage() {
Log.d(TAG, "loadFirstPage: ");
// To ensure list is visible when retry button in error view is clicked
hideErrorView();
callTopRatedMoviesApi().enqueue(new Callback<TopRatedMovies>() {
#Override
public void onResponse(Call<TopRatedMovies> call, Response<TopRatedMovies> response) {
// Got data. Send it to adapter
hideErrorView();
List<Result> results = fetchResults(response);
for(int i=0;i<results.size();i++) {
Log.e("keshav", "Title ->" + results.get(i).getTitle());
Log.e("keshav", "Id ->" + results.get(i).getGenreIds());
}
progressBar.setVisibility(View.GONE);
adapter.addAll(results);
// if (currentPage <= TOTAL_PAGES) adapter.addLoadingFooter();
// else isLastPage = true;
}
#Override
public void onFailure(Call<TopRatedMovies> call, Throwable t) {
t.printStackTrace();
showErrorView(t);
}
});
}
private List<Result> fetchResults(Response<TopRatedMovies> response) {
TopRatedMovies topRatedMovies = response.body();
return topRatedMovies.getResults();
}
private Call<TopRatedMovies> callTopRatedMoviesApi() {
return movieService.getTopRatedMovies(
getString(R.string.my_api_key),
"en_US",
currentPage
);
}
private void showErrorView(Throwable throwable) {
if (errorLayout.getVisibility() == View.GONE) {
errorLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
txtError.setText(fetchErrorMessage(throwable));
}
}
private String fetchErrorMessage(Throwable throwable) {
String errorMsg = getResources().getString(R.string.error_msg_unknown);
if (!isNetworkConnected()) {
errorMsg = getResources().getString(R.string.error_msg_no_internet);
} else if (throwable instanceof TimeoutException) {
errorMsg = getResources().getString(R.string.error_msg_timeout);
}
return errorMsg;
}
// Helpers -------------------------------------------------------------------------------------
private void hideErrorView() {
if (errorLayout.getVisibility() == View.VISIBLE) {
errorLayout.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
}
package com.keshav.retroft2arrayinsidearrayexamplekeshav.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bumptech.glide.DrawableRequestBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.R;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.models.Result;
import com.keshav.retroft2arrayinsidearrayexamplekeshav.utils.PaginationAdapterCallback;
import java.util.ArrayList;
import java.util.List;
public class RetrofitArrayInsideArrayAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// View Types
private static final int ITEM = 0;
private static final String BASE_URL_IMG = "https://image.tmdb.org/t/p/w150";
private List<Result> movieResults;
private Context context;
private boolean retryPageLoad = false;
private String errorMsg;
public RetrofitArrayInsideArrayAdapter(Context context) {
this.context = context;
movieResults = new ArrayList<>();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
Log.e("keshav", "onCreateViewHolder Adapter ->" + viewType);
switch (viewType) {
case ITEM:
View viewItem = inflater.inflate(R.layout.item_list_new, parent, false);
viewHolder = new MovieVH(viewItem);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Result result = movieResults.get(position); // Movie
Log.e("keshav", "onBindViewHolder ->" + getItemViewType(position));
switch (getItemViewType(position)) {
case ITEM:
final MovieVH movieVH = (MovieVH) holder;
// movieVH.mMovieTitle.setText(result.getTitle());
// movieVH.mMovieTitle.setText("Keshav "+result.getGenreIds());
movieVH.mMovieTitle.setText(result.getTitle() + " " + result.getGenreIds());
movieVH.mYear.setText(formatYearLabel(result));
movieVH.mMovieDesc.setText(result.getOverview());
movieVH.tv_vote_count.setText("Vote Count :- " + result.getVoteCount());
movieVH.tv_id.setText("ID :- " + result.getId());
movieVH.tv_video.setText("Video :- " + result.getVideo());
movieVH.tv_vote_average.setText("Vote Average :- " + result.getVoteAverage());
movieVH.tv_popularity.setText("Popularity :- " + result.getPopularity());
// load movie thumbnail
loadImage(result.getPosterPath())
.listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// TODO: 08/11/16 handle failure
// movieVH.mProgress.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// image ready, hide progress now
// movieVH.mProgress.setVisibility(View.GONE);
return false; // return false if you want Glide to handle everything else.
}
})
.into(movieVH.mPosterImg);
// load movie thumbnail
loadImage(result.getBackdropPath())
.listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// TODO: 08/11/16 handle failure
movieVH.mProgress.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// image ready, hide progress now
movieVH.mProgress.setVisibility(View.GONE);
return false; // return false if you want Glide to handle everything else.
}
})
.into(movieVH.iv_backdrop_path);
break;
}
}
#Override
public int getItemCount() {
return movieResults == null ? 0 : movieResults.size();
}
#Override
public int getItemViewType(int position) {
Log.e("keshav", "getItemViewType ->" + movieResults.size());
Log.e("keshav", "getItemView-1 ->" + movieResults.size());
Log.e("keshav", "getItemView-2 ->" + position);
return ITEM;
}
private String formatYearLabel(Result result) {
if (result != null && result.getReleaseDate() != null) {
Log.e("keshav", "formatYearLabel -> " + result.getReleaseDate());
return result.getReleaseDate().substring(0, 4) // we want the year only
+ " | "
+ result.getOriginalLanguage().toUpperCase();
} else {
return "Keshav";
}
}
private DrawableRequestBuilder<String> loadImage(#NonNull String posterPath) {
return Glide
.with(context)
.load(BASE_URL_IMG + posterPath)
.diskCacheStrategy(DiskCacheStrategy.ALL) // cache both original & resized image
.centerCrop()
.crossFade();
}
/*
Helpers - Pagination
_________________________________________________________________________________________________
*/
public void add(Result r) {
movieResults.add(r);
notifyItemInserted(movieResults.size() - 1);
}
public void addAll(List<Result> moveResults) {
for (Result result : moveResults) {
add(result);
}
}
public Result getItem(int position) {
return movieResults.get(position);
}
public void showRetry(boolean show, #Nullable String errorMsg) {
retryPageLoad = show;
notifyItemChanged(movieResults.size() - 1);
if (errorMsg != null) this.errorMsg = errorMsg;
}
protected class MovieVH extends RecyclerView.ViewHolder {
private TextView mMovieTitle;
private TextView mMovieDesc;
private TextView mYear; // displays "year | language"
private TextView tv_vote_count;
private TextView tv_id;
private TextView tv_video;
private TextView tv_vote_average;
private TextView tv_popularity;
private ImageView mPosterImg;
private ImageView iv_backdrop_path;
private ProgressBar mProgress;
public MovieVH(View itemView) {
super(itemView);
mMovieTitle = (TextView) itemView.findViewById(R.id.movie_title);
mMovieDesc = (TextView) itemView.findViewById(R.id.movie_desc);
tv_vote_count = (TextView) itemView.findViewById(R.id.tv_vote_count);
tv_id = (TextView) itemView.findViewById(R.id.tv_id);
tv_video = (TextView) itemView.findViewById(R.id.tv_video);
tv_vote_average = (TextView) itemView.findViewById(R.id.tv_vote_average);
tv_popularity = (TextView) itemView.findViewById(R.id.tv_popularity);
mYear = (TextView) itemView.findViewById(R.id.movie_year);
mPosterImg = (ImageView) itemView.findViewById(R.id.movie_poster);
iv_backdrop_path = (ImageView) itemView.findViewById(R.id.iv_backdrop_path);
mProgress = (ProgressBar) itemView.findViewById(R.id.movie_progress);
}
}
}

Categories

Resources