java.lang.IndexOutOfBoundsException When Displaying Multiple Data in RecyclerView - java

I have 3 parts of data displayed in one RecyclerView:
storyList
yukulList
homeList
When I've tried to display only storyList or yukulList or homeList data in RecyclerView, it works. But when I've tried to display more than one data, for example: storyList && yukulList or storyList && yukulList && homeList, it will show
java.lang.IndexOutOfBoundsException.
I've tried to add notifyDataSetChanged() but it can't works.
ShowFavouriteList.java
public class ShowFavouriteList extends AppCompatActivity implements AdapterFavList.FavListener {
private RecyclerView recyclerView;
private TextView noFavtsTV;
AppPreferences appPreferences;
private SearchView searchView;
private AdapterFavList yAdapterFavlist;
private AdapterFavList mAdapterFavlist;
private AdapterFavList tAdapterFavlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_favourite_list);
SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
//toolbar logo and desc
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
setSupportActionBar(topToolBar); //munculkan menu ke toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button
recyclerView = findViewById(R.id.recycler_view);
noFavtsTV = findViewById(R.id.no_favt_text);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences sPTuru = getApplicationContext().getSharedPreferences("MyTuru", 0);
SharedPreferences sPHome = getApplicationContext().getSharedPreferences("MyHome", 0);
PreferenceMenejer preferenceMenejer = new PreferenceMenejer(sharedPreferences, sPTuru, sPHome);
appPreferences = new AppPreferences(preferenceMenejer);
fetchData();
} // Oncreate
private void fetchData() {
List<Story> storyList = appPreferences.getFavouriteCardList();
List<YukulModel> yukulList = appPreferences.getFavouriteYukul();
List<HomeModel> homeList = appPreferences.getFavouriteHome();
if(storyList != null && storyList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
tAdapterFavlist = new AdapterFavList(this, storyList, yukulList, homeList, this, appPreferences);
recyclerView.setAdapter(tAdapterFavlist);
tAdapterFavlist.notifyDataSetChanged();
}
if(yukulList != null && yukulList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
yAdapterFavlist = new AdapterFavList(this, storyList, yukulList, homeList, this, appPreferences);
recyclerView.setAdapter(yAdapterFavlist);
yAdapterFavlist.notifyDataSetChanged();
}
if(homeList != null && homeList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mAdapterFavlist = new AdapterFavList(this, storyList, yukulList, homeList, this, appPreferences);
recyclerView.setAdapter(mAdapterFavlist);
mAdapterFavlist.notifyDataSetChanged();
}
}
#Override
public void onItemKlik(RecyclerView.ViewHolder viewHolder, HomeModel modelField, int position) {
// Tidur List
List<HomeModel> modelList = appPreferences.getFavouriteHome();
HomeModel click = modelList.get(position);
Toast.makeText(getApplicationContext(), "Selected: " + click.getName(), Toast.LENGTH_LONG).show();
int id = Integer.parseInt(click.getIdStory());
if (id == 0) {
startActivity(new Intent(this, DoaPagi.class));
} else if (id == 1) {
startActivity(new Intent(this, DoaSore.class));
} else if (id == 2) {
startActivity(new Intent(this, DoaWc.class));
} else if (id == 3) {
startActivity(new Intent(this, DoaMasjid.class));
} else if (id == 4) {
startActivity(new Intent(this, DzikirShalat.class));
} else if (id == 5) {
startActivity(new Intent(this, ChildYukul.class));
} else if (id == 6) {
startActivity(new Intent(this, DoaPakaian.class));
} else if (id == 7) {
startActivity(new Intent(this, ChildTidur.class));
}
}
#Override
public void onItemTuru(RecyclerView.ViewHolder viewHolder, Story tField, int position) {
// Tidur List
List<Story> storyList = appPreferences.getFavouriteCardList();
Story clic = storyList.get(position);
int idTuru = Integer.parseInt(clic.getIdStory());
if (idTuru == 0) {
startActivity(new Intent(this, DoaMauTidur.class));
} else if (idTuru == 1) {
startActivity(new Intent(this, DoaBangunt.class));
} else if (idTuru == 2) {
startActivity(new Intent(this, DoaJimak.class));
}
}
#Override
public void onItemYukul(RecyclerView.ViewHolder viewHolder, YukulModel yField, int position) {
// Tidur List
}
private void showNoFavtText(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_fav, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable_tidur configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search_fav).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapterFavlist.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapterFavlist.getFilter().filter(query);
return false;
}
});
return true;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.search_fav) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
AdapterFavList.java
public class AdapterFavList extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
public static final String ACTION_LIKE_IMAGE_CLICKED = "action_like_image_button";
final int VIEW_TYPE_TIDUR = 0;
final int VIEW_TYPE_YUKUL = 1;
final int VIEW_TYPE_HOME = 2;
private Context context;
private AppPreferences appPreferences;
private List<Story> storyList;
private List<YukulModel> yukulList;
private List<HomeModel> homeList;
private List<HomeModel> homeListFiltered;
private List<Object> collection = new ArrayList<Object>();
private FavListener listener;
private int changedItemPosition;
private boolean isLiked;
public AdapterFavList(Context context, List<Story> storyList, List<YukulModel> yukulList, List<HomeModel> homeList, FavListener listener, AppPreferences appPreferences) {
this.context = context;
this.storyList = storyList;
this.yukulList = yukulList;
this.homeListFiltered = homeList;
this.listener = listener;
this.appPreferences = appPreferences;
addData();
}
public void addData() {
storyList = appPreferences.getFavouriteCardList();
yukulList = appPreferences.getFavouriteYukul();
homeList = appPreferences.getFavouriteHome();
if(storyList != null && storyList.size() > 0) {
collection.addAll(storyList);
}
if(yukulList != null && yukulList.size() > 0) {
collection.addAll(yukulList);
}
if(homeList != null && homeList.size() > 0) {
collection.addAll(homeListFiltered);
}
}
public interface FavListener {
void onItemKlik(RecyclerView.ViewHolder viewHolder, HomeModel modelField, int position);
void onItemTuru(RecyclerView.ViewHolder viewHolder, Story tField, int position);
void onItemYukul(RecyclerView.ViewHolder viewHolder, YukulModel yField, int position);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_TIDUR) {
return new tidurViewHolder(LayoutInflater.from(context).inflate(R.layout.item_story_favourite_list, parent, false));
}
if(viewType == VIEW_TYPE_YUKUL) {
return new yukulViewHolder(LayoutInflater.from(context).inflate(R.layout.item_favourite_yukul, parent, false));
}
if(viewType == VIEW_TYPE_HOME) {
return new homeViewHolder(LayoutInflater.from(context).inflate(R.layout.item_fav_home, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Object item = collection.get(position);
if(holder instanceof tidurViewHolder){
((tidurViewHolder) holder).bind(storyList.get(position));
((tidurViewHolder) holder).setViewData((Story) item, holder.getAdapterPosition());
}
if(holder instanceof yukulViewHolder){
((yukulViewHolder) holder).bind(yukulList.get(position));
((yukulViewHolder) holder).viewDataYukul((YukulModel) item, holder.getAdapterPosition());
}
if(holder instanceof homeViewHolder){
((homeViewHolder) holder).bind(homeList.get(position));
((homeViewHolder) holder).viewDataHome((HomeModel) item, holder.getAdapterPosition());
}
}
#Override
public int getItemCount() {
return collection.size();
}
#Override
public int getItemViewType(int position){
Object item = collection.get(position);
if(item instanceof Story) {
return VIEW_TYPE_TIDUR;
}
if(item instanceof YukulModel){
return VIEW_TYPE_YUKUL;
}
if(item instanceof HomeModel){
return VIEW_TYPE_HOME;
}
return -1;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
List<HomeModel> homeList = appPreferences.getFavouriteHome();
if (charString.isEmpty()) {
homeListFiltered = homeList;
}
else {
List<HomeModel> filteredList = new ArrayList<>();
for (HomeModel row : homeList) {
if ( row.getName().toLowerCase().contains(charString.toLowerCase()) ) {
filteredList.add(row);
}
}
homeListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = homeListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
homeListFiltered = (ArrayList<HomeModel>) filterResults.values;
notifyDataSetChanged();
}
};
} //Filter
public void tidurPutHeart(boolean isChecked, Story tidurstory) {
SharedPreferences tidursharedPreferences = context.getSharedPreferences("Turu", Activity.MODE_PRIVATE);
SharedPreferences.Editor tidureditor = tidursharedPreferences.edit();
tidureditor.putBoolean(tidurstory.getIdStory(), isChecked);
tidureditor.commit();
}
public void yukulPutHeart(boolean isChecked, YukulModel yukulstory) {
SharedPreferences yukulsharedPreferences = context.getSharedPreferences("Yukul", Activity.MODE_PRIVATE);
SharedPreferences.Editor yukuleditor = yukulsharedPreferences.edit();
yukuleditor.putBoolean(yukulstory.getIdStory(), isChecked);
yukuleditor.commit();
}
public void homePutHeart(boolean isChecked, HomeModel homestory) {
SharedPreferences homesharedPreferences = context.getSharedPreferences("Home", Activity.MODE_PRIVATE);
SharedPreferences.Editor homeeditor = homesharedPreferences.edit();
homeeditor.putBoolean(homestory.getIdStory(), isChecked);
homeeditor.commit();
}
//ViewHolder
public class tidurViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public tidurViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
} // itemView
public void bind(final Story item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemTuru(tidurViewHolder.this, item, position);
}
}
}
});
}
public void setViewData(final Story story, final int adapterPosition) {
textView.setText(story.getName());
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
tidurPutHeart(isChecked, story);
appPreferences.saveFavouriteCard(story);
}
else {
isLiked = false;
tidurPutHeart(isChecked, story);
appPreferences.deleteCard(story.getIdStory());
// updateLikes();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //setviewdata
public void updateLikes() {
if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //tidurViewholder
//homeViewHolder
public class homeViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public homeViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
} // itemView
public void bind(final HomeModel item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemKlik(homeViewHolder.this, item, position);
}
}
}
});
}
public void viewDataHome(final HomeModel story, final int adapterPosition) {
textView.setText(story.getName());
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
homePutHeart(isChecked, story);
appPreferences.saveFavouriteHome(story);
}
else {
isLiked = false;
homePutHeart(isChecked, story);
appPreferences.deleteCardHome(story.getIdStory());
// updateLikesHome();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //setviewdata
public void updateLikesHome() {
if (!isLiked && homeList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
homeList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //homeviewholder
public class yukulViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public yukulViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
} //itemview
public void bind(final YukulModel item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemYukul(yukulViewHolder.this, item, position);
}
}
}
});
}
public void viewDataYukul(final YukulModel yukulId, final int adapterPosition) {
textView.setText(yukulId.getName());
if (yukulId.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
yukulPutHeart(isChecked, yukulId);
appPreferences.saveFavouriteYukul(yukulId);
}
else {
isLiked = false;
yukulPutHeart(isChecked, yukulId);
appPreferences.deleteCardYukul(yukulId.getIdStory());
// updateLikeYukul();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //viewdatayukul
public void updateLikeYukul() {
if (!isLiked && yukulList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
yukulList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //yukulviewholder
} //HomeAdapter
Logcat
2019-07-20 09:54:52.822 6902-6902/com.seadlab.doadandzikir E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.seadlab.doadandzikir, PID: 6902
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.get(ArrayList.java:437)
at com.seadlab.doadandzikir.FavouriteList.AdapterFavList.onBindViewHolder(AdapterFavList.java:124)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3962)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:610)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:132)
at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1361)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:869)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:753)
at android.view.View.layout(View.java:20672)
at android.view.ViewGroup.layout(ViewGroup.java:6194)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2792)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2319)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
2019-07-20 09:54:52.825 6902-6902/com.seadlab.doadandzikir E/AndroidRuntime: at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:696)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Try to remove this recyclerView.setHasFixedSize(true) or pass FALSE to it. passing TRUE to this method means your adapter's object content will not change, but here your changing the adapter content by performing a QUERY SEARCH on the adapter's content.

