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

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

Related

Transition between 2 recycler views having cards

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

Nested Recycler View, Child And Parent Remove Issue

I have created a Nested recycle rview with parent and child both dynamic.Addition to both Parent and Child is working fine.Deletion from child is working fine.I want to remove parent view when all the child views for the same is removed.Confused about how could i implement the same.
Here is the child Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ToDoModel> values;
private Context context;
//private OnEditListener onEditListener;
AlertDialog alertDialog;
/*public MyAdapter(List<ToDoModel> context) {
this.values = context;
this.onEditListener = onEditListener;
}*/
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtHeader;
public TextView txtFooter;
public ImageView mIcon;
public View layout;
public ImageView deleteItem;
public CheckBox doneButton;
public ImageView editItem;
public ViewHolder(View v) {
super(v);
layout = v;
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
mIcon = (ImageView) v.findViewById(R.id.icon);
deleteItem = (ImageView) v.findViewById(R.id.deleteButton);
doneButton = (CheckBox) v.findViewById(R.id.checkBox);
editItem = (ImageView) v.findViewById(R.id.editButton);
}
}
public void add(int position, ToDoModel item) {
values.add(position, item);
sort();
notifyDataSetChanged();
//notifyItemInserted(position);
}
public void replace(ToDoModel item)
{
int editPos;
editPos = values.indexOf(item);
values.set(editPos,item);
sort();
notifyDataSetChanged();
}
public void sort() {
if ((int) values.size() > 1) {
Collections.sort(values);
}
}
public void remove(int position) {
values.remove(position);
notifyDataSetChanged();
}
public MyAdapter(List<ToDoModel> myDataset) {
values = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.todo_row_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ToDoModel toDoModel = values.get(position);
switch ((String) toDoModel.task) {
case "To Go":
holder.mIcon.setImageResource(R.drawable.ic_explore24px);
break;
case "To Get":
holder.mIcon.setImageResource(R.drawable.ic_shoppingbag24px);
break;
case "To Do":
holder.mIcon.setImageResource(R.drawable.ic_todo);
break;
default:
break;
}
holder.txtHeader.setText(toDoModel.header);
holder.txtFooter.setText(toDoModel.task + " | " + toDoModel.tod + " | " + toDoModel.footer);
holder.doneButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
//holder.mIcon.setImageResource(R.drawable.ic_check_circle24px);
Toast.makeText(buttonView.getContext(), "Marked As Done", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(buttonView.getContext(), "Marked As UnDone", Toast.LENGTH_SHORT).show();
}
}
});
holder.deleteItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
View view = LayoutInflater.from(v.getContext()).inflate(R.layout.delete_promptdialog,null);
Button YesButton = (Button) view.findViewById(R.id.buttonYes);
Button NoButton = (Button) view.findViewById(R.id.buttonNo);
YesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
Toast.makeText(v.getContext(), "List Item Removed", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
NoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Delete Canceled", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
builder.setView(view);
alertDialog=builder.create();
alertDialog.show();
/*remove(position);
Toast.makeText(v.getContext(), "List Item Removed", Toast.LENGTH_SHORT).show();*/
}
});
/* holder.editItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onEditListener.onEditClick(values.get(position));
//Toast.makeText(v.getContext(), "List Edit", Toast.LENGTH_SHORT).show();
}
});*/
}
/*public interface OnEditListener {
void onEditClick(ToDoModel currentData);
}*/
#Override
public int getItemCount() {
return values.size();
}
}
Here is the Parent Adapter
public class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.ParentViewHolder> {
private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
public List<TodoParent> parentList;
public TodoParent todayList;
public static long todayEpochDate;
public ParentAdapter(List<TodoParent> parentList, MainFragment mainFragment) {
this.parentList = parentList;
}
public void add(int position, TodoParent item) {
parentList.add(position, item);
sort();
notifyDataSetChanged();
//notifyItemInserted(position);
}
public void sort() {
if ((int) parentList.size() > 1) {
Collections.sort(parentList);
//if(!(todayList.ParentTitle.isEmpty())) Collections.swap(parentList, parentList.indexOf(todayList), 0);
}
/* if ( todayList )
{
System.out.println("Entering Swap");
setToday(todayList);
}*/
}
public void setToday(TodoParent item) {
int todayPos;
todayPos = parentList.indexOf(item);
parentList.remove(todayPos);
notifyDataSetChanged();
parentList.add(0,item);
notifyDataSetChanged();
}
#NonNull
#Override
public ParentAdapter.ParentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_parent_view,parent,false);
ParentViewHolder vh = new ParentViewHolder(view);
return vh;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull ParentViewHolder holder, int position) {
TodoParent todoParent = parentList.get(position);
todoParent.ParentId = position;
Calendar mCal;
mCal = Calendar.getInstance();
int mDay = mCal.get(Calendar.DAY_OF_MONTH);
int mMonth = mCal.get(Calendar.MONTH);
int mYear = mCal.get(Calendar.YEAR);
String dateString = mDay +"/"+ (mMonth+1) +"/" + mYear;
try {
todayEpochDate = new SimpleDateFormat("dd/MM/yyyy").parse(dateString).getTime()/1000;
} catch (ParseException e) {
e.printStackTrace();
}
if((long)todayEpochDate == (long)todoParent.EpochTime)
{
holder.mTitle.setText("Today");
todayList = todoParent;
System.out.println("todayE:"+todayEpochDate);
System.out.println("SelectedE:"+todoParent.EpochTime);
}
else
{
holder.mTitle.setText(todoParent.ParentTitle);
System.out.println("today:"+todayEpochDate);
System.out.println("Selected:"+todoParent.EpochTime);
}
LinearLayoutManager layoutManager = new LinearLayoutManager(holder.childView.getContext(),
LinearLayoutManager.VERTICAL,false);
layoutManager.setInitialPrefetchItemCount(todoParent.mChildList.size());
holder.childView.setLayoutManager(layoutManager);
MyAdapter myAdapter = new MyAdapter(todoParent.mChildList);
holder.childView.setAdapter(myAdapter);
holder.childView.setRecycledViewPool(viewPool);
}
#Override
public int getItemCount() {
return parentList.size();
}
public class ParentViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public RecyclerView childView;
public ParentViewHolder(#NonNull View itemView) {
super(itemView);
mTitle = itemView.findViewById(R.id.mParentTitle);
childView = itemView.findViewById(R.id.mChildView);
}
}
}
remove for child is working fine. How to remove Parent here when there are no more child views?

