ExpandableList View from Json - android

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

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 ...

Unable to fetch the data from Firebase Database

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.

Use Retrofit to display JsonObject information in Recylerview?

I tried to display jsonObject in Recyclerview use retrofit library, but it only accept in the Array format. I tried to change the jsonObject to jsonArray, but the problem is the server don't recognize the json type. So now my question is, how to display jsonObject to recyclerview widget. Give me tips or idea..Thank in advance
This is my Jsonobject Data..
{
"success": true,
"data": {
"id": 1,
"parent_id": null,
"name": "Ionnex Sdn Bhd",
"description": "Test Value",
"image": "http://www.ionnex.com/images/logo_ionnex.png",
"phone_no": "12345678",
"fax": "123456",
"address": "Kl Sentral",
"latitude": 0,
"longitude": 0,
"created_at": "2017-08-15 02:26:00",
"donors_count": "4",
"donors_amount": "601.00"
}
}
This is my Fragment connect to the recyclerview widget.
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
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.ImageView;
import com.baracode.eilsan.data.ApiRequest;
import com.baracode.eilsan.donate.DonateMenuActivity;
import com.baracode.eilsan.donate.parentOrganisation.ParentOrganisationActivity;
import com.baracode.eilsan.donate.parentOrganisation.adapter.DonateParentOrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationModel;
import com.baracode.eilsan.R;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import static android.R.id.message;
public class OrganisationFragment extends Fragment {
private ViewPager viewPager;
private ImageView mosqueImage;
private RecyclerView recyclerView;
// private ArrayList<OrganisationModel> organisationModelArrayList = new ArrayList<>();
private ArrayList<Organisation> organisationList = new ArrayList<>();
// Organisation organisationList = new Organisation();
private OrganisationAdapter organisationAdapter;
private OrganisationFragment.MainPagerAdapter adapter;
private Organisation organisation;
private Context context;
private ApiRequest apiRequest;
public Organisation selectedOrganization = null;
public OrganisationFragment() {
// Required empty public constructor
}
public View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_organisation, container, false);
recyclerView = rootView.findViewById(R.id.organisation_recyclerview);
mosqueImage = rootView.findViewById(R.id.donate_fragment_mosque_image);
// organisationModelArrayList.clear();
prepareOrganisationData();
// Organisation org = ParentOrganisationActivity.selectedOrganization;
// recyclerView.setAdapter();
return rootView;
}
//here create parse
public static OrganisationFragment newInstance(Organisation organisation) {
OrganisationFragment fragment = new OrganisationFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
fragment.selectedOrganization = organisation;
return fragment;
}
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private FragmentManager fragmentManager;
private final ArrayList<Fragment> fragmentList = new ArrayList<>();
private final ArrayList<String> fragmentTitleList = new ArrayList<>();
MainPagerAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
}
//Organisation data change here
private void prepareOrganisationData() {
// OrganisationModel organisationModel = new OrganisationModel("Masjid Sultan Abu Bakar", "Kuala Lumpur", R.drawable.mosque_1);
// this.organisationModelArrayList.add(organisationModel);
//
// organisationModel = new OrganisationModel("Masjid Zahir", "Kuala Lumpur", R.drawable.mosque_2);
// this.organisationModelArrayList.add(organisationModel);
Bundle extras = getActivity().getIntent().getExtras();
if (extras == null) {
selectedOrganization = null;
} else {
Gson gson = new Gson();
// Gson gson = new GsonBuilder().serializeNulls().create();
selectedOrganization = gson.fromJson(extras.getString("org"), Organisation.class);
Organisation org = selectedOrganization;
Picasso.with(context).load(org.getImage()).into(mosqueImage);
}
ApiRequest.getInstance().getOrganisationIdDetails(getActivity(), selectedOrganization.id, new ApiRequest.GetAllOrgIdDetailsCallback() {
#Override
public void getAllOrgIdDetailsSuccess(ArrayList<Organisation> result) {
organisationList = result;
organisationAdapter = new OrganisationAdapter(organisationList, context);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(organisationAdapter);
}
#Override
public void getAllOrgDetailsFail(String message) {
}
});
}
/* TODO
add onClick listener to each object
*/
}
This is my Fragment Adapter..
import android.content.Context;
import android.content.Intent;
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.LinearLayout;
import android.widget.TextView;
import com.baracode.eilsan.R;
import com.baracode.eilsan.donate.organisation.OrganisationActivity;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class OrganisationAdapter extends RecyclerView.Adapter<OrganisationAdapter.MyViewHolder> {
private Context context;
// private final ArrayList<OrganisationModel> organisationModelList;
ArrayList<Organisation> organisationModelList;
public OrganisationAdapter(ArrayList<Organisation> organisationModelList , Context context) {
this.organisationModelList = organisationModelList;
this.context = context;
}
#Override
public OrganisationAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_organisation_recyclerview, parent, false);
return new OrganisationAdapter.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(OrganisationAdapter.MyViewHolder holder, int position) {
// OrganisationModel organisationModel = organisationModelList.get(position);
final Organisation organisationModel = organisationModelList.get(position);
holder.organisationName.setText(organisationModel.getName());
holder.cityName.setText(organisationModel.getAddress());
// holder.mosqueImage.setImageResource(organisationModel.getOrganisationImage());
Picasso.with(context)
.load(organisationModel.getImage())
.into(holder.mosqueImage);
holder.headlineLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.organisation_linearlayout:
intent = new Intent(view.getContext(), OrganisationActivity.class);
view.getContext().startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return organisationModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView organisationName, cityName;
public ImageView mosqueImage;
public LinearLayout headlineLinearLayout;
public MyViewHolder(View view) {
super(view);
organisationName = view.findViewById(R.id.donate_parent_organisation_name);
cityName = view.findViewById(R.id.donate_parent_organisation_city_name);
mosqueImage = view.findViewById(R.id.donate_parent_organisation_image);
headlineLinearLayout = view.findViewById(R.id.organisation_linearlayout);
}
}
/* TODO
* Implement on click listener on the recyclerview
* */
}
This is my Fragment Model(Setter n Getter)
public class OrganisationModel {
private String organisationName = "";
private String cityName = "";
private int organisationImage;
public int getOrganisationImage() {
return organisationImage;
}
public void setOrganisationImage(int organisationImage) {
this.organisationImage = organisationImage;
}
public String getOrganisationName() {
return organisationName;
}
public void setOrganisationName(String organisationName) {
this.organisationName = organisationName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public OrganisationModel(String organisationName, String cityName, int organisationImage) {
this.organisationName = organisationName;
this.cityName = cityName;
this.organisationImage = organisationImage;
}
}
This is MyApirequest class to get the Json Object
public void getOrganisationIdDetails(final Context context, String organizationIdDetails, final GetAllOrgIdDetailsCallback apiCallback) {
String accessToken = LocalData.getInstance().loadStringData(LocalData.KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOrgIdDetails("Bearer " + accessToken, organizationIdDetails);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("eihsan", "getOrgIdDetails: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
//JsonArray jsonArray = jsonData.getAsJsonArray("data");
Organisation org = new Organisation();
// ArrayList<Organisation> organisationList = new ArrayList<>();
org.setId(jsonData.get("id").getAsString());
org.setParentId(jsonData.get("parent_id").toString());
org.setName(jsonData.get("name").getAsString());
org.setDescription(jsonData.get("description").getAsString());
org.setImage(jsonData.get("image").getAsString());
org.setPhone_no(jsonData.get("phone_no").getAsString());
org.setFax(jsonData.get("fax").getAsString());
org.setAddress(jsonData.get("address").getAsString());
org.setLatitude(jsonData.get("latitude").getAsString());
org.setLongitude(jsonData.get("longitude").getAsString());
org.setDonorCount(jsonData.get("donors_count").getAsString());
apiCallback.getAllOrgIdDetailsSuccess(org);
} else {
apiCallback.getAllOrgDetailsFail("Data Error occurred");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
}
});
}
AFTER FEW MONTH, I SOLVED THE PROBLEM..
Use retrofit library and call the api before display. So here how to call the data for future reference....
public void getOneOrg(String orgId, final GetOneOrgCallback apiCallback) {
String auth = "Bearer " + LocalData.getInstance().loadStringData(LocalData.SP_KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOneOrg(auth, orgId);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
StaticFunction.showLogD("getOneOrg: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
Organization org = gson.fromJson(jsonData, Organization.class);
apiCallback.getOneOrgSuccess(org);
} else {
apiCallback.getOneOrgFail("Data error");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
apiCallback.getOneOrgFail("Data error");
}
});
}
Here how i called the json object in API "Organization" is the java file for each variables in api.

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);
}
}
}