In your adapter, the collection list is the only list that's safe to access using position. Trying to call yukulList.get(position) is guaranteed to eventually throw an exception.
All of these lines in onBindViewHolder() are unsafe and should be changed:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
// ...
((tidurViewHolder) holder).bind(storyList.get(position));
// ...
((yukulViewHolder) holder).bind(yukulList.get(position));
// ...
((homeViewHolder) holder).bind(homeList.get(position));
// ...
}
You can access the "view type" value that you've returned from getItemViewType() by calling holder.getItemViewType(), and you can use that to determine the right type of view holder and item to use:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Object item = collection.get(position);
int adapterPosition = holder.getAdapterPosition();
if (holder.getItemViewType() == VIEW_TYPE_TIDUR){
Story story = (Story) item;
tidurViewHolder vh = (tidurViewHolder) holder;
vh.bind(story);
vh.setViewData(story, adapterPosition);
} else if (holder.getItemViewType() == VIEW_TYPE_YUKUL){
YukulModel yukul = (YukulModel) item;
yukulViewHolder vh = (yukulViewHolder) holder;
vh.bind(yukul);
vh.viewDataYukul(yukul, adapterPosition);
} else if (holder.getItemViewType() == VIEW_TYPE_HOME){
HomeModel home = (HomeModel) item;
homeViewHolder vh = (homeViewHolder) holder;
vh.bind(home);
vh.viewDataHome(home, adapterPosition);
}
}
Note also that there's no need to actually pass holder.getAdapterPosition() into e.g. setViewData(), since you can simply call getAdapterPosition() from within the tidurViewHolder method.
And I would also say that you could combine your bind() and setViewData() calls into one, which would leave you with this:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Object item = collection.get(position);
if (holder.getItemViewType() == VIEW_TYPE_TIDUR){
((tidurViewHolder) holder).bind((Story) item);
} else if (holder.getItemViewType() == VIEW_TYPE_YUKUL){
((yukulViewHolder) holder).bind((YukulModel) item);
} else if (holder.getItemViewType() == VIEW_TYPE_HOME){
((homeViewHolder) holder).bind((HomeModel) item);
}
}