Manage tap different items rapidly in a recycler view

My problem is that I have a recycler view that opens a dialog when a tap on them, but when rapidly tap on two different item it opens two dialog.
How can I solve this?.
I've tried
using a bool before the click action:
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if(!clicked[0]){
clicked[0] = true;
if (mListener != null) {
mListener.onClickBoard(mValues.get(i));
}else{
((MainActivity)mContext).onClickBoard(mValues.get(i).getAreaId(), mValues.get(i).getName());
}
}
}
})
but this just solve the case when I double tap the same item, but not when I tap different items fast.
hope you can help me, what should I do.
EDIT
I would prefer to solve it from the adapter because I will use the solution for other recycler views, and the others don't call a dialog.
My Adapter Class:
public class MyBoardAdapter extends RecyclerView.Adapter<MyBoardAdapter.ViewHolder> {
private List<Board> mValues;
private Context mContext;
private final OnBoardFragmentInteractionListener mListener;
public MyBoardAdapter(List<Board> mValues, OnBoardFragmentInteractionListener mListener, Context context) {
this.mValues = mValues;
this.mContext = context;
this.mListener = mListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_board, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int i) {
holder.mItem = mValues.get(i);
holder.tvName.setText(holder.mItem.getName());
holder.tvWaiter.setVisibility(View.GONE);
holder.tvCount.setVisibility(View.GONE);
final boolean[] clicked = {false};
GestureDetector gestureDetector;
byte[] decodedString = Base64.decode(holder.mItem.getSrc(), Base64.DEFAULT);
try {
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivTable.setImageBitmap(decodedByte);
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> map = isEmpty(holder.mItem.getAreaId(), holder.mItem.getName());
if (!map.isEmpty()) {
holder.ivTable.setImageResource(R.mipmap.ic_launcher_atento_round);
holder.tvWaiter.setText(map.get("name"));
holder.tvWaiter.setVisibility(View.VISIBLE);
holder.tvCount.setText("(" + map.get("count") + ")");
holder.tvCount.setVisibility(View.VISIBLE);
}
gestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener(){
});
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if(!clicked[0]){
clicked[0] = true;
if (mListener != null) {
mListener.onClickBoard(mValues.get(i));
}else{
((MainActivity)mContext).onClickBoard(mValues.get(i).getAreaId(), mValues.get(i).getName());
}
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public void setmValues(List<Board> mValues) {
this.mValues = mValues;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
#BindView(R.id.ivBoard)
ImageView ivTable;
#BindView(R.id.tvName)
TextView tvName;
#BindView(R.id.tvWaiter)
TextView tvWaiter;
#BindView(R.id.tvCount)
TextView tvCount;
public Board mItem;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
this.mView = itemView;
}
#Override
public String toString() {
return "ViewHolder{" +
"mView=" + mView +
", ivTable=" + ivTable +
", tvName=" + tvName +
", tvWaiter=" + tvWaiter +
", tvCount=" + tvCount +
", mItem=" + mItem +
'}';
}
}
public Map<String, String> isEmpty(String area, String mesa) {
Map<String, String> response = new HashMap<>();
if (!mOcu.get(0).isEmpty()) {
for (int i = 0; i <= mOcu.get(0).size() - 1; i++) {
if (mOcu.get(0).get(i).trim().equals(area.trim()) && mesa.equals(mOcu.get(1).get(i))) {
Log.i("Mesa Ocupada", mOcu.get(0).get(i) + " -- " + mOcu.get(1).get(i));
response.put("code", mOcu.get(2).get(i));
response.put("name", mOcu.get(3).get(i));
response.put("count", mOcu.get(5).get(i));
return response;
}
}
}
return response;
}
}
Dialog Code:
public void dialogCustomer() {
View mView = getLayoutInflater().inflate(R.layout.dialog_customer, null);
final AlertDialog dialog = new AlertDialog.Builder(this).setView(mView).create();
final TextView tvCustomer = (TextView) mView.findViewById(R.id.tvCustomer);
final EditText etCustomer = (EditText) mView.findViewById(R.id.etCustomer);
final Button btnSubmit = (Button) mView.findViewById(R.id.btnSubmit);
tvCustomer.setText("Atento Cliente");
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startHomeActivity(etCustomer.getText().toString());
dialog.dismiss();
}
});
etCustomer.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
startHomeActivity(etCustomer.getText().toString());
dialog.dismiss();
return true;
}
return false;
}
});
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
orderFragment = (OrderFragment) getSupportFragmentManager().findFragmentByTag("orderFragment");
if (orderFragment == null) {
new AccessBoardAsyncTask(mContext).execute("L", mBoard);
}
}
});
dialog.show();
}
If you prefer fix it from your adapter, I think you could fix it declaring a private boolean disableViews = false; in your adapter, then call notifyDataSetChanged(); after user hits a holder.mView:
if (!disableViews) {
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if (mListener != null) {
mListener.onClickBoard(mValues.get(i));
}else{
((MainActivity)mContext).onClickBoard(mValues.get(i).getAreaId(), mValues.get(i).getName());
}
disableViews = true;
notifyDataSetChanged();
}
});
} else {
holder.mView.setOnClickListener(null);
}
And then set disableViews = false; when you want to receive click events again.

java.lang.IndexOutOfBoundsException When Displaying Multiple Data in RecyclerView

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

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