Recycler view not showing after parsing json data using Volley

Inside my tab bar i want to show my data in Recycler view by using json parsing using volley library. I parsed the data and it showing in toast perfectly.But in Recycler view its not showing Here is my codes.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
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.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.transform.ErrorListener;
import info.tatwa.adupter.AdupterBoxOffice;
import info.tatwa.extras.Keys;
import info.tatwa.extras.UrlEndPoint;
import info.tatwa.login.L;
import info.tatwa.model.Movies;
import info.tatwa.network.MyApplication;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
import info.tatwa.extras.UrlEndPoint.*;
import info.tatwa.extras.Keys.EndpointBoxOffice.*;
public class FragmentBoxOffice extends Fragment {
private VolleySingleton volleySingleton;
private RequestQueue requestQueue;
private AdupterBoxOffice adupterBoxOffice;
private ArrayList<Movies>listMovie = new ArrayList<>();
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final String ROTET_TOMATO_URL_BOX_OFFICE="My url is here"
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView listMovieHits;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentBoxOffice.
*/
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static String getRequestUrl(int limit){
//ROTET_TOMATO_URL_BOX_OFFICE+"?apikey="+ MyApplication.ROTET_TOMATO_API_KEY+"&limit="+limit;
return UrlEndPoint.URL_BOX_OFFICE +
UrlEndPoint.URL_CHAR_QUASTIAN+
UrlEndPoint.URL_CHAR_PAREM_APIKEY +
MyApplication.ROTET_TOMATO_API_KEY +
UrlEndPoint.URL_CHAR_APPEND+
UrlEndPoint.URL_CHAR_PAREM_LIMIT + limit;
}
public FragmentBoxOffice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getmRequestQueue();
senJsonRequest();
}
public void senJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10), (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
paresJSONResponse(response);
listMovie =paresJSONResponse(response);
adupterBoxOffice.setMovieList(listMovie);
L.t(getActivity(), response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Error"+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(request);
}
public ArrayList<Movies> paresJSONResponse(JSONObject response){
ArrayList<Movies> listMovie = new ArrayList<>();
if(response ==null|| response.length()==0 ){
return null;
}
try {
StringBuilder data = new StringBuilder();
JSONArray arrayMovie = response.getJSONArray(Keys.EndpointBoxOffice.KEY_MOVIES);
Log.v("BIKASH", "JSON Object id" + arrayMovie);
for(int i = 0; i<arrayMovie.length();i++){
JSONObject currentMovies= arrayMovie.getJSONObject(i);
Long id =currentMovies.getLong(Keys.EndpointBoxOffice.KEY_ID);
String title=currentMovies.getString(Keys.EndpointBoxOffice.KEY_TITLE);
JSONObject objectReleaseDates=currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RELEASE_DATES);
String releaseDate=null;
if(objectReleaseDates.has(Keys.EndpointBoxOffice.KEY_THEATER)){
releaseDate = objectReleaseDates.getString(Keys.EndpointBoxOffice.KEY_THEATER);
}
else {
releaseDate="NA";
}
int audianceRatting=-1;
JSONObject objectRatting = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RATINGS);
{
if(objectRatting.has(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE)){
audianceRatting=objectRatting.getInt(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE);
}
}
String synuypsis = currentMovies.getString(Keys.EndpointBoxOffice.KEY_SYNOPSIS);
String urlThumbnel = null;
JSONObject objPoster = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
if(objPoster.has(Keys.EndpointBoxOffice.KEY_THUMBNAIL)){
urlThumbnel = objPoster.getString(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
}
Movies movie =new Movies();
movie.setId(id);
movie.setTitle(title);
Date date = dateFormat.parse(releaseDate);
movie.setReleaseDateTheater(date);
movie.setAudienceScore(audianceRatting);
movie.setSynopsis(synuypsis);
movie.setUrlThumbnail(urlThumbnel);
listMovie.add(movie);
// data.append(id + "\n");
}
L.t(getActivity(),listMovie.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return listMovie;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_fragment_box_office, container, false);
listMovieHits =(RecyclerView)view.findViewById(R.id.listMovieHits);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
adupterBoxOffice = new AdupterBoxOffice(getActivity());
listMovieHits.setAdapter(adupterBoxOffice);
senJsonRequest();
return view;
}
}
My Adupter
import android.content.Context;
import android.support.v4.app.FragmentActivity;
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.RatingBar;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import java.util.ArrayList;
import info.tatwa.model.Movies;
import info.tatwa.myfragment.FragmentBoxOffice;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
public class AdupterBoxOffice extends RecyclerView.Adapter<AdupterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
FragmentBoxOffice activity;
private ArrayList<Movies> listMovie = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
public AdupterBoxOffice(Context context){
layoutInflater=LayoutInflater.from(context);
volleySingleton=VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movies>listMovie){
this.listMovie = listMovie;
notifyItemRangeChanged(0,listMovie.size());
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.movie_list_itom,parent,false);
ViewHolderBoxOffice viewHolder =new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movies currentMovie =listMovie.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
holder.movieReleaseDate.setText(currentMovie.getReleaseDateTheater().toString());
holder.movieRatting.setRating(currentMovie.getAudienceScore()/20.0f);
String urlThumbnel = currentMovie.getUrlThumbnail();
if(urlThumbnel!=null){
imageLoader.get(urlThumbnel, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.imagePoster.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return listMovie.size();
}
static class ViewHolderBoxOffice extends RecyclerView.ViewHolder {
private ImageView imagePoster;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieRatting;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
imagePoster=(ImageView)itemView.findViewById(R.id.movieThumbnail);
movieTitle =(TextView)itemView.findViewById(R.id.movieTitle);
movieReleaseDate=(TextView)itemView.findViewById(R.id.movieReleaseDate);
movieRatting=(RatingBar)itemView.findViewById(R.id.movieAudienceScore);
}
}
}
And My Model class
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
public class Movies{
private long id;
private String title;
private Date releaseDateTheater;
private int audienceScore;
private String synopsis;
private String urlThumbnail;
private String urlSelf;
private String urlCast;
private String urlReviews;
private String urlSimilar;
public Movies() {
}
public Movies(long id,
String title,
Date releaseDateTheater,
int audienceScore,
String synopsis,
String urlThumbnail,
String urlSelf,
String urlCast,
String urlReviews,
String urlSimilar) {
this.id = id;
this.title = title;
this.releaseDateTheater = releaseDateTheater;
this.audienceScore = audienceScore;
this.synopsis = synopsis;
this.urlThumbnail = urlThumbnail;
this.urlSelf = urlSelf;
this.urlCast = urlCast;
this.urlReviews = urlReviews;
this.urlSimilar = urlSimilar;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReleaseDateTheater() {
return releaseDateTheater;
}
public void setReleaseDateTheater(Date releaseDateTheater) {
this.releaseDateTheater = releaseDateTheater;
}
public int getAudienceScore() {
return audienceScore;
}
public void setAudienceScore(int audienceScore) {
this.audienceScore = audienceScore;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getUrlThumbnail() {
return urlThumbnail;
}
public void setUrlThumbnail(String urlThumbnail) {
this.urlThumbnail = urlThumbnail;
}
public String getUrlSelf() {
return urlSelf;
}
public void setUrlSelf(String urlSelf) {
this.urlSelf = urlSelf;
}
public String getUrlCast() {
return urlCast;
}
public void setUrlCast(String urlCast) {
this.urlCast = urlCast;
}
public String getUrlReviews() {
return urlReviews;
}
public void setUrlReviews(String urlReviews) {
this.urlReviews = urlReviews;
}
public String getUrlSimilar() {
return urlSimilar;
}
public void setUrlSimilar(String urlSimilar) {
this.urlSimilar = urlSimilar;
}
#Override
public String toString() {
return "\nID: " + id +
"\nTitle " + title +
"\nDate " + releaseDateTheater +
"\nSynopsis " + synopsis +
"\nScore " + audienceScore +
"\nurlThumbnail " + urlThumbnail +
"\nurlSelf " + urlSelf +
"\nurlCast " + urlCast +
"\nurlReviews " + urlReviews +
"\nurlSimilar " + urlSimilar +
"\n";
}
}
Please help me out .. Thanks in advance ..
After adupterBoxOffice.setMovieList(listMovie);
try add adupterBoxOffice.notifyDataSetChanged();
I found my solution.I put some wrong key during pars the Json. That's why my ArrayList returning zero.
Many many thanks to all for helping me out.

Categories

Resources