Pass data from RecyclerView to RecyclerViewMore using Serializable - AndroidX - java

I want to show all items in RecyclerView in Fragment to RecyclerViewMore in Another Activity when I press "See All Items", but I getting null when I want to receive the data from RecyclerViewMore
//SectionAdapter.java
public class AdapterSectionHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_section_hottrendingnews, null);
return new SectionHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionHotTrendingNewsViewHolder sectionHotTrendingNewsViewHolder = (SectionHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
ArrayList singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterSingleHotTrendingNews itemListDataAdapter = new AdapterSingleHotTrendingNews(mContext, singleSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() { #Override public void onClick(View v) {
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
new Intent().putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent); } });
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setHasFixedSize(true);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewSectionHotTrendingNews;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerView_Section_HotTrendingNews);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}
//SingleAdapter.java
public class AdapterSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_single_hottrendingnews, null);
return new SingleHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleHotTrendingNewsViewHolder singleHotTrendingNewsViewHolder = (SingleHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//ModelSection.java
public class ModelSectionHotTrendingNews implements Serializable {
private String headerTitle;
private ArrayList<ModelSingleHotTrendingNews> allItemsInSection;
public ModelSectionHotTrendingNews() {
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<ModelSingleHotTrendingNews> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<ModelSingleHotTrendingNews> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
//ModelSingle.java
public class ModelSingleHotTrendingNews implements Serializable {
private int id;
private String gamedate;
private String gamedescription;
private int gameimage;
private Boolean trendingnewssaving;
private String value;
private String message;
public ModelSingleHotTrendingNews(int id, String gamedate, String gamedescription, int gameimage, Boolean trendingnewssaving, String value, String message) {
this.id = id;
this.gamedate = gamedate;
this.gamedescription = gamedescription;
this.gameimage = gameimage;
this.trendingnewssaving = trendingnewssaving;
this.value = value;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getGameimage() {
return gameimage;
}
public void setGameimage(int gameimage) {
this.gameimage = gameimage;
}
public Boolean getTrendingnewssaving() {
return trendingnewssaving;
}
public void setTrendingnewssaving(Boolean trendingnewssaving) {
this.trendingnewssaving = trendingnewssaving;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
//This function SectionAdapter.java is to send data from RecyclerView in Fragment to RecyclerViewMore Activity
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() { #Override public void onClick(View v) {
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
new Intent().putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent); } });
//I use same Model in those RecyclerViews but different Adapter
//I use RecyclerView in Fragment AdapterSection.java,AdapterSingle.java,ModelSection.java,ModelSingle.java
//I user RecyclerViewMore in Activity
AdapterMoreSection.java,AdapterMoreSingle.java,ModelSection.java,ModelSingle.java
//RecyclerViewMoreActivity.java
public class TabMoreHotActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentmore_tabhot);
AdapterMoreSectionHotTrendingNews adapterMoreSectionHotTrendingNews;
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = null;
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
{
modelSectionHotTrendingNews = (ArrayList<ModelSectionHotTrendingNews>) bundle.getSerializable("MoreNews");
}
//1
RecyclerView RecyclerViewMoreSingleHotTrendingNews = findViewById(R.id.RecyclerViewMore_Single_HotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
adapterMoreSectionHotTrendingNews = new AdapterMoreSectionHotTrendingNews(this, modelSectionHotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setAdapter(adapterMoreSectionHotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//Optimized
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewMoreSingleHotTrendingNews.setItemViewCacheSize(20);
}
}
//I got this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.indofun.android.indojoy, PID: 32309
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.indofun.android.indojoy.Adapters.AdapterMore_HotTrendingNews.AdapterMoreSectionHotTrendingNews.getItemCount(AdapterMoreSectionHotTrendingNews.java:109)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:4042)
at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3532)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23279)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23279)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:898)
at android.view.View.measure(View.java:23279)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2873)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1910)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2165)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1779)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7810)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:658)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
//Provide the code it will help me a lot
//UPDATED
//AdapterMoreSingle
public class AdapterMoreSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterMoreSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemmore_single_hottrendingnews, null);
return new SingleMoreHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleMoreHotTrendingNewsViewHolder singleMoreHotTrendingNewsViewHolder = (SingleMoreHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleMoreHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleMoreHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleMoreHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleMoreHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//UPDATED2 AdapterSectionMore.java
public class AdapterMoreSectionHotTrendingNews extends RecyclerView.Adapter {
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterMoreSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemmore_section_hottrendingnews, null);
return new SectionMoreHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionMoreHotTrendingNewsViewHolder sectionMoreHotTrendingNewsViewHolder = (SectionMoreHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionMoreHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
// here you have to change your ArrayList to ArrayList<ModelSingleHotTrendingNews>
ArrayList<ModelSingleHotTrendingNews> singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterMoreSingleHotTrendingNews itemListDataAdapter = new AdapterMoreSingleHotTrendingNews(mContext, singleSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
final String sectionTitle = modelSectionHotTrendingNewsX.getHeaderTitle();
sectionMoreHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() {
#Override public void onClick(View v) {
//More IN RecyclerViewMore
}
});
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setHasFixedSize(true);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}

Because you are passing null modelSectionHotTrendingNews to your adapter.
You just need to initialize your ArrayList in your TabMoreHotActivity
And one more thing you have to set layout manger to your recycler view before set adapter.
public class TabMoreHotActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentmore_tabhot);
AdapterMoreSectionHotTrendingNews adapterMoreSectionHotTrendingNews;
// here you have to initialize it
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = new ArrayList<>();
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
{
modelSectionHotTrendingNews = (ArrayList<ModelSectionHotTrendingNews>) bundle.getSerializable("MoreNews");
}
//1
RecyclerView RecyclerViewMoreSingleHotTrendingNews = findViewById(R.id.RecyclerViewMore_Single_HotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
adapterMoreSectionHotTrendingNews = new AdapterMoreSectionHotTrendingNews(this, modelSectionHotTrendingNews);
// here have to set layout manager before set adapter
RecyclerViewMoreSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
// and then you have to set adapter to recyclerview
RecyclerViewMoreSingleHotTrendingNews.setAdapter(adapterMoreSectionHotTrendingNews);
//Optimized
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewMoreSingleHotTrendingNews.setItemViewCacheSize(20);
}
}
UPDATE
Change ArrayList to ArrayList<ModelSingleHotTrendingNews> inside onBindViewHolder in AdapterMoreSectionHotTrendingNews.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionMoreHotTrendingNewsViewHolder sectionMoreHotTrendingNewsViewHolder = (SectionMoreHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionMoreHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
// here you have to change your ArrayList to ArrayList<ModelSingleHotTrendingNews>
ArrayList<ModelSingleHotTrendingNews> singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
// reset of your codes here.

For this error
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
By #Jakir answer, you can initialize ArrayList for extra point initialize with specific size (i.e new ArrayList<>(0);) to reduce the memory usage because of array list default a lot memory of 10 objects in memory.
or
check this condition in getItem
#Override
public int getItemCount() {
return modelSectionHotTrendingNews != null && modelSectionHotTrendingNews.size();
}
It will resolve this error.
For serializable parsing in your code
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
// here you create put extra in new intent not the intent that you created
new Intent().putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent);
Change this to
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
// here you create put extra in new intent not the intent that you created
intent.putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent);
Happy coding.... ;)

