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);
}
}
}
Related
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.
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;
}
}
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
I want to build a movie app that consumes a REST api using retrofit and displays images using Picasso and bring in Retrofit and show real movie posters as well as detail information for each movie.
i'm using The Movie Database Api to get some real data into our app. Checkout their documentation and get familiar with their API, specially the movies/popular endpoint
But when running the application white screen showing pictures does not show movies and I do not know where is the problem
this MainActivity :
package com.walkatheri.movies;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
RecyclerView mRecyclerView;
final MoviesAdapter mAdapter;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mAdapter = new MoviesAdapter(this);
mRecyclerView.setAdapter(mAdapter);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org/3")
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addEncodedQueryParam("api_key", "MY _KEY");
}
})
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movies.MovieResult>() {
#Override
public void success(Movies.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public MovieViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public static class MoviesAdapter extends RecyclerView.Adapter<MovieViewHolder> {
List<Movies>MovieList ;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context)
{
this.mContext = context;
this.mInflater = LayoutInflater.from(context);
this.MovieList = new ArrayList<>();
}
public void setMovieList(List<Movies> movieList)
{
this.MovieList=movieList ;
// The adapter needs to know that the data has changed. If we don't call this, app will crash.
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.row_movie, parent, false);
MovieViewHolder viewHolder = new MovieViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movies movies = MovieList.get(position);
Picasso.with(mContext)
.load(movies.getPoster()).placeholder(R.color.colorAccent)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return (MovieList == null) ? 0 : MovieList.size();
}
}
}
Movies class :
package com.walkatheri.movies;
import android.graphics.Movie;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by waad on 08/10/2016.
*/
public class Movies {
private String title;
#SerializedName("poster_path")
private String poster;
#SerializedName("overview")
private String description;
#SerializedName("backdrop_path")
private String backdrop;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoster() {
return "http://image.tmdb.org/t/p/w500" + poster;
}
// public String getPoster() {
// return "http://t2.gstatic.com/images?q=tbn:ANd9GcQW3LbpT94mtUG1PZIIzJNxmFX399wr_NcvoppJ82k7z99Hx6in";
// }
public void setPoster(String poster) {
this.poster = poster;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBackdrop() {
return backdrop;
}
public void setBackdrop(String backdrop) {
this.backdrop = backdrop;
}
public static class MovieResult {
private List<Movies> resulte;
public List<Movies> getResults() {
return resulte;
}
}}
MoviesApiService class:
package com.walkatheri.movies;
import retrofit.Callback;
import retrofit.http.GET;
/**
* Created by waad on 18/10/2016.
*/
public interface MoviesApiService {
#GET("/movie/popular")
void getPopularMovies(Callback<Movies.MovieResult>cb);
}
Very difficult to point out mistakes without any hint like stacktraces.
Some pointers
Use retrofit asynchronous call.
You need .addConverterFactory(GsonConverterFactory.create()) to convert json to pojos.
Image will be loaded only if you us the url http://image.tmdb.org/t/p/w185"+"yourposterpath". Check the moviedb link
Update your libs and change your api accordingly (Recommended)
Lastly a clean architecture will help you write tests properly. Your code is unstructured and you need to separate components properly. Suggest you read about MVP or MVVM patterns. Dagger can also help.
A good read about retrofit https://inthecheesefactory.com/blog/retrofit-2.0/en
So the changes
public class TestActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public static final String MOVIE_DB_API_URL = "http://api.themoviedb.org/3/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mAdapter = new MoviesAdapter(this);
mRecyclerView.setAdapter(mAdapter);
final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15,TimeUnit.SECONDS)
.build();
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(MOVIE_DB_API_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
Call<MoviesList> movieResultCallback = service.getPopularMovies();
// asynchronous call
movieResultCallback.enqueue(new Callback<MoviesList>() {
#Override
public void onResponse(Call<MoviesList> call, Response<MoviesList> response) {
//int code = response.code();
// can check the status code
mAdapter.setMovieList(response.body().getResults());
}
#Override
public void onFailure(Call<MoviesList> call, Throwable t) {
}
});
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public MovieViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
public static class MoviesAdapter extends RecyclerView.Adapter<MovieViewHolder> {
List<Movies>MovieList ;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context)
{
this.mContext = context;
this.mInflater = LayoutInflater.from(context);
this.MovieList = new ArrayList<>();
}
public void setMovieList(List<Movies> movieList)
{
this.MovieList=movieList ;
// The adapter needs to know that the data has changed. If we don't call this, app will crash.
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.row, parent, false);
MovieViewHolder viewHolder = new MovieViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movies movies = MovieList.get(position);
Picasso.with(mContext)
.load("http://image.tmdb.org/t/p/w185"+movies.getPoster_path()).placeholder(R.color.colorAccent)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return (MovieList == null) ? 0 : MovieList.size();
}
}
public static class LoggingInterceptor implements Interceptor {
#Override public okhttp3.Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().url()
.newBuilder()
.addQueryParameter("api_key", "4848b32592990671646565fa3240a7bc")
.build();
Request request = chain.request().newBuilder().url(url).build();;
long t1 = System.nanoTime();
String requestLog = String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers());
//YLog.d(String.format("Sending request %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
if(request.method().compareToIgnoreCase("post")==0){
requestLog ="\n"+requestLog+"\n"+bodyToString(request);
}
Log.d("TAG","request"+"\n"+requestLog);
okhttp3.Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseLog = String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers());
String bodyString = response.body().string();
Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
//return response;
}
}
private static String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
if (copy != null && copy.body() != null) // make sure its not null to avoif NPE
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
}
Then
public interface MoviesApiService {
#GET("movie/popular")
Call<MoviesList> getPopularMovies();
}
My Model classes
Use http://www.jsonschema2pojo.org/ to convert json to pojo
I copied the below for one the respositories on github.
Lots of similar repositories avaiable on github. https://github.com/ewintory/udacity-popular-movies and many more..
public class Movies implements Parcelable {
private int id,vote_count,favourite,reviewsaved,trailersaved;
private float vote_average,popularity;
private String original_language,original_title,overview,release_date,poster_path,title,generids,backdrop_path;
private boolean video,favored;
public Movies()
{
}
public void setReviewsaved(int reviewsaved) {
this.reviewsaved = reviewsaved;
}
public void setTrailersaved(int trailersaved) {
this.trailersaved = trailersaved;
}
public int getTrailersaved() {
return trailersaved;
}
public int getReviewsaved() {
return reviewsaved;
}
public void setFavored(boolean favored) {
this.favored = favored;
}
public void setId(int id) {
this.id = id;
}
public void setVote_count(int vote_count) {
this.vote_count = vote_count;
}
public void setFavourite(int favourite) {
this.favourite = favourite;
}
public void setVote_average(float vote_average) {
this.vote_average = vote_average;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public void setOverview(String overview) {
this.overview = overview;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public void setPopularity(float popularity) {
this.popularity = popularity;
}
public void setTitle(String title) {
this.title = title;
}
public void setGenerids(String generids) {
this.generids = generids;
}
public void setbackdrop_path(String backdrop_path) {
this.backdrop_path = backdrop_path;
}
public void setVideo(boolean video) {
this.video = video;
}
public String getGenerids() {
return generids;
}
public int getId() {
return id;
}
public int getVote_count() {
return vote_count;
}
public float getVote_avarage() {
return vote_average;
}
public String getOriginal_language() {
return original_language;
}
public String getOriginal_title() {
return original_title;
}
public String getOverview() {
return overview;
}
public String getRelease_date() {
return release_date;
}
public String getBackdrop_path() {
return backdrop_path;
}
public int getFavourtite() {
return favourite;
}
public String getPoster_path() {
return poster_path;
}
public float getPopularity() {
return popularity;
}
public String getTitle() {
return title;
}
public boolean isVideo() {
return video;
}
// Parcelling part
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.original_language);
dest.writeString(this.original_title);
dest.writeString(this.overview);
dest.writeString(this.poster_path);
dest.writeString(this.generids);
dest.writeString(this.title);
dest.writeString(this.release_date);
dest.writeString(this.backdrop_path);
dest.writeInt(this.favourite);
dest.writeInt(this.id);
dest.writeInt(this.vote_count);
dest.writeFloat(this.vote_average);
dest.writeFloat(this.popularity);
}
protected Movies(Parcel in) {
this.original_language = in.readString();
this.original_title = in.readString();
this.overview = in.readString();
this.poster_path = in.readString();
this.generids = in.readString();
this.title = in.readString();
this.release_date = in.readString();
this.backdrop_path = in.readString();
this.favourite = in.readInt();
this.id = in.readInt();
this.vote_count = in.readInt();
this.vote_average =in.readFloat();
this.popularity = in.readFloat();
}
public static final Creator<Movies> CREATOR = new Creator<Movies>() {
public Movies createFromParcel(Parcel source) {
return new Movies(source);
}
public Movies[] newArray(int size) {
return new Movies[size];
}
};
#Override
public int describeContents() {
return 0;
}
}
MoviesList
public class MoviesList {
private int total_pages;
public int getTotal_pages() {
return total_pages;
}
private ArrayList<Movies> results;
public ArrayList<Movies> getResults() {
return results;
}
}
Finally updated libs
// Okhttp
compile 'com.squareup.okhttp3:okhttp:3.4.1'
//Retrofit and adapters
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.picasso:picasso:2.5.2'
You can check your logs
It's almost impossible to know for sure what's going on, given your vague input, but my bet would be that you haven't specified internet permission in app's manifest:
<uses-permission android:name="android.permission.INTERNET"/>
(in src/main/AndroidManifest.xml, under manifest tag)
New to using okhttp and Gson. I am practicing by creating a List View that will display information from Rotten Tomatoes API
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
ListView listView;
Response responseObj;
CustomAdapter adapter;
String url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=9htuhtcb4ymusd73d4z6jxcj";
Gson gson;
OkHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.myList);
client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(com.squareup.okhttp.Response response) throws IOException {
String responseStr = response.body().string();
gson = new Gson();
**responseObj = gson.fromJson(responseStr,Response.class);**
adapter = new CustomAdapter(MainActivity.this, responseObj.getMovies());
listView.setAdapter(adapter);
}
});
}
}
This is the Error I get for line 44
FATAL EXCEPTION: OkHttp Dispatcher
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException:
Invalid double: ""
public class Response {
private String link_template;
/**
* id : 771312089
* title : The Hunger Games: Mockingjay - Part 2
* year : 2015
* mpaa_rating : PG-13
* runtime : 136
* critics_consensus :
* release_dates : {"theater":"2015-11-20"}
* ratings : {"critics_rating":"Fresh","critics_score":70,"audience_rating":"Upright","audience_score":71}
* synopsis : The second half of Suzanne Collins' final Hunger Games book is adapted in this Lionsgate production. ~ Jeremy Wheeler, Rovi
* posters : {"thumbnail":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg","profile":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg","detailed":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg","original":"http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg"}
* abridged_cast : [{"name":"Jennifer Lawrence","id":"770800260","characters":["Katniss Everdeen"]},{"name":"Julianne Moore","id":"162654248","characters":["President Alma Coin"]},{"name":"Gwendoline Christie","id":"771060732","characters":["Commander Lyme"]},{"name":"Josh Hutcherson","id":"162654356","characters":["Peeta Mellark"]},{"name":"Robert Knepper","id":"162707688","characters":["Antonius"]}]
* links : {"self":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089.json","alternate":"http://www.rottentomatoes.com/m/the_hunger_games_mockingjay_part_2/","cast":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/cast.json","reviews":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/reviews.json","similar":"http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/similar.json"}
*/
private List<MoviesEntity> movies;
public void setLinks(LinksEntity links) {
this.links = links;
}
public void setLink_template(String link_template) {
this.link_template = link_template;
}
public void setMovies(List<MoviesEntity> movies) {
this.movies = movies;
}
public LinksEntity getLinks() {
return links;
}
public String getLink_template() {
return link_template;
}
public List<MoviesEntity> getMovies() {
return movies;
}
public static class LinksEntity {
private String self;
private String alternate;
public void setSelf(String self) {
this.self = self;
}
public void setAlternate(String alternate) {
this.alternate = alternate;
}
public String getSelf() {
return self;
}
public String getAlternate() {
return alternate;
}
}
public static class MoviesEntity {
private String id;
private String title;
private int year;
private String mpaa_rating;
private int runtime;
private String critics_consensus;
/**
* theater : 2015-11-20
*/
private ReleaseDatesEntity release_dates;
/**
* critics_rating : Fresh
* critics_score : 70
* audience_rating : Upright
* audience_score : 71
*/
private RatingsEntity ratings;
private String synopsis;
/**
* thumbnail : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
* profile : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
* detailed : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
* original : http://resizing.flixster.com/nim-D7-9jGbUZS5wczNes_PmWyI=/53x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/20/29/11202951_ori.jpg
*/
private PostersEntity posters;
/**
* self : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089.json
* alternate : http://www.rottentomatoes.com/m/the_hunger_games_mockingjay_part_2/
* cast : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/cast.json
* reviews : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/reviews.json
* similar : http://api.rottentomatoes.com/api/public/v1.0/movies/771312089/similar.json
*/
private LinksEntity links;
/**
* name : Jennifer Lawrence
* id : 770800260
* characters : ["Katniss Everdeen"]
*/
private List<AbridgedCastEntity> abridged_cast;
public void setId(String id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setYear(int year) {
this.year = year;
}
public void setMpaa_rating(String mpaa_rating) {
this.mpaa_rating = mpaa_rating;
}
public void setRuntime(int runtime) {
this.runtime = runtime;
}
public void setCritics_consensus(String critics_consensus) {
this.critics_consensus = critics_consensus;
}
public void setRelease_dates(ReleaseDatesEntity release_dates) {
this.release_dates = release_dates;
}
public void setRatings(RatingsEntity ratings) {
this.ratings = ratings;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public void setPosters(PostersEntity posters) {
this.posters = posters;
}
public void setLinks(LinksEntity links) {
this.links = links;
}
public void setAbridged_cast(List<AbridgedCastEntity> abridged_cast) {
this.abridged_cast = abridged_cast;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public int getYear() {
return year;
}
public String getMpaa_rating() {
return mpaa_rating;
}
public int getRuntime() {
return runtime;
}
public String getCritics_consensus() {
return critics_consensus;
}
public ReleaseDatesEntity getRelease_dates() {
return release_dates;
}
public RatingsEntity getRatings() {
return ratings;
}
public String getSynopsis() {
return synopsis;
}
public PostersEntity getPosters() {
return posters;
}
public LinksEntity getLinks() {
return links;
}
public List<AbridgedCastEntity> getAbridged_cast() {
return abridged_cast;
}
public static class ReleaseDatesEntity {
private String theater;
public void setTheater(String theater) {
this.theater = theater;
}
public String getTheater() {
return theater;
}
}
public static class RatingsEntity {
private String critics_rating;
private int critics_score;
private String audience_rating;
private int audience_score;
public void setCritics_rating(String critics_rating) {
this.critics_rating = critics_rating;
}
public void setCritics_score(int critics_score) {
this.critics_score = critics_score;
}
public void setAudience_rating(String audience_rating) {
this.audience_rating = audience_rating;
}
public void setAudience_score(int audience_score) {
this.audience_score = audience_score;
}
public String getCritics_rating() {
return critics_rating;
}
public int getCritics_score() {
return critics_score;
}
public String getAudience_rating() {
return audience_rating;
}
public int getAudience_score() {
return audience_score;
}
}
public static class PostersEntity {
private String thumbnail;
private String profile;
private String detailed;
private String original;
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public void setProfile(String profile) {
this.profile = profile;
}
public void setDetailed(String detailed) {
this.detailed = detailed;
}
public void setOriginal(String original) {
this.original = original;
}
public String getThumbnail() {
return thumbnail;
}
public String getProfile() {
return profile;
}
public String getDetailed() {
return detailed;
}
public String getOriginal() {
return original;
}
}
public static class LinksEntity {
private String self;
private String alternate;
private String cast;
private String reviews;
private String similar;
public void setSelf(String self) {
this.self = self;
}
public void setAlternate(String alternate) {
this.alternate = alternate;
}
public void setCast(String cast) {
this.cast = cast;
}
public void setReviews(String reviews) {
this.reviews = reviews;
}
public void setSimilar(String similar) {
this.similar = similar;
}
public String getSelf() {
return self;
}
public String getAlternate() {
return alternate;
}
public String getCast() {
return cast;
}
public String getReviews() {
return reviews;
}
public String getSimilar() {
return similar;
}
}
public static class AbridgedCastEntity {
private String name;
private String id;
private List<String> characters;
public void setName(String name) {
this.name = name;
}
public void setId(String id) {
this.id = id;
}
public void setCharacters(List<String> characters) {
this.characters = characters;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public List<String> getCharacters() {
return characters;
}
}
}
}
package com.example.nano1.gsonexample;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class CustomAdapter extends BaseAdapter {
private List<Response.MoviesEntity> mMovieItem;
private Context context;
private LayoutInflater inflater;
public CustomAdapter(Context context, List<Response.MoviesEntity> mMovieItem) {
this.context = context;
this.mMovieItem = mMovieItem;
}
#Override
public int getCount() {
return mMovieItem.size();
}
#Override
public Object getItem(int position) {
return mMovieItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.each_list_item, parent, false);
Response.MoviesEntity item = (Response.MoviesEntity) getItem(position);
ImageView thumbnail = (ImageView) rowView.findViewById(R.id.thumnnail);
TextView title = (TextView) rowView.findViewById(R.id.title);
TextView rating = (TextView) rowView.findViewById(R.id.rating);
String imageURL = item.getPosters().getOriginal();
Picasso.with(context).load(imageURL).into(thumbnail);
title.setText(item.getTitle());
rating.setText(item.getRatings().getAudience_rating());
return rowView;
}
}
in the declared classes above you have members of type int now in the response you are getting values for these members as empty string "" which is not allowed, it should be an integer. that makes the exception, you either:
1- change member type to String, and handle empty string as 0 in the setters/getters
or
2- ask the back-end team to send correct data
or
3- use a custom TypedAdapter in the Gson converter to handle integers when they have empty string
P.S: i am aware the sample json does not contain empty strings but on the real call on the service, you might have an empty strings for integer members