Try using three different recycler view, one for each data, and in the main layout set each recycler view with height = 0dp and weight 0.3, this going to make then each one has the same height and it'll fit perfectly in any screen

Related

Pass data from RecyclerView to RecyclerViewMore using Serializable - AndroidX

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

How Do We Handle Click From Multiple Item View in RecyclerView? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have problem:
There is three part of data that displayed in one RecyclerView. As you know, all of data are displayed in favourite page, which mean, they are not constant. If user press the favourite button, the data will be displayed in favourite page, otherwise it's won't. So, all of data are change every time, it depends on user activity. Because of this, I get trouble in getting item's ID when user click certain item.
I've already tried to solve this problem, but still stuck many days...
ShowFavouriteList.java
public class ShowFavouriteList extends AppCompatActivity implements AdapterFavList.FavListener {
private RecyclerView recyclerView;
private TextView noFavtsTV;
AppPreferences appPreferences;
private SearchView searchView;
private AdapterFavList yAdapterFavlist;
private AdapterFavList mAdapterFavlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_favourite_list);
SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
//toolbar logo and desc
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
setSupportActionBar(topToolBar); //munculkan menu ke toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button
recyclerView = findViewById(R.id.recycler_view);
noFavtsTV = findViewById(R.id.no_favt_text);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences sPTuru = getApplicationContext().getSharedPreferences("MyTuru", 0);
SharedPreferences sPHome = getApplicationContext().getSharedPreferences("MyHome", 0);
PreferenceMenejer preferenceMenejer = new PreferenceMenejer(sharedPreferences, sPTuru, sPHome);
appPreferences = new AppPreferences(preferenceMenejer);
fetchData();
} // Oncreate
private void fetchData() {
List<Story> storyList = appPreferences.getFavouriteCardList();
List<YukulModel> yukulList = appPreferences.getFavouriteYukul();
List<HomeModel> modelList = appPreferences.getFavouriteHome();
if(storyList != null && storyList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(new AdapterFavList(this, storyList, yukulList, modelList, this, appPreferences));
}
if(yukulList != null && yukulList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
yAdapterFavlist = new AdapterFavList(this, storyList, yukulList, modelList, this, appPreferences);
recyclerView.setAdapter(yAdapterFavlist);
}
if(modelList != null && modelList.size() > 0) {
showNoFavtText(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mAdapterFavlist = new AdapterFavList(this, storyList, yukulList, modelList, this, appPreferences);
recyclerView.setAdapter(mAdapterFavlist);
}
}
#Override
public void onItemKlik(int pos) {
// Tidur List
List<HomeModel> modelList = appPreferences.getFavouriteHome();
HomeModel click = modelList.get(pos);
Toast.makeText(getApplicationContext(), "Selected: " + click.getName(), Toast.LENGTH_LONG).show();
int id = Integer.parseInt(click.getIdStory());
if(modelList != null && modelList.size() > 0) {
if (id == 0) {
startActivity(new Intent(this, DoaPagi.class));
} else if (id == 1) {
startActivity(new Intent(this, DoaSore.class));
} else if (id == 2) {
startActivity(new Intent(this, DoaWc.class));
} else if (id == 3) {
startActivity(new Intent(this, DoaMasjid.class));
} else if (id == 4) {
startActivity(new Intent(this, DzikirShalat.class));
} else if (id == 5) {
startActivity(new Intent(this, ChildYukul.class));
} else if (id == 6) {
startActivity(new Intent(this, DoaPakaian.class));
} else if (id == 7) {
startActivity(new Intent(this, ChildTidur.class));
}
}
}
private void showNoFavtText(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_fav, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable_tidur configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search_fav).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapterFavlist.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapterFavlist.getFilter().filter(query);
return false;
}
});
return true;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.search_fav) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
AdapterFavList.java
public class AdapterFavList extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
public static final String ACTION_LIKE_IMAGE_CLICKED = "action_like_image_button";
final int VIEW_TYPE_TIDUR = 0;
final int VIEW_TYPE_YUKUL = 1;
final int VIEW_TYPE_HOME = 2;
private Context context;
private AppPreferences appPreferences;
private List<Story> storyList;
private List<YukulModel> yukulList;
private List<HomeModel> homeList;
private List<HomeModel> homeListFiltered;
private List<Object> collection = new ArrayList<Object>();
private FavListener listener;
private int changedItemPosition;
private int posisiItemYukul;
private int posisiItemHome;
private boolean isLiked;
public AdapterFavList(Context context, List<Story> storyList, List<YukulModel> yukulList, List<HomeModel> homeList, FavListener listener, AppPreferences appPreferences) {
this.context = context;
this.storyList = storyList;
this.yukulList = yukulList;
this.homeListFiltered = homeList;
this.listener = listener;
this.appPreferences = appPreferences;
addData();
}
public interface FavListener {
void onItemKlik(int pos);
// void onTidurKlik(int pos);
// void onYukulKlik(int pos);
}
public void addData() {
storyList = appPreferences.getFavouriteCardList();
yukulList = appPreferences.getFavouriteYukul();
homeList = appPreferences.getFavouriteHome();
if(storyList != null && storyList.size() > 0) {
collection.addAll(storyList);
}
if(yukulList != null && yukulList.size() > 0) {
collection.addAll(yukulList);
}
if(homeList != null && homeList.size() > 0) {
collection.addAll(homeListFiltered);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_TIDUR) {
return new tidurViewHolder(LayoutInflater.from(context).inflate(R.layout.item_story_favourite_list, parent, false));
}
if(viewType == VIEW_TYPE_YUKUL) {
return new yukulViewHolder(LayoutInflater.from(context).inflate(R.layout.item_favourite_yukul, parent, false));
}
if(viewType == VIEW_TYPE_HOME) {
return new homeViewHolder(LayoutInflater.from(context).inflate(R.layout.item_fav_home, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Object item = collection.get(position);
if(holder instanceof tidurViewHolder){
((tidurViewHolder) holder).setViewData((Story) item, holder.getAdapterPosition());
}
if(holder instanceof yukulViewHolder){
((yukulViewHolder) holder).viewDataYukul((YukulModel) item, holder.getAdapterPosition());
}
if(holder instanceof homeViewHolder){
((homeViewHolder) holder).viewDataHome((HomeModel) item, holder.getAdapterPosition());
}
}
#Override
public int getItemCount() {
return collection.size();
}
#Override
public int getItemViewType(int position){
Object item = collection.get(position);
if(item instanceof Story) {
return VIEW_TYPE_TIDUR;
}
if(item instanceof YukulModel){
return VIEW_TYPE_YUKUL;
}
if(item instanceof HomeModel){
return VIEW_TYPE_HOME;
}
return -1;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
List<HomeModel> homeList = appPreferences.getFavouriteHome();
if (charString.isEmpty()) {
homeListFiltered = homeList;
}
else {
List<HomeModel> filteredList = new ArrayList<>();
for (HomeModel row : homeList) {
if ( row.getName().toLowerCase().contains(charString.toLowerCase()) ) {
filteredList.add(row);
}
}
homeListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = homeListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
homeListFiltered = (ArrayList<HomeModel>) filterResults.values;
notifyDataSetChanged();
}
};
} //Filter
public void tidurPutHeart(boolean isChecked, Story tidurstory) {
SharedPreferences tidursharedPreferences = context.getSharedPreferences("Turu", Activity.MODE_PRIVATE);
SharedPreferences.Editor tidureditor = tidursharedPreferences.edit();
tidureditor.putBoolean(tidurstory.getIdStory(), isChecked);
tidureditor.commit();
}
public void yukulPutHeart(boolean isChecked, YukulModel yukulstory) {
SharedPreferences yukulsharedPreferences = context.getSharedPreferences("Yukul", Activity.MODE_PRIVATE);
SharedPreferences.Editor yukuleditor = yukulsharedPreferences.edit();
yukuleditor.putBoolean(yukulstory.getIdStory(), isChecked);
yukuleditor.commit();
}
public void homePutHeart(boolean isChecked, HomeModel homestory) {
SharedPreferences homesharedPreferences = context.getSharedPreferences("Home", Activity.MODE_PRIVATE);
SharedPreferences.Editor homeeditor = homesharedPreferences.edit();
homeeditor.putBoolean(homestory.getIdStory(), isChecked);
homeeditor.commit();
}
//ViewHolder
public class tidurViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public tidurViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
}
});
} // itemView
public void setViewData(final Story story, final int adapterPosition) {
textView.setText(story.getName());
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
tidurPutHeart(isChecked, story);
appPreferences.saveFavouriteCard(story);
}
else {
isLiked = false;
tidurPutHeart(isChecked, story);
appPreferences.deleteCard(story.getIdStory());
// updateLikes();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //setviewdata
public void updateLikes() {
if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //tidurViewholder
//homeViewHolder
public class homeViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public homeViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemKlik(position);
}
}
}
});
} // itemView
public void viewDataHome(final HomeModel story, final int adapterPosition) {
textView.setText(story.getName());
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
homePutHeart(isChecked, story);
appPreferences.saveFavouriteHome(story);
}
else {
isLiked = false;
homePutHeart(isChecked, story);
appPreferences.deleteCardHome(story.getIdStory());
// updateLikesHome();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //setviewdata
public void updateLikesHome() {
if (!isLiked && homeList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
homeList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //homeviewholder
public class yukulViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private CheckBox likeCheckBox;
public yukulViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
}
});
} //itemview
public void viewDataYukul(final YukulModel yukulId, final int adapterPosition) {
textView.setText(yukulId.getName());
if (yukulId.getIsLiked() == 1) {
likeCheckBox.setChecked(false);
}
else {
likeCheckBox.setChecked(true);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
posisiItemYukul = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
yukulPutHeart(isChecked, yukulId);
appPreferences.saveFavouriteYukul(yukulId);
}
else {
isLiked = false;
yukulPutHeart(isChecked, yukulId);
appPreferences.deleteCardYukul(yukulId.getIdStory());
// updateLikeYukul();
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
if(collection.size() == 0) {
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
}
}
}
});
} //viewdatayukul
public void updateLikeYukul() {
if (!isLiked && yukulList.get(changedItemPosition).getIsLiked() == 0) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman favourite list
yukulList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemRangeChanged(getAdapterPosition(), collection.size());
collection.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
}
} //updateLikes
} //yukulviewholder
} //HomeAdapter
try it adapter
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ClickItem clickItem;
Context context;
//your data model
ArrayList<ModelField> modelFields;
public RecyclerviewAdapter(Context context, ArrayList<ModelField> modelField, ClickItem clickItem) {
this.context = context;
this.modelFields = modelField;
this.clickItem = clickItem;
}
#Override
public int getItemViewType(int position) {
//get view type
return super.getItemViewType(position);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// get view create
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
// set bind view
if (holder instanceof viewHolder_1) {
((viewHolder_1) holder).bind(modelFields.get(position));
} else if (holder instanceof viewHolder_2) {
((viewHolder_2) holder).bind(modelFields.get(position));
} else if (holder instanceof viewHolder_3) {
((viewHolder_3) holder).bind(modelFields.get(position));
}
}
#Override
public int getItemCount() {
//arraylist size
return modelFields.size();
}
interface ClickItem {
void onClick(RecyclerView.ViewHolder viewHolder, ModelField modelField, int position);
}
public class viewHolder_1 extends RecyclerView.ViewHolder {
public viewHolder_1(#NonNull View itemView) {
super(itemView);
//casting views
}
public void bind(final ModelField item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickItem.onClick(viewHolder_1.this, item, getAdapterPosition());
}
});
}
}
public class viewHolder_2 extends RecyclerView.ViewHolder {
public viewHolder_2(#NonNull View itemView) {
super(itemView);
//casting views
}
public void bind(final ModelField item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickItem.onClick(viewHolder_2.this, item, getAdapterPosition());
}
});
}
}
public class viewHolder_3 extends RecyclerView.ViewHolder {
public viewHolder_3(#NonNull View itemView) {
super(itemView);
//casting views
}
public void bind(final ModelField item) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickItem.onClick(viewHolder_3.this, item, getAdapterPosition());
}
});
}
}
}
and using
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(this, your data arraylist, new RecyclerviewAdapter.ClickItem() {
#Override
public void onClick(RecyclerView.ViewHolder viewHolder, ModelField modelField, int position) {
}
});
recyclerview.setAdapter(recyclerviewAdapter);