Related

Transition between 2 recycler views having cards

I have 2 recycler views that have cards.They basically look the same have the same number of cards and everthing. The first one is for like viewing and other stuff and the second one is only for deleting cards. OnlongClicking a card in the first recycler view triggers the opening of the second recycler view. I wanted to add transitions in between them like what keep notes has done when a card is long clicked. Both the recycler view use the same adapter. I have set what the adapter should do based on passing context to the adapter. enter image description here this is my 1st layout having the 1st recycler view.enter image description here this is the 2nd layout having the second recycler view.I want like a seamless transition for the tool bar again just like what Google keeps has done.A simple solution would be preferred as I am very new to this stuff.
Here is the java code for the adapter.
public class Task_recycle_view_adapter extends RecyclerView.Adapter<Task_recycle_view_adapter.ViewHolder>{
private List<struct_task> task_list= new ArrayList<>();
private ArrayList<String> isSelected=new ArrayList<String>();
protected Context context1;
protected Context context2;
private String labelName;
private String taskName;
private ConstraintLayout label_menu_avatar;
public Task_recycle_view_adapter(Context context1,Context context2)
{
this.context1=context1;
this.context2=context2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {//parent is the parent of the recycle view it is taken as an arg to use it to attach the every view to the parent view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_task,parent,false);//to inflate a layout
ViewHolder holder= new ViewHolder(view);
return holder;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.taskname.setText(task_list.get(position).getTask_name());
holder.taskid.setText(String.valueOf(task_list.get(position).getTask_id()));
if(context2==null && context1!=null) {
String taskName=task_list.get(position).getTask_name();
Long taskid=task_list.get(position).getTask_id();
String duedate=task_list.get(position).getDue_date();
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(context1);
ArrayList<SubTaskModel> subtask_list=(ArrayList<SubTaskModel>) dataBaseHelper.getAllSubTasksFor(labelName, Long.parseLong(holder.taskid.getText().toString()));
Intent intent1 =new Intent(context1,ViewTaskActivity.class);
intent1.putExtra("label_name",labelName);
intent1.putExtra("task_id",taskid);
intent1.putExtra("task_name",taskName);
intent1.putExtra("due_date",duedate);
intent1.putParcelableArrayListExtra("subtask_list", (ArrayList<? extends Parcelable>) subtask_list);
context1.startActivity(intent1);
}
});
holder.parent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent2 = new Intent(context1, Delete_page_Activity.class);
intent2.putParcelableArrayListExtra("task_list", (ArrayList<? extends Parcelable>) task_list);
intent2.putExtra("label_name",labelName);
intent2.putExtra("selected_task",taskName);
Pair[] pairs = new Pair[1];
pairs[0]= new Pair<View,String>(label_menu_avatar,"transition1");
ActivityOptions options= ActivityOptions.makeSceneTransitionAnimation((Activity) context1,pairs);
context1.startActivity(intent2,options.toBundle());
return true;
}
});
}
if(context2!=null && context1==null)
{
if(taskName.equals(task_list.get(position).getTask_name()))
{
holder.active=1;
isSelected.add(holder.taskid.getText().toString());
holder.parent.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
}
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.active==0) {
isSelected.add(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
holder.active=1;
}
else {
isSelected.remove(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card_transparent);
holder.active=0;
}
}
});
}
// subtasks 1 to 5
if(task_list.get(position).getSubtask1()!=null)
holder.subtask1.setText(task_list.get(position).getSubtask1());
else
holder.subtask1.setVisibility(View.GONE);
if(task_list.get(position).getSubtask2()!=null)
holder.subtask2.setText(task_list.get(position).getSubtask2());
else
holder.subtask2.setVisibility(View.GONE);
if(task_list.get(position).getSubtask3()!=null)
holder.subtask3.setText(task_list.get(position).getSubtask3());
else
holder.subtask3.setVisibility(View.GONE);
if(task_list.get(position).getSubtask4()!=null)
holder.subtask4.setText(task_list.get(position).getSubtask4());
else
holder.subtask4.setVisibility(View.GONE);
if(task_list.get(position).getSubtask5()!=null)
holder.subtask5.setText(task_list.get(position).getSubtask5());
else
holder.subtask5.setVisibility(View.GONE);
// due date
if(task_list.get(position).getDue_date()!=null)
holder.duedate.setText(task_list.get(position).getDue_date());
else
holder.duedate.setVisibility(View.GONE);
// progress
holder.progresscircle.setProgress(task_list.get(position).getProgress());
}
#Override
public int getItemCount() {
return task_list.size();
}
public void setTask_list(List<struct_task> task_list) {
this.task_list = task_list;//to refresh the data inside the recycler view
}
#Override
public int getItemViewType(int position) {
return position;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public ArrayList<String> getIsSelected() {
return isSelected;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setLabel_menu_avatar(ConstraintLayout label_menu_avatar) {
this.label_menu_avatar = label_menu_avatar;
}
public static class ViewHolder extends RecyclerView.ViewHolder{// holds the view for every item inside the recycle view
private TextView taskname,taskid,duedate,subtask1,subtask2,subtask3,subtask4,subtask5;
private CardView parent;
private ProgressBar progresscircle;
public void setActive(int active) {
this.active = active;
}
private int active;
public ViewHolder(#NonNull View itemView) {
super(itemView);
taskid=itemView.findViewById(R.id.task_id);
taskname = itemView.findViewById(R.id.task_name);
parent = itemView.findViewById(R.id.card_for_every_task);
duedate = itemView.findViewById(R.id.due_date);
progresscircle = itemView.findViewById(R.id.progress_circular);
subtask1 = itemView.findViewById(R.id.subtask_1);
subtask2 = itemView.findViewById(R.id.subtask_2);
subtask3 = itemView.findViewById(R.id.subtask_3);
subtask4 = itemView.findViewById(R.id.subtask_4);
subtask5 = itemView.findViewById(R.id.subtask_5);
active=0;
}
}
}
Here is the code for the 1st activity i.e the 1st image:
public class TaskPageActivity extends AppCompatActivity {
private RecyclerView task_rv;//task recycler view
private FloatingActionButton addTask;
private long tasksNum;
private String labelName;
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private Task_recycle_view_adapter adapter= new Task_recycle_view_adapter(this,null);
private List<struct_task> tasks;
private EditText searchBar;
private ConstraintLayout search_btn;
private ConstraintLayout calendar_btn;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_title);
getWindow().getSharedElementExitTransition();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
search_btn= findViewById(R.id.search_btn);
calendar_btn=findViewById(R.id.calendar_btn);
search_btn.setClickable(true);
search_btn.setFocusable(true);
labelName = getIntent().getExtras().getString("832715");
TextView txtLabelName = findViewById(R.id.Label_name);
txtLabelName.setText(labelName);
task_rv = findViewById(R.id.Recycle_view_task);
addTask = findViewById(R.id.add_task);
searchBar= (SearchBar) findViewById(R.id.search_bar);
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter); //displays all tasks and return number of tasks
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
addTask.setOnClickListener(view -> {
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter);
Intent intent = new Intent(TaskPageActivity.this, AddTaskPageActivity.class);
intent.putExtra("labelName", labelName);
intent.putExtra("taskID", tasksNum);
startActivity(intent);
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(searchBar.getVisibility()==View.INVISIBLE) {
search_btn.setAlpha(.5f);
searchBar.setVisibility(View.VISIBLE);
searchBar.requestFocus();
imm.showSoftInput(searchBar,InputMethodManager.SHOW_IMPLICIT);
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
searchBar.requestFocus();
}
else {
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
}
});
searchBar.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
if(params.verticalBias==.9f) {
searchBar.requestFocus();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
}
searchBar.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER) && params.verticalBias==.55f)
{
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
imm.hideSoftInputFromWindow(searchBar.getWindowToken(),0);
}
return false;
}
});
}
}
});
searchBar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
AlertDialog alertDialog = new AlertDialog.Builder(TaskPageActivity.this).create();
calendar_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(calendar_btn.getAlpha()==1.0f) {
calendar_btn.setAlpha(.5f);
LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.dialog_calendar,null);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(view1);
CalendarView mCalendarView= view1.findViewById(R.id.calendar);
mCalendarView.setMinDate(Calendar.getInstance().getTimeInMillis());
alertDialog.show();
}
}
});
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(calendar_btn.getAlpha()==.5f)
calendar_btn.setAlpha(1.0f);
}
});
}
private void filter(String string) {
ArrayList<struct_task> filteredList = new ArrayList<>();
for(struct_task item: tasks)
{
if(item.getTask_name().contains(string) || item.getTask_name().contains(string.toUpperCase()))
{
filteredList.add(item);
}
}
if(filteredList.size()!=0) {
adapter.setTask_list(filteredList);
task_rv.setAdapter(adapter);
}
}
#Override
public void onBackPressed() {
if(searchBar.getText().toString().length()!=0) {
showAllTasks(labelName, dataBaseHelper, adapter);
searchBar.setText(null);
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
else if(searchBar.getText().toString().length()==0)
{
super.onBackPressed();
}
}
#Override
protected void onResume() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
showAllTasks(labelName, dataBaseHelper, adapter);
if(params.verticalBias==.54f) {
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
}
if(searchBar.getText().toString().length()==0) {
showAllTasks(labelName, dataBaseHelper, adapter);
}
else {
filter(searchBar.getText().toString());
}
super.onResume();
}
private void showAllTasks(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
tasks = dataBaseHelper.getAllTasksFor(labelName);
adapter.setLabelName(labelName);
adapter.setTask_list(tasks);
task_rv.setAdapter(adapter);
task_rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
}
long getTasksNum(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
return dataBaseHelper.getLastTaskID(labelName)+1; //to determine ID of next task
}
#Override
protected void onUserLeaveHint() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias=.9f;
searchBar.setLayoutParams(params);
searchBar.setText(null);
searchBar.clearFocus();
super.onUserLeaveHint();
}
}
And finally for the 2nd activity which is triggered by longclicking any card
public class Delete_page_Activity extends AppCompatActivity {
private Task_recycle_view_adapter recycle_view_adapter = new Task_recycle_view_adapter(null,this);
private ArrayList<String> delete_list=new ArrayList<>();
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private String labelName=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_page);
overridePendingTransition(0,0);
Toolbar toolbar=findViewById(R.id.toolbar_bar);
ImageView close_btn=findViewById(R.id.close_btn);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
ArrayList<struct_task> task_list = getIntent().getParcelableArrayListExtra("task_list");
labelName=getIntent().getExtras().getString("label_name");
String task = getIntent().getExtras().getString("selected_task");
Log.e("test",labelName);
RecyclerView recyclerView = findViewById(R.id.delete_Recycler_View);
recycle_view_adapter.setTaskName(task);
recycle_view_adapter.setTask_list(task_list);
recyclerView.setAdapter(recycle_view_adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
close_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.tool_bar_item1:
delete_list = recycle_view_adapter.getIsSelected();
if(delete_list.size()==0)
{
Toast toast1= new Toast(this);
toast1.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg1,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast1.setView(view);
toast1.show();
}
else {
for (int task = 0; task < delete_list.size(); task++) {
dataBaseHelper.deleteOneTask(labelName, Long.parseLong(delete_list.get(task)));
}
finish();
}
break;
case R.id.tool_bar_item2:
Boolean flag=dataBaseHelper.deleteAllCompletedTasks(labelName);
if(flag)
finish();
else
{
Toast toast2= new Toast(this);
toast2.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg2,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast2.setView(view);
toast2.show();
}
break;
}
return true;
}
}
I have added the code related to the scene transititon which is in the adapter.
here is a gif of the problem when i add a scene transition
enter image description here
As u can see there are 2 pauses when going from 1st to 2nd activity 1st pause being longer 2nd one shorter. And also a pause when exiting the 2nd activity which seems to have the same duration as the 2nd pause.

Why I cannot pass data from RecyclerView to another RecyclerView - AndroidX

I want to make data from RecyclerView1 Activity1 can be passed to RecyclerView2 Activity2
//SectionAdapter.java
public class AdapterSectionHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_section_hottrendingnews, null);
return new SectionHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionHotTrendingNewsViewHolder sectionHotTrendingNewsViewHolder = (SectionHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
ArrayList singleSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterSingleHotTrendingNews itemListDataAdapter = new AdapterSingleHotTrendingNews(mContext, singleSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
sectionHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() { #Override public void onClick(View v) {
Intent intent = new Intent(mContext, TabMoreHotActivity.class);
// here you create put extra in new intent not the intent that you created
intent.putExtra("MoreNews", modelSectionHotTrendingNews.get(position).getAllItemsInSection());
mContext.startActivity(intent);
} });
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setHasFixedSize(true);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionHotTrendingNewsViewHolder.RecyclerViewSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewSectionHotTrendingNews;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerView_Section_HotTrendingNews);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}
//SingleAdapter.java
public class AdapterSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_single_hottrendingnews, null);
return new SingleHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleHotTrendingNewsViewHolder singleHotTrendingNewsViewHolder = (SingleHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//ModelSection.java
public class ModelSectionHotTrendingNews implements Serializable {
private String headerTitle;
private ArrayList<ModelSingleHotTrendingNews> allItemsInSection;
public ModelSectionHotTrendingNews() {
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<ModelSingleHotTrendingNews> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<ModelSingleHotTrendingNews> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
//ModelSingle.java
public class ModelSingleHotTrendingNews implements Serializable {
private int id;
private String gamedate;
private String gamedescription;
private int gameimage;
private Boolean trendingnewssaving;
private String value;
private String message;
public ModelSingleHotTrendingNews(int id, String gamedate, String gamedescription, int gameimage, Boolean trendingnewssaving, String value, String message) {
this.id = id;
this.gamedate = gamedate;
this.gamedescription = gamedescription;
this.gameimage = gameimage;
this.trendingnewssaving = trendingnewssaving;
this.value = value;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getGameimage() {
return gameimage;
}
public void setGameimage(int gameimage) {
this.gameimage = gameimage;
}
public Boolean getTrendingnewssaving() {
return trendingnewssaving;
}
public void setTrendingnewssaving(Boolean trendingnewssaving) {
this.trendingnewssaving = trendingnewssaving;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
//AdapterMoreSection.java
public class AdapterMoreSectionHotTrendingNews extends RecyclerView.Adapter {
private Context mContext;
private ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews;
public AdapterMoreSectionHotTrendingNews(Context mContext, ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews) {
this.mContext = mContext;
this.modelSectionHotTrendingNews = modelSectionHotTrendingNews;
}
#Override
public SectionMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemmore_section_hottrendingnews, null);
return new SectionMoreHotTrendingNewsViewHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SectionMoreHotTrendingNewsViewHolder sectionMoreHotTrendingNewsViewHolder = (SectionMoreHotTrendingNewsViewHolder) holder;
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = modelSectionHotTrendingNews.get(position);
//Set
sectionMoreHotTrendingNewsViewHolder.TVSectionTitle.setText(modelSectionHotTrendingNewsX.getHeaderTitle());
ArrayList singleMoreSectionItems = modelSectionHotTrendingNewsX.getAllItemsInSection();
/*AdapterSingleHotLatestNews.RecyclerViewClickListener listenerLatestNews;
listenerLatestNews = new AdapterSingleHotLatestNews.RecyclerViewClickListener() {
#Override
public void onRowHotLatestNewsClick(View view, int position) {
}
#Override
public void onIconHotLatestNewsClick(View view, int position) {
}
};*/
AdapterMoreSingleHotTrendingNews itemListDataAdapter = new AdapterMoreSingleHotTrendingNews(mContext, singleMoreSectionItems);
/*itemRowHolder.recycler_view_list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
//Allow ScrollView to intercept touch events once again.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle RecyclerView touch events.
v.onTouchEvent(event);
return true;
}
});*/
final String sectionTitle = modelSectionHotTrendingNewsX.getHeaderTitle();
sectionMoreHotTrendingNewsViewHolder.BTNHotTrendingNewsMore.setOnClickListener(
new View.OnClickListener() {
#Override public void onClick(View v) {
//More IN RecyclerViewMore
}
});
/*Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
//SetRecyclerView
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setHasFixedSize(true);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setAdapter(itemListDataAdapter);
sectionMoreHotTrendingNewsViewHolder.RecyclerViewMoreSectionHotTrendingNews.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
int itemCount = modelSectionHotTrendingNews.size();
return itemCount;
}
public class SectionMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder {
protected TextView TVSectionTitle;
protected ImageView BTNHotTrendingNewsMore;
protected RecyclerView RecyclerViewMoreSectionHotTrendingNews;
public SectionMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVSectionTitle = (TextView) itemView.findViewById(R.id.TV_SectionTitle);
BTNHotTrendingNewsMore= (ImageView) itemView.findViewById(R.id.BTN_HotTrendingNewsMore);
RecyclerViewMoreSectionHotTrendingNews = (RecyclerView) itemView.findViewById(R.id.RecyclerViewMore_Section_HotTrendingNews);
}
}
}
//AdapterMoreSingle.java
public class AdapterMoreSingleHotTrendingNews extends RecyclerView.Adapter{
private Context mContext;
private ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
public AdapterMoreSingleHotTrendingNews(Context mContext, ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews) {
this.mContext = mContext;
this.modelSingleHotTrendingNews = modelSingleHotTrendingNews;
}
//Container
#Override
public SingleMoreHotTrendingNewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemmore_single_hottrendingnews, null);
return new SingleMoreHotTrendingNewsViewHolder(v);
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SingleMoreHotTrendingNewsViewHolder singleMoreHotTrendingNewsViewHolder = (SingleMoreHotTrendingNewsViewHolder) holder;
final ModelSingleHotTrendingNews modelSingleHotTrendingNewsX = modelSingleHotTrendingNews.get(position);
//Set
singleMoreHotTrendingNewsViewHolder.TVGameDate.setText(modelSingleHotTrendingNewsX.getGamedate());
singleMoreHotTrendingNewsViewHolder.TVGameDescription.setText(modelSingleHotTrendingNewsX.getGamedescription());
singleMoreHotTrendingNewsViewHolder.IMGGameImage.setImageResource(modelSingleHotTrendingNewsX.getGameimage());
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Boolean booltrendingnewssaving = modelSingleHotTrendingNewsX.getTrendingnewssaving();
final int id = modelSingleHotTrendingNewsX.getId();
if (booltrendingnewssaving == true){
Toast.makeText(v.getContext(), "Turn Off Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_off);
modelSingleHotTrendingNewsX.setTrendingnewssaving(false);
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(booltrendingnewssaving == false) {
Toast.makeText(v.getContext(), "Turn On Saved News " + id, Toast.LENGTH_SHORT).show();
singleMoreHotTrendingNewsViewHolder.ICONHotTrendingNewsSaving.setImageResource(R.drawable.saved_on);
modelSingleHotTrendingNewsX.setTrendingnewssaving(true);
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
singleMoreHotTrendingNewsViewHolder.ROWHotTrendingNewsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), modelSingleHotTrendingNews.get(position).getGamedescription(), Toast.LENGTH_SHORT).show();
//Passing Data to GameDescriptionActivity
Intent intent = new Intent(mContext, GameDetailActivity.class);
intent.putExtra("ImagePKG", modelSingleHotTrendingNews.get(position).getGameimage());
intent.putExtra("NamePKG", modelSingleHotTrendingNews.get(position).getGamedate());
intent.putExtra("UrlPKG", modelSingleHotTrendingNews.get(position).getId());
intent.putExtra("DescriptionPKG", modelSingleHotTrendingNews.get(position).getGamedescription());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
int itemCount = modelSingleHotTrendingNews.size();
return itemCount;
}
public class SingleMoreHotTrendingNewsViewHolder extends RecyclerView.ViewHolder{
TextView TVGameDate;
TextView TVGameDescription;
ImageView IMGGameImage;
ImageView ICONHotTrendingNewsSaving;
private RelativeLayout ROWHotTrendingNewsContainer;
public SingleMoreHotTrendingNewsViewHolder(View itemView) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
ICONHotTrendingNewsSaving = itemView.findViewById(R.id.ICON_HotTrendingNewsSaving);
ROWHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_HotTrendingNewsContainer);
}
}
}
//Activity2More.java
public class TabMoreHotActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmentmore_tabhot);
AdapterMoreSectionHotTrendingNews adapterMoreSectionHotTrendingNews;
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = new ArrayList<>();
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
{
modelSectionHotTrendingNews = (ArrayList<ModelSectionHotTrendingNews>) bundle.getSerializable("MoreNews");
}
//1
RecyclerView RecyclerViewMoreSingleHotTrendingNews = findViewById(R.id.RecyclerViewMore_Single_HotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
adapterMoreSectionHotTrendingNews = new AdapterMoreSectionHotTrendingNews(this, modelSectionHotTrendingNews);
RecyclerViewMoreSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RecyclerViewMoreSingleHotTrendingNews.setAdapter(adapterMoreSectionHotTrendingNews);
//Optimized
RecyclerViewMoreSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewMoreSingleHotTrendingNews.setItemViewCacheSize(20);
}
}
//Error
Process: com.indofun.android.indojoy, PID: 18827
java.lang.ClassCastException: com.indofun.android.indojoy.Models.Model_HotTrendingNews.ModelSingleHotTrendingNews cannot be cast to com.indofun.android.indojoy.Models.Model_HotTrendingNews.ModelSectionHotTrendingNews
at com.indofun.android.indojoy.Adapters.AdapterMore_HotTrendingNews.AdapterMoreSectionHotTrendingNews.onBindViewHolder(AdapterMoreSectionHotTrendingNews.java:39)
//NOTE
//RecyclerView1 using AdapterSection.java,AdapterSingle.java,ModelSection.java,ModelSingle.java
//RecyclerView2 using AdapterMoreSection.java,AdapterMoreSingle.java,ModelSection.java,ModelSingle.java
Inside TabMoreHotActivity use like this:
ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews = new ArrayList<>();
Bundle bundle = getIntent().getExtras();
if(bundle!=null {
modelSingleHotTrendingNews = ArrayList<ModelSingleHotTrendingNews>) bundle.getSerializable("MoreNews");
}

Add item on RecycleView Android

I'm trying to add an item on RecycleView like this:
I have an object called Image
public class Image{
public String name;
public String url;
}
When I click on the button to add a new item, my code is like this:
#Override
public void addItemOnList(String url) {
adapter.addItem(new ImageObject("aaaaaa", R.drawable.close_button));
}
That is my method which inserts on the list.
public void addItem(ImageObject imageObject) {
itemList.add(imageObject);
notifyDataSetChanged();
}
My problem is when I click for the first time in additem my onBindViewHolder doesn't iterate all the list but when I check in debug mod my getItemCount is correct! So If I try to add an item after the first time all work well.
MainActivity
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener, OnStartDragListener {
private RecyclerViewAdapter adapter;
private ArrayList<ImageObject> listViewItems;
private RecyclerView recyclerView;
private ItemTouchHelper itemTouchHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
StaggeredGridLayoutManager staggeredLayoutManager = new StaggeredGridLayoutManager(3, 1);
recyclerView.setLayoutManager(staggeredLayoutManager);
List<ImageObject> staggered = getListItemData();
adapter = new RecyclerViewAdapter(this, staggered);
recyclerView.setAdapter(adapter);
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);
itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
private List<ImageObject> getListItemData() {
listViewItems = new ArrayList<ImageObject>();
listViewItems.add(new ImageObject("Alkane", R.drawable.one));
listViewItems.add(new ImageObject("Ethane", R.drawable.two));
listViewItems.add(new ImageObject("Alkyne", R.drawable.three));
listViewItems.add(new ImageObject("Benzene", R.drawable.four));
listViewItems.add(new ImageObject("Alkane", R.drawable.one));
listViewItems.add(new ImageObject("Ethane", R.drawable.two));
listViewItems.add(new ImageObject("Alkyne", R.drawable.three));
listViewItems.add(new ImageObject("Benzene", R.drawable.four));
listViewItems.add(new ImageObject("Alkane", R.drawable.one));
listViewItems.add(new ImageObject("Ethane", R.drawable.two));
listViewItems.add(new ImageObject("Alkyne", R.drawable.three));
listViewItems.add(new ImageObject("Benzene", R.drawable.four));
return listViewItems;
}
#Override
public void addButtonClicked() {
FragmentManager fm = getSupportFragmentManager();
AlertFragment.newInstance(this).show(fm, "dialog");
}
#Override
public void addItemOnList(String url) {
adapter.addItem(new ImageObject("aaaaaa", R.drawable.close_button));
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
itemTouchHelper.startDrag(viewHolder);
}
}
My Adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolders> implements ItemTouchHelperAdapter {
private List<ImageObject> itemList;
private MainActivity mainActivity;
private RecyclerViewClickListener recycleListener;
private OnStartDragListener dragStartListener;
public RecyclerViewAdapter(MainActivity mainActivity, List<ImageObject> itemList) {
this.itemList = itemList;
this.mainActivity = mainActivity;
this.recycleListener = mainActivity;
this.dragStartListener = mainActivity;
}
#Override
public ViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView;
switch (viewType) {
case 1:
layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.add_item_list, null);
break;
default:
layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, null);
break;
}
return new ViewHolders(layoutView);
}
#Override
public void onBindViewHolder(final ViewHolders holder, final int position) {
switch (holder.getItemViewType()) {
case 1:
configureViewHolderAddItem(holder, position);
break;
case 0:
configureDefaultViewHolder(holder, position);
break;
}
}
private void configureViewHolderAddItem(final ViewHolders holder, final int position) {
holder.addItemLayout = holder.itemView.findViewById(R.id.add_item_layout);
holder.addItemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recycleListener.addButtonClicked();
}
});
}
private void configureDefaultViewHolder(final ViewHolders holder, final int position) {
Log.e("test", "position - " + position);
Log.e("test", "name - " + itemList.get(position).getName());
holder.itemLayout = holder.itemView.findViewById(R.id.main_layout);
holder.removeItemButton = holder.itemView.findViewById(R.id.remove_item_button);
holder.itemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemList.remove(holder.getLayoutPosition());
notifyItemRemoved(holder.getLayoutPosition());
notifyItemRangeChanged(holder.getLayoutPosition(), itemList.size());
}
});
holder.itemLayout.setBackgroundResource(itemList.get(position).getPhoto());
holder.itemLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
dragStartListener.onStartDrag(holder);
}
return false;
}
});
//resizeTheFirstPosition(holder, position);
}
private void resizeTheFirstPosition(ViewHolders holder, int position) {
if (position == 0) {
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
200, mainActivity.getResources().getDisplayMetrics());
holder.itemLayout.getLayoutParams().height = dimensionInDp;
holder.itemLayout.getLayoutParams().width = dimensionInDp;
holder.itemLayout.requestLayout();
}
}
public void addItem(ImageObject imageObject) {
itemList.add(imageObject);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return position == itemList.size() - 1 ? 1 : 0;
}
#Override
public int getItemCount() {
return this.itemList.size();
}
#Override
public boolean onItemMove(int fromPosition, int toPosition) {
Collections.swap(itemList, fromPosition, toPosition);
notifyItemMoved(fromPosition, toPosition);
return true;
}
#Override
public void onItemDismiss(int position) {
itemList.remove(position);
notifyItemRemoved(position);
}
public class ViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener,
ItemTouchHelperViewHolder {
private ImageView removeItemButton;
private ImageView addItemButton;
private FrameLayout addItemLayout;
private RelativeLayout itemLayout;
public ViewHolders(View itemView) {
super(itemView);
}
#Override
public void onClick(View view) {
itemList.remove(getLayoutPosition());
//notifyItemRemoved(getLayoutPosition());
notifyItemRangeChanged(getLayoutPosition(), itemList.size());
Toast.makeText(mainActivity, "Removed item- " + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
#Override
public void onItemSelected() {
itemView.setBackgroundColor(Color.LTGRAY);
}
#Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
Finally, I fixed this. I don't know why but I change how I insert on the list
Old code:
public void addItem(ImageObject imageObject) {
itemList.add(imageObject);
notifyDataSetChanged();
}
New code:
public void addItem(ImageObject imageObject) {
itemList.add(itemList.size() - 1, imageObject);
notifyDataSetChanged();
}

onClickListener in RecyclerView.ViewHolder

I've got a RecyclerView.ViewHolder and RecyclerView.Adapter, I need after click on item and then send information about this item to another Activity.
PlacesAdapter.java
public class PlacesAdapter extends RecyclerView.Adapter<PlacesViewHolder> {
private PlacesActivity placesActivity;
Context context;
private int position;
List<Places> places;
public PlacesAdapter(List<Places> places) {
this.places = places;}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PlacesViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.places_view, viewGroup, false);
PlacesViewHolder pvh = new PlacesViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PlacesViewHolder personViewHolder, int i) {
personViewHolder.name.setText(places.get(i).name);
personViewHolder.address.setText(places.get(i).address);
Picasso.with(personViewHolder.itemView.getContext())
.load(places.get(i).photo)
.into(personViewHolder.getPhoto());
}
#Override
public int getItemCount() {
return places.size();
}
}
PlacesViewHolder.java
In this line "intent.putExtra(PlacesDetail.PLACES_NAME,);" How can I send name?
public class PlacesViewHolder extends RecyclerView.ViewHolder {
CardView cv;
public TextView name;
public TextView address;
public ImageView photo;
public PlacesViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
name = (TextView)itemView.findViewById(R.id.person_name);
address = (TextView)itemView.findViewById(R.id.person_age);
photo = (ImageView)itemView.findViewById(R.id.person_photo);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, PlacesDetail.class);
intent.putExtra(PlacesDetail.PLACES_NAME,);
context.startActivity(intent);
}
});
}
public TextView getAddress() {
return address;
}
public TextView getName() {
return name;
}
public ImageView getPhoto() {
return photo;
}
}
This is the complete example of custom Adapter where i'm able to get the details of particular items. In MainActivity you need to set the adapter :
adapter = new MyAdapter(getApplicationContext(), account_no, title, aFN1, aLN1,aFN2, aLN2,aFN3, aLN3,isavilable,waitlist,flag);
adapter.notifyDataSetChanged();
mRecyclerView.setAdapter(adapter);
Now see the code for the custom Adapter :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
String TAG = "MyAdapter";
Context context;
private String[] accountNo;
private String[] title;
private String[] afn1;
private String[] aln1;
private String[] afn2;
private String[] aln2;
private String[] afn3;
private String[] aln3;
private String[] isAvailable;
private String[] waitlist;
private int flag;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView account_no,title,afn1,afn2,aln1,aln2,color,is_available;
private ImageView img_android;
CardView cardView;
public ViewHolder(CardView v) {
super(v);
account_no = (TextView)v.findViewById(R.id.acctno);
title = (TextView)v.findViewById(R.id.title);
afn1 = (TextView) v.findViewById(R.id.afn1);
cardView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(Context context, String[] accountNo,String[] title,String[] afn1,String[] aln1,String[] afn2,String[] aln2,String[] afn3,String[] aln3,String[] isAvailable, String[] waitlist,int flag) {
this.context = context;
this.accountNo = accountNo;
this.title = title;
this.afn1 = afn1;
this.aln1 = aln1;
this.afn2 = afn2;
this.aln2 = aln2;
this.afn3 = afn3;
this.aln3 = aln3;
this.isAvailable = isAvailable;
this.waitlist = waitlist;
this.flag = flag;
Log.d(TAG,afn1.toString() +aln1+afn2+aln2+afn3+aln3.toString()+waitlist);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(cv);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final CardView cardView = holder.cardView;
final TextView accountno = (TextView)cardView.findViewById(R.id.acctno);
accountno.setText(accountNo[position]);
final TextView titletxt = (TextView)cardView.findViewById(R.id.title);
titletxt.setText(title[position]);
final TextView afn1txt = (TextView) cardView.findViewById(R.id.afn1);
afn1txt.setText(afn1[position]+" "+aln1[position]);
Log.d(TAG,waitlist[position]);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = getItemViewType(position);
SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.MYPREFERENCE,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(Constant.ACCOUNT,accountNo[position]);
edit.putString(Constant.TITLE,title[position]);
edit.putString(Constant.AFN1,afn1[position]);
edit.putString(Constant.ALN1,aln1[position]);
edit.putString(Constant.AFN2,afn2[position]);
edit.putString(Constant.ALN2,aln2[position]);
edit.putString(Constant.AFN3,afn3[position]);
edit.putString(Constant.ALN3,aln3[position]);
edit.putBoolean(Constant.IS_AVAILABLE, Boolean.parseBoolean(isAvailable[position].toUpperCase()));
edit.putString(Constant.WAITLIST,waitlist[position]);
Log.d("WaitingNo2 :",""+String.valueOf(waitlist[position]));
edit.commit();
Intent intent = new Intent(v.getContext(), DetailsActivity.class);
v.getContext().startActivity(intent);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return accountNo.length;
}
}
After All that get the value from sharedPreferences in the Activity which is called on Card Click:
preferences = getSharedPreferences("myshared", Context.MODE_PRIVATE);
AccountNo = sharedPreferences.getString(Constant.ACCOUNT,null).toUpperCase();
title = sharedPreferences.getString(Constant.TITLE,null).toUpperCase();
afn1 = sharedPreferences.getString(Constant.AFN1,null).toUpperCase();
aln1 = sharedPreferences.getString(Constant.ALN1,null).toUpperCase();
afn2 = sharedPreferences.getString(Constant.AFN2,null).toUpperCase();
aln2 = sharedPreferences.getString(Constant.ALN2,null).toUpperCase();
afn3 = sharedPreferences.getString(Constant.AFN3,null).toUpperCase();
aln3 = sharedPreferences.getString(Constant.ALN3,null).toUpperCase();
isAvailable = sharedPreferences.getBoolean(Constant.IS_AVAILABLE,isAvailable);
waitlist = sharedPreferences.getString(Constant.WAITLIST,waitlist);
Now do whatever you want and enjoy the code.
You can achieve this by creating an interface inside your adapter for an itemclicklistener and then you can set onItemClickListener from your PlacesActivity.
Somewhere inside your PlacesAdapter you would need the following:
private onRecyclerViewItemClickListener mItemClickListener;
public void setOnItemClickListener(onRecyclerViewItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface onRecyclerViewItemClickListener {
void onItemClickListener(View view, int position, String places_name);
}
Then inside your ViewHolder (which I've added as an inner class inside my adapter), you would apply the listener to the components you'd like the user to click, like so:
class PlacesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
PlacesViewHolder(View view) {
super(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClickListener(v, getAdapterPosition(), PlacesDetail.PLACES_NAME);
}
}
}
This example shows an onClickListener being applied to the view inside PlacesViewHolder.
recyclerView.setAdapter(adapter);// set adapter on recyclerview
adapter.notifyDataSetChanged();// Notify the adapter
adapter.setOnItemClickListener(new PlacesAdapter.onRecyclerViewItemClickListener() {
#Override
public void onItemClickListener(View view, int position, String places_name) {
//perform click logic here (places_name is passed)
}
});
To implement this code, you would setOnItemClickListener to your adapter inside PlacesActivity as shown above.
try this , it's work with me correctly
Create a new class and this code
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}
And in your Activity add this to your adapter implementation
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// do something
}
}
}
#Override
public void onLongItemClick(View view, int position) {
// do whatever
}
})
);

RecyclerView on item click NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So I've set up my RecyclerView with SQLite DB and it's populating the list, but every time I click on the list item it should open the new activity and pass data to it via intent extras.
The click gives me NullPointerException:
Process: com.daroioradecic.fxtodo, PID: 6762
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$RecHolder.onClick(RecAdapter.java:106)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
in my Recycler View adapter class which is:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
It gives the error on line itemClickCallback.onItemClick(getAdapterPosition()); which is the last line in the class.
I'm overriding onClick in the class where recycler view is populated like this:
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
That class implements implements RecAdapter.ItemClickCallback
Any ideas? Thanks!
MAIN ACTIVITY CLASS: (keep in mind that I just transitioned from ListView so I haven't done any cleaning)
public class HomeScreen extends AppCompatActivity implements RecAdapter.ItemClickCallback {
private RecyclerViewUtils.ShowHideToolbarOnScrollingListener showHideToolbarListener;
//SCROLL
private Toolbar tToolbar;
// REC
private RecyclerView recView;
private RecAdapter adapter;
private ArrayList listData;
// ZA SNACKBAR
private CoordinatorLayout coordinatorLayout;
private RelativeLayout relLay;
// NAVIGACIJA
private DrawerLayout mDrawer;
private ActionBarDrawerToggle drawerToggle;
private Toolbar toolbar;
NavigationView nvDrawer;
DrawerLayout dlDrawer;
//----------------------------------------------------------------------------------------------
DatabaseHandler dba;
private ArrayList<Todo> dbTodo = new ArrayList<>();
private TodoAdapter todoAdapter;
private ListView lista;
private Cursor mCursor;
LinearLayout layoutZaUnosTodoa;
EditText editTextZaNazivTodoa;
Button buttonSave;
private CheckBox checkBoxDoneOrNotNaListi;
android.support.design.widget.FloatingActionButton fab;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_home_screen);
tToolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(tToolbar);
tToolbar.setNavigationIcon(R.drawable.ic_nav_menu);
getSupportActionBar().setTitle(R.string.app_name);
// REC
recView = (RecyclerView) findViewById(R.id.rec_list);
recView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecAdapter(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
recView.addOnScrollListener(showHideToolbarListener = new RecyclerViewUtils.ShowHideToolbarOnScrollingListener(tToolbar));
if (savedInstanceState != null) {
showHideToolbarListener.onRestoreInstanceState((RecyclerViewUtils.ShowHideToolbarOnScrollingListener.State) savedInstanceState
.getParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE));
}
layoutZaUnosTodoa = (LinearLayout) findViewById(R.id.layoutZaUnosTodoa);
editTextZaNazivTodoa = (EditText) findViewById(R.id.editTextZaNazivTodoa);
editTextZaNazivTodoa.setSelection(editTextZaNazivTodoa.getText().length());
buttonSave = (Button) findViewById(R.id.buttonSave);
//lista = (ListView) findViewById(R.id.lista);
fab = (android.support.design.widget.FloatingActionButton) findViewById(R.id.fab);
checkBoxDoneOrNotNaListi = (CheckBox) findViewById(R.id.checkBoxDoneOrNotNaListi);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordiantorLayout);
relLay = (RelativeLayout) findViewById(R.id.relLay);
refreshData();
layoutZaUnosTodoa.setVisibility(View.GONE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.VISIBLE);
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToDB();
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
relLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
dlDrawer.setDrawerListener((DrawerLayout.DrawerListener) drawerToggle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
drawerToggle.syncState();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE,
showHideToolbarListener.onSaveInstanceState());
super.onSaveInstanceState(outState);
}
private void saveToDB() {
Todo todo = new Todo();
todo.setTitle(editTextZaNazivTodoa.getText().toString());
dba.addTodo(todo);
adapter.notifyDataSetChanged();
dba.close();
editTextZaNazivTodoa.setText("");
}
public void refreshData() {
dbTodo.clear();
dba = new DatabaseHandler(HomeScreen.this);
ArrayList<Todo> todoFromDB = dba.getTodo();
for (int i = 0; i < todoFromDB.size(); i++) {
String title = todoFromDB.get(i).getTitle();
String dateText = todoFromDB.get(i).getRecordDate();
int mid = todoFromDB.get(i).getItemId();
Todo myTodo = new Todo();
myTodo.setTitle(title);
myTodo.setItemId(mid);
myTodo.setRecordDate(dateText);
dbTodo.add(myTodo);
}
dba.close();
adapter = new RecAdapter(dbTodo, this);
recView.setAdapter(adapter);
// todoAdapter = new TodoAdapter(HomeScreen.this, R.layout.layout_row_za_listu, dbTodo);
//Animation collapseList = AnimationUtils.loadAnimation(HomeScreen.this, R.anim.collapse_search_results);
//lista.startAnimation(collapseList);
//lista.setAdapter(todoAdapter);
// todoAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
/* #Override
public void onSecondaryItemClick(int p) {
}*/
public class TodoAdapter extends ArrayAdapter<Todo> {
Activity activity;
int layoutResource;
Todo todo;
ArrayList<Todo> mData = new ArrayList<>();
public TodoAdapter(Activity act, int resource, ArrayList<Todo> data) {
super(act, resource, data);
activity = act;
layoutResource = resource;
mData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Todo getItem(int position) {
return mData.get(position);
}
#Override
public int getPosition(Todo item) {
return super.getPosition(item);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null || (row.getTag() == null)) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource, null);
holder = new ViewHolder();
holder.mTitle = (TextView) row.findViewById(R.id.tekstNaListi);
holder.checkBox = (CheckBox) row.findViewById(R.id.checkBoxDoneOrNotNaListi);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.myTodo = getItem(position);
holder.mTitle.setText(holder.myTodo.getTitle());
final ViewHolder finalHolder = holder;
holder.mTitle.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
int mid = finalHolder.myTodo.getItemId();
DatabaseHandler dba = new DatabaseHandler(HomeScreen.this);
dba.deleteTodo(mid);
Snackbar snackbar = Snackbar.make(coordinatorLayout, getResources().getString(R.string.snack_bar_tekst), Snackbar.LENGTH_SHORT);
snackbar.show();
todoAdapter.notifyDataSetChanged();
return true;
}
});
/*holder.mTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = finalHolder.myTodo.getTitle().toString();
String dateText = finalHolder.myTodo.getRecordDate().toString();
int mid = finalHolder.myTodo.getItemId();
Intent i = new Intent(HomeScreen.this, Details.class);
i.putExtra("naslov", title);
i.putExtra("datum", dateText);
i.putExtra("id", mid);
startActivity(i);
}
});*/
final View finalRow = row;
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.mTitle = (TextView) finalRow.findViewById(R.id.tekstNaListi);
if (finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(finalHolder.mTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
finalHolder.mTitle.setAlpha(0.5f);
} else if (!finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(0);
finalHolder.mTitle.setAlpha(0.8f);
}
}
});
return row;
}
}
class ViewHolder {
Todo myTodo;
TextView mTitle, mContent, mDate;
int mId;
CheckBox checkBox;
}
EDIT:
This error shows up:
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$1.onClick(RecAdapter.java:67)
and it refeers to this line in adapter class:
itemClickCallback.onItemClick(position);
1) Check the callback null or not.
#Override
public void onClick(View v) {
if (itemClickCallback!=null){
itemClickCallback.onItemClick(getAdapterPosition());
}
}
2) The activity/class implements the method. This is okay. But, are you set the listener in your onCreate() ?
rectAdapter.setItemClickCallback(this);
3)EDITED Change your adapter like this:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, final int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(position);
}
});
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
}
}}

Categories