java.lang.ClassCastException: MainActivity cannot be cast?

Here's the full log
11-16 04:13:35.810 3555-3555/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.steven.test, PID: 3555
java.lang.ClassCastException: com.steven.test.MainActivity cannot be cast to com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment$FavoritesListUpdater
at com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment.onAttach(AllCurrencyListFragment.java:182)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1372)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1188)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:1071)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:115)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2380)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2215)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:649)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1238)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1086)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1616)
at android.view.View.measure(View.java:22091)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:739)
at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:809)
at android.view.View.measure(View.java:22091)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1632)
at com.duolingo.open.rtlviewpager.RtlViewPager.onMeasure(RtlViewPager.java:211)
at android.view.View.measure(View.java:22091)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:22091)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:739)
at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:809)
at android.view.View.measure(View.java:22091)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:22091)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1059)
at android.view.View.measure(View.java:22091)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
at android.view.View.measure(View.java:22091)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22091)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22091)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
11-16 04:13:35.811 3555-3555/? E/AndroidRuntime: 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:22091)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:725)
at android.view.View.measure(View.java:22091)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2447)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1529)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1786)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1417)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6934)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:979)
at android.view.Choreographer.doCallbacks(Choreographer.java:791)
at android.view.Choreographer.doFrame(Choreographer.java:726)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:965)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6578)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:460)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Here are my activities :
The fragment which starts and passes to the other fragment -
public class CurrencyListTabsFragment extends Fragment implements ViewPager.OnPageChangeListener,
FavoriteCurrencyListFragment.AllCoinsListUpdater, AllCurrencyListFragment.FavoritesListUpdater {
private SectionsPagerAdapterCurrencyList mSectionsPagerAdapter;
private View rootView;
public ViewPager mViewPager;
public static String baseImageURL = "";
public static String SYMBOL = "SYMBOL";
private Toolbar mToolbar;
public final static String DAY = "24h";
public final static String WEEK = "7d";
public final static String HOUR = "1h";
public final static String SORT_SETTING = "sort_setting";
public Fragment context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_currency_list_tabs, container, false);
context = this;
mToolbar = rootView.findViewById(R.id.toolbar_currency_list);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
TabLayout tabLayout = rootView.findViewById(R.id.currency_list_tabs);
mViewPager = rootView.findViewById(R.id.currency_list_tabs_container);
mSectionsPagerAdapter = new SectionsPagerAdapterCurrencyList(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(2);
mViewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
return rootView;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = mSectionsPagerAdapter.getFragment(position);
if (fragment != null) {
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
public void removeFavorite(CMCCoin coin) {
FavoriteCurrencyListFragment frag = (FavoriteCurrencyListFragment) mSectionsPagerAdapter.getFragment(1);
if (frag != null) {
frag.removeFavorite(coin);
}
}
public void addFavorite(CMCCoin coin) {
FavoriteCurrencyListFragment frag = (FavoriteCurrencyListFragment) mSectionsPagerAdapter.getFragment(1);
if (frag != null) {
frag.addFavorite(coin);
}
}
public void allCoinsModifyFavorites(CMCCoin coin) {
AllCurrencyListFragment frag = (AllCurrencyListFragment) mSectionsPagerAdapter.getFragment(0);
if (frag != null) {
frag.getAdapter().notifyDataSetChanged();
}
}
public void performFavsSort() {
FavoriteCurrencyListFragment frag = (FavoriteCurrencyListFragment) mSectionsPagerAdapter.getFragment(1);
if (frag != null) {
frag.performFavsSort();
}
}
public void performAllCoinsSort() {
AllCurrencyListFragment frag = (AllCurrencyListFragment) mSectionsPagerAdapter.getFragment(0);
if (frag != null) {
frag.performAllCoinsSort();
}
}
}
This is the fragment which is throwing the error in "onAttach" method
public class AllCurrencyListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,
SearchView.OnQueryTextListener {
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView currencyRecyclerView;
private AllCurrencyListAdapter adapter;
private ArrayList<CMCCoin> currencyItemList;
private ArrayList<CMCCoin> filteredList = new ArrayList<>();
private MenuItem searchItem;
private SearchView searchView;
private View rootView;
private Context mContext;
public static String currQuery = "";
ArrayList<CMCCoin> searchList;
private HashMap<String, String> searchedSymbols = new HashMap<>();
private HashMap<String, Integer> slugToIDMap = new HashMap<>();
public static boolean searchViewFocused = false;
private FavoritesListUpdater favsUpdateCallback;
private SharedPreferences sharedPreferences;
public interface FavoritesListUpdater {
void removeFavorite(CMCCoin coin);
void addFavorite(CMCCoin coin);
void performFavsSort();
}
public AllCurrencyListFragment() {
}
public void performAllCoinsSort() {
int sortType = sharedPreferences.getInt(SORT_SETTING, 1);
sortList(adapter.getCurrencyList(), sortType);
adapter.notifyDataSetChanged();
}
public void getQuickSearch() {
CoinMarketCapService.getCMCQuickSearch(mContext, new afterTaskCompletion<CMCQuickSearch[]>() {
#Override
public void onTaskCompleted(CMCQuickSearch[] quickSearchNodeList) {
slugToIDMap = new HashMap<>();
Parcelable recyclerViewState;
recyclerViewState = currencyRecyclerView.getLayoutManager().onSaveInstanceState();
for (CMCQuickSearch node : quickSearchNodeList) {
slugToIDMap.put(node.getSlug(), node.getId());
}
if (searchViewFocused) {
for (CMCCoin coin: searchList) {
if (slugToIDMap.get(coin.getId()) != null) {
coin.setQuickSearchID(slugToIDMap.get(coin.getId()));
}
}
adapter.setCurrencyList(searchList);
} else {
for (CMCCoin coin : currencyItemList) {
if (coin.getId() != null && slugToIDMap.get(coin.getId()) != null) {
coin.setQuickSearchID(slugToIDMap.get(coin.getId()));
}
}
adapter.setCurrencyList(currencyItemList);
}
int sortType = sharedPreferences.getInt(SORT_SETTING, 1);
sortList(adapter.getCurrencyList(), sortType);
adapter.notifyDataSetChanged();
favsUpdateCallback.performFavsSort();
currencyRecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
swipeRefreshLayout.setRefreshing(false);
}
}, new afterTaskFailure() {
#Override
public void onTaskFailed(Object o, Exception e) {
Log.e("ERROR", "Server Error: " + e.getMessage());
swipeRefreshLayout.setRefreshing(false);
}
}, true);
}
#Override
public void onRefresh() {
getCurrencyList();
}
public static AllCurrencyListFragment newInstance() {
return new AllCurrencyListFragment();
}
public void getCurrencyList() {
swipeRefreshLayout.setRefreshing(true);
CoinMarketCapService.getAllCoins(mContext, new afterTaskCompletion<CMCCoin[]>() {
#Override
public void onTaskCompleted(CMCCoin[] cmcCoinList) {
try {
if (searchViewFocused) { // Copy some code here to make the checks faster
searchedSymbols.clear();
searchList.clear();
for (CMCCoin coin : filteredList) {
searchedSymbols.put(coin.getSymbol(), coin.getSymbol());
}
for (CMCCoin coin : cmcCoinList) {
if (searchedSymbols.get(coin.getSymbol()) != null) {
searchList.add(coin);
}
}
} else {
currencyItemList.clear();
currencyItemList.addAll(Arrays.asList(cmcCoinList));
}
} catch (Exception e) {
e.printStackTrace();
}
getQuickSearch();
}
}, new afterTaskFailure() {
#Override
public void onTaskFailed(Object o, Exception e) {
Log.e("ERROR", "Server Error: " + e.getMessage());
swipeRefreshLayout.setRefreshing(false);
}
}, true);
}
#Override
public void onResume() {
super.onResume();
getActivity().invalidateOptionsMenu();
}
#Override
public void onAttach(Context context) {
this.mContext = context;
this.favsUpdateCallback = (FavoritesListUpdater) context;
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_all_currency_list, container, false);
setHasOptionsMenu(true);
DatabaseHelperSingleton db = DatabaseHelperSingleton.getInstance(mContext);
sharedPreferences = getContext().getSharedPreferences(SHAREDPREF_SETTINGS, MODE_PRIVATE);
searchList = new ArrayList<>();
// Setup currency list
currencyRecyclerView = rootView.findViewById(R.id.currency_list_recycler_view);
HorizontalDividerItemDecoration divider = new HorizontalDividerItemDecoration.Builder(mContext).build();
currencyRecyclerView.addItemDecoration(divider);
LinearLayoutManager llm = new LinearLayoutManager(mContext);
llm.setOrientation(LinearLayoutManager.VERTICAL);
currencyRecyclerView.setLayoutManager(llm);
currencyItemList = new ArrayList<>();
adapter = new AllCurrencyListAdapter(favsUpdateCallback, currencyItemList, db, (AppCompatActivity) mContext, new CustomItemClickListener() {
#Override
public void onItemClick(int position, View v) {
Intent intent = new Intent(mContext, CurrencyDetailsTabsActivity.class);
intent.putExtra(GraphFragment.ARG_SYMBOL, adapter.getCurrencyList().get(position).getSymbol());
intent.putExtra(GraphFragment.ARG_ID, adapter.getCurrencyList().get(position).getId());
intent.putExtra(GraphFragment.COIN_OBJECT, adapter.getCurrencyList().get(position));
mContext.startActivity(intent);
}
});
currencyRecyclerView.setAdapter(adapter);
// Setup swipe refresh layout
swipeRefreshLayout = rootView.findViewById(R.id.currency_list_swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.myAccentColor);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
getCurrencyList();
}
});
return rootView;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.sort_button:
int sortType = sharedPreferences.getInt(SORT_SETTING, 1);
new MaterialDialog.Builder(getActivity())
.title(R.string.sort_by)
.items(R.array.sort_options)
.dividerColorRes(R.color.myPrimaryColor)
.widgetColorRes(R.color.myPrimaryColor)
.buttonRippleColorRes(R.color.myPrimaryColor)
.itemsCallbackSingleChoice(sortType, new MaterialDialog.ListCallbackSingleChoice() {
#Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
sortList(adapter.getCurrencyList(), which);
adapter.notifyDataSetChanged();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(SORT_SETTING, which);
editor.apply();
favsUpdateCallback.performFavsSort();
Toast toast = Toast.makeText(getContext(), "Sorting by: " + text, Toast.LENGTH_SHORT);
toast.show();
return true;
}
})
.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
currQuery = query;
query = query.toLowerCase();
filteredList.clear();
for (CMCCoin coin : currencyItemList) {
if (coin.getSymbol().toLowerCase().contains(query) || coin.getName().toLowerCase().contains(query)) {
filteredList.add(coin);
}
}
adapter.setCurrencyList(filteredList);
return true;
}
private void showInputMethod(View view) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(view, 0);
}
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
if (searchView != null && searchViewFocused) {
((AppCompatActivity)mContext).getSupportActionBar().setTitle("");
searchView.requestFocusFromTouch();
searchView.setIconified(false);
searchView.setIconified(false);
searchView.setQuery(currQuery, false);
showInputMethod(rootView);
}
}
#Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.all_currency_list_tab_menu, menu);
searchItem = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
// Detect SearchView icon clicks
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchViewFocused = true;
setItemsVisibility(menu, searchItem, false);
}
});
// Detect SearchView close
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
searchViewFocused = false;
setItemsVisibility(menu, searchItem, true);
return false;
}
});
if (searchViewFocused) ((AppCompatActivity)mContext).getSupportActionBar().setTitle("");
super.onCreateOptionsMenu(menu, inflater);
}
private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
for (int i = 0; i < menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item != exception) item.setVisible(visible);
}
if (!visible) {
((AppCompatActivity)mContext).getSupportActionBar().setTitle("");
} else {
((AppCompatActivity)mContext).getSupportActionBar().setTitle(getResources().getString(R.string.app_name));
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
searchViewFocused = false;
}
public AllCurrencyListAdapter getAdapter() {
return this.adapter;
}
}
I've tried to look around for answers but could'nt find even one and this error is stressing me out since I can't fix it! App crashes when I try to start this fragment. Any help is appricated.
You need to have MainActivity ... implements AllCurrencyListFragment.FavoritesListUpdater
The Fragment will attach to an Activity, so in other words, at com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment.onAttach(AllCurrencyListFragment.java:182), that Activity that you have used to load this Fragment, must implement that interface.
Plus, a Fragment is not an extension of a Context object
Here are my activities
You showed two Fragments...
In public void onAttach(Context context), the context passed in seems to be of type com.steven.test.MainActivity which appears not to be compatible with com.steven.test.providers.priceticker.currencylist.AllCurrencyListFragment$FavoritesListUpdate when you try and cast it here:
this.favsUpdateCallback = (FavoritesListUpdater) context;
I don't know what are you trying to do.
in your code, you try to cast
FavoritesListUpdater
to Context
and that what causes the error.
I think you want to cast the context to MainActivity right?
this.favsUpdateCallback = ((MainActivity) getActivity()).favsUpdateCallback ;
Do you want to do it like that?

A Search doesn't update my RecyclerView

I'm currently developing an Android application which can either load information from my website or use the information stored in an SQLite database. I'm trying to implement a search feature into it but I ran into a problem.
The data in my recyclerview doesn't update when a search is made. I've looked it up on Google many times but I still haven't found a solution. Is there a bright person here willing to help me?
MainActivity.java
public class MainActivity extends AppCompatActivity implements DienstAdapter.ListItemClickListener, NavigationView.OnNavigationItemSelectedListener {
private static final String DIENST_URL = "https://mywebsite.com/apps/test/dienstenapi.php";
private RecyclerView recyclerView;
private DienstAdapter adapter;
private List<Dienst> dienstList;
private SQLiteDatabase mDb;
private Cursor cursor;
private SharedPreferences sharedPreferences;
private NavigationView navigationView;
private View headerView;
private TextView gebruikersnaam;
private Resources res;
private SwipeRefreshLayout swiper;
private static Toast mToast = null;
private SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = this.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.app_name);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
gebruikersnaam = headerView.findViewById(R.id.gebruikersnaam);
res = getResources();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
setupPreferenceGebruikersnaam();
swiper = findViewById(R.id.swiper);
swiper.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
dienstList.clear();
loadDiensten();
}
});
dienstList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DienstDbHelper dbHelper = new DienstDbHelper(this);
mDb = dbHelper.getWritableDatabase();
loadDiensten();
}
#Override
protected void onDestroy() {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
super.onDestroy();
}
SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("example_text")){
setupPreferenceGebruikersnaam();
}
}
};
private void loadDienstenOnline() {
String moetInfoOphalen = sharedPreferences.getString("example_list", "1");
if (moetInfoOphalen.equals("1") || moetInfoOphalen.equals("0")) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, DIENST_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray diensten = new JSONArray(response);
for (int i = 0; i < diensten.length(); i++) {
JSONObject dienstObject = diensten.getJSONObject(i);
int id = dienstObject.getInt("id");
String naam = dienstObject.getString("naam");
String beschrijving = dienstObject.getString("beschrijving");
String categorie = dienstObject.getString("categorie");
double prijs = dienstObject.getDouble("prijs");
String afbeelding = dienstObject.getString("afbeelding");
dienstList.add(new Dienst(id, naam, beschrijving, categorie, prijs, afbeelding));
}
voegDienstenToeAanDb(mDb, dienstList);
adapter = new DienstAdapter(MainActivity.this, dienstList, MainActivity.this);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
} else {
loadDienstenOffline();
Toast.makeText(MainActivity.this, R.string.instelling_blokkeert_ophalen_diensten, Toast.LENGTH_LONG).show();
}
}
private void loadDienstenOffline() {
cursor = getAlleDiensten();
if ((cursor != null) && (cursor.getCount() > 0)) {
omzettenCursorNaarDiensten(cursor);
adapter = new DienstAdapter(MainActivity.this, dienstList, MainActivity.this);
recyclerView.setAdapter(adapter);
} else {
dienstList.add(new Dienst(0, "", "", "", 0, ""));
adapter = new DienstAdapter(MainActivity.this, dienstList, MainActivity.this);
recyclerView.setAdapter(adapter);
recyclerView.setVisibility(View.GONE);
if (mToast != null)
mToast.cancel();
mToast.makeText(this, R.string.internet_werkt_niet, Toast.LENGTH_LONG).show();
}
}
private boolean internetIsBeschikbaar() {
ConnectivityManager cm =(ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
private void loadDiensten() {
recyclerView.setVisibility(View.VISIBLE);
if (internetIsBeschikbaar()) {
loadDienstenOnline();
} else {
loadDienstenOffline();
}
swiper.setRefreshing(false);
}
#Override
public void onListItemClick(String url, String naam) {
Intent intent = new Intent(MainActivity.this, DienstActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, url);
intent.putExtra("DienstNaam", naam);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
inflater.inflate(R.menu.search_menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager != null ? searchManager.getSearchableInfo(getComponentName()) : null);
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
adapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
adapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent startSettingsActivity = new Intent(this, SettingsActivity.class);
startActivity(startSettingsActivity);
return true;
} else if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
private static void voegDienstenToeAanDb(SQLiteDatabase db, List<Dienst> diensten){
if(db == null){
return;
}
List<ContentValues> list = new ArrayList<>();
ContentValues cv;
for (Dienst d : diensten) {
cv = new ContentValues();
cv.put(DienstContract.DienstEntry.COLUMN_NAAM, d.getNaam());
cv.put(DienstContract.DienstEntry.COLUMN_BESCHRIJVING, d.getBeschrijving());
cv.put(DienstContract.DienstEntry.COLUMN_CATEGORIE, d.getCategorie());
cv.put(DienstContract.DienstEntry.COLUMN_PRIJS, d.getPrice());
cv.put(DienstContract.DienstEntry.COLUMN_AFBEELDING, d.getAfbeelding());
list.add(cv);
}
try
{
db.beginTransaction();
//clear the table first
db.delete (DienstContract.DienstEntry.TABLE_NAME,null,null);
//go through the list and add one by one
for(ContentValues c : list){
db.insert(DienstContract.DienstEntry.TABLE_NAME, null, c);
}
db.setTransactionSuccessful();
}
catch (SQLException e) {
//too bad :(
}
finally
{
db.endTransaction();
}
}
private Cursor getAlleDiensten() {
return mDb.query(
DienstContract.DienstEntry.TABLE_NAME,
null,
null,
null,
null,
null,
DienstContract.DienstEntry._ID
);
}
private void omzettenCursorNaarDiensten(Cursor c) {
int teller = 0, id;
String naam, beschrijving, categorie, afbeelding;
double prijs;
while (c.moveToPosition(teller)) {
id = Integer.parseInt(c.getString(c.getColumnIndex(DienstContract.DienstEntry._ID)));
naam = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_NAAM));
beschrijving = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_BESCHRIJVING));
categorie = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_CATEGORIE));
prijs = c.getDouble(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_PRIJS));
afbeelding = c.getString(c.getColumnIndex(DienstContract.DienstEntry.COLUMN_AFBEELDING));
dienstList.add(new Dienst(id, naam, beschrijving, categorie, prijs, afbeelding));
teller++;
}
}
private void setupPreferenceGebruikersnaam() {
String text = String.format(res.getString(R.string.welkomsbericht), sharedPreferences.getString("example_text", "gebruiker"));
gebruikersnaam.setText(text);
}
}
DienstAdapter.java
public class DienstAdapter extends RecyclerView.Adapter<DienstAdapter.DienstViewHolder> implements Filterable {
private Context mContext;
private List<Dienst> dienstList;
private List<Dienst> dienstListFiltered;
private final ListItemClickListener mOnClickListener;
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
dienstListFiltered = dienstList;
} else {
List<Dienst> filteredList = new ArrayList<>();
for (Dienst row : dienstList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getNaam().toLowerCase().contains(charString.toLowerCase()) || row.getBeschrijving().contains(charSequence)) {
filteredList.add(row);
}
}
dienstListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = dienstListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
dienstListFiltered = (ArrayList<Dienst>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface ListItemClickListener {
void onListItemClick(String url, String naam);
}
DienstAdapter(Context mContext, List<Dienst> dienstList, ListItemClickListener listener) {
this.mContext = mContext;
this.dienstList = dienstList;
this.dienstListFiltered = dienstList;
mOnClickListener = listener;
}
#Override
public DienstViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_layout, null);
return new DienstViewHolder(view);
}
#Override
public void onBindViewHolder(DienstViewHolder holder, int position) {
Dienst dienst = dienstList.get(position);
holder.tv_naam.setText(dienst.getNaam());
holder.tv_beschrijving.setText(dienst.getBeschrijving());
holder.tv_categorie.setText(String.valueOf(dienst.getCategorie()));
holder.tv_prijs.setText(String.valueOf(dienst.getPrice()));
if (dienst.getPrice() != 0)
holder.tv_prijs.setText(String.format("€ %.2f", dienst.getPrice()));
else
holder.tv_prijs.setText("");
Glide.with(mContext).load(dienst.getAfbeelding()).into(holder.iv_afbeelding);
}
#Override
public int getItemCount() {
return dienstList.size();
}
public class DienstViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView iv_afbeelding;
TextView tv_naam, tv_beschrijving, tv_categorie, tv_prijs;
DienstViewHolder(View itemView) {
super(itemView);
iv_afbeelding = itemView.findViewById(R.id.iv_afbeelding);
tv_naam = itemView.findViewById(R.id.tv_naam);
tv_beschrijving = itemView.findViewById(R.id.tv_beschrijving);
tv_categorie = itemView.findViewById(R.id.tv_categorie);
tv_prijs = itemView.findViewById(R.id.tv_prijs);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int clickedPosition = getAdapterPosition();
String url = dienstList.get(clickedPosition).getAfbeelding().replace(".png", ".html");
String naam = dienstList.get(clickedPosition).getNaam();
mOnClickListener.onListItemClick(url, naam);
}
}
}
Firstly, getItemCount() and onBindViewHolder() should use the filtered list dienstListFiltered.
And You forgot to update the count of the FilterResults.
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
// Filter data ...
// ...
FilterResults filterResults = new FilterResults();
filterResults.values = dienstListFiltered;
filterResults.count = dienstListFiltered.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
dienstListFiltered = (ArrayList<Dienst>) filterResults.values;
notifyDataSetChanged();
}
};
}
See: Custom Listview Adapter with filter Android
Can you add
notifyDataSetChanged();
immediately after
filteredList.add(row);
?

notifyDataSetChanged(); not refreshing ListView?

I'm working on a notes app and I'm running into trouble deleting notes: after the note is deleted, it still shows in the listview.
I'm trying to use notifyDataSetChanged(), but it doesn't seem to be working for me.
MainActivity:
public class MainActivity extends AppCompatActivity {
private ListView mListViewNotes;
ArrayAdapter<Note> listAdapter;
ArrayList<Note> list_items = new ArrayList<>();
int count = 0;
String list_item;
Object mActionMode;
Toolbar app_bar;
ArrayList<Note> notes;
private String mNoteFileName;
private Note mLoadedNote;
Note loadedNote;
ImageView picTest;
NoteAdapter na;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
app_bar = (Toolbar) findViewById(R.id.app_bar);
TextView title_1 = (TextView) findViewById(R.id.title1);
TextView title_2 = (TextView) findViewById(R.id.title2);
TextView title_m = (TextView) findViewById(R.id.title_m);
Typeface music_font = Typeface.createFromAsset(getAssets(), "fonts/melodymakernotesonly.ttf");
Typeface notes_font = Typeface.createFromAsset(getAssets(), "fonts/the unseen.ttf");
setSupportActionBar(app_bar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setElevation(12);
title_1.setTypeface(music_font);
title_2.setTypeface(notes_font);
title_m.setTypeface(music_font);
listAdapter = new ArrayAdapter<Note>(this, R.layout.item_note, R.id.item_note, list_items);
mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
if (mNoteFileName != null && !mNoteFileName.isEmpty()) {
loadedNote = Utilities.getNoteByName(this, mNoteFileName);
}
mListViewNotes = (ListView) findViewById(R.id.listview_notes);
mListViewNotes.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListViewNotes.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (list_items.contains(notes.get(position))) {
count = count-1;
list_items.remove(notes.get(position));
mode.setTitle(count + " Notes Selected");
} else {
count = count+1;
list_items.add(notes.get(position));
mode.setTitle(count + " Notes Selected");
}
if (count == 0) {
mode.setTitle("No Notes Selected");
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
app_bar.setVisibility(View.GONE);
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
deleteNote();
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
count = 0;
app_bar.setVisibility(View.VISIBLE);
list_items.clear();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_note:
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_settings:
Log.d("list:", "testing");
}
return true;
}
#Override
protected void onResume() {
super.onResume();
mListViewNotes.setAdapter(null);
notes = Utilities.getAllSavedNotes(this);
if (notes == null || notes.size() == 0) {
Toast.makeText(this, "No Notes!", Toast.LENGTH_LONG).show();
} else {
na = new NoteAdapter(this, R.layout.item_note, notes);
mListViewNotes.setAdapter(na);
mListViewNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String filename = ((Note) mListViewNotes.getItemAtPosition(position)).getDateTime() + Utilities.FileExtention;
Intent view_note = new Intent(getApplicationContext(), NoteActivity.class);
view_note.putExtra("NOTE_FILE", filename);
startActivity(view_note);
}
});
}
}
private void deleteNote() {
if(list_items.contains(null)) {
finish();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle("Delete")
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (Note loadedNote : list_items) {
Utilities.deleteNote(getApplicationContext(), loadedNote.getDateTime() + Utilities.FileExtention);
}
na.notifyDataSetChanged();
listAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.setCancelable(false);
dialog.show();
}
}
NoteAdapter
public class NoteAdapter extends ArrayAdapter<Note> {
public NoteAdapter(Context context, int resource, ArrayList<Note> notes) {
super(context, resource, notes);
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
//return super.getView(position, convertView, parent);
if(convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_note, null);
}
Note note = getItem(position);
if(note != null) {
TextView title = (TextView) convertView.findViewById(R.id.list_note_title);
TextView content = (TextView) convertView.findViewById(R.id.list_note_content);
TextView date = (TextView) convertView.findViewById(R.id.list_note_date);
Typeface scribble_card = Typeface.createFromAsset(getContext().getAssets(), "fonts/the unseen.ttf");
title.setTypeface(scribble_card);
content.setTypeface(scribble_card);
title.setText(note.getTitle());
date.setText(note.getDateTimeFormatted(getContext()));
if(note.getContent().length() > 25) {
content.setText(note.getContent().substring(0,25) + "...");
} else {
content.setText(note.getContent());
}
if(note.getContent().length() <= 0) {
content.setText("(Empty Note..)");
} else {
content.setText(note.getContent());
}
if (note.getTitle().length() <= 0) {
title.setText("(Untitled)");
} else {
title.setText(note.getTitle());
}
}
return convertView;
}
You are setting adapter with a list:
na = new NoteAdapter(this, R.layout.item_note, notes);
mListViewNotes.setAdapter(na);
na.notifyDataSetChanged(); will only work if your notes list is changed.
And I don't see that you remove/add/modify on notes list.
If you are deleting item from list you need to remove it from notes list, too:
notes.remove(position_to_remove);
na.notifyDataSetChanged();

Categories