Android RecyclerView item selection issue - java

I am designing a live quiz app that fetches data from server and question are displayed in a RecyclerView that contains a question and four options. Now when I select one option for a given question, it is selected properly but at the same time, the corresponding option for other question is selected automatically.
Screenshot of the item selection issue is the following.
Here is the adapter class of my RecyclerView
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder>{
private int mItemSelected=-1;
private List<DmLiveQuiz> questionList;
DmLiveQuiz questionsList; // DmLiveQuiz questionsList
private Context context; //context
final DataHolder dh=new DataHolder();
public List<Integer> myResponse= new ArrayList<Integer>();
public int qno;
public String myQno;
public int afterSub;
DataHolder dataHolder;
public LiveTestAdapter(List<DmLiveQuiz> questionList, Context context) {
this.questionList = questionList;
this.context = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView= LayoutInflater.from(parent.getContext()).inflate(R.layout.live_quiz_display_format,parent,false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
questionsList=questionList.get(holder.getAdapterPosition());
holder.tvQNo.setText(questionsList.getQuestionId()+"");
holder.tvquestion.getLayoutParams().width= LinearLayout.LayoutParams.WRAP_CONTENT;
holder.tvquestion.setText(questionsList.getQuestion());
holder.optA.setText(questionsList.getOptA());
holder.optB.setText(questionsList.getOptB());
holder.optC.setText(questionsList.getOptC());
holder.optD.setText(questionsList.getOptD());
holder.optA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_border);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_border);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_border);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_border);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.tvClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
}
});
}
#Override
public int getItemCount() {
return questionList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder{
TextView tvquestion, tvClear,tvQNo;
Button optA,optB,optC,optD;
public CustomViewHolder(View itemView) {
super(itemView);
tvQNo=(TextView)itemView.findViewById(R.id.tvLiveQuizQuestionNo);
tvquestion=(TextView)itemView.findViewById(R.id.tvLiveQuizQuestion);
optA=(Button)itemView.findViewById(R.id.buttonOptionA);
optB=(Button)itemView.findViewById(R.id.buttonOptionB);
optC=(Button)itemView.findViewById(R.id.buttonOptionC);
optD=(Button)itemView.findViewById(R.id.buttonOptionD);
tvClear=(TextView)itemView.findViewById(R.id.tvClearSelection);
}
}
}
The only problem I am facing is the auto selection of unanswered options.
Please help me out in selecting the selected option only not the ones which are not selected. Thanks in advance.

The views will be reused in your RecyclerView and hence you are having such a problem. In your case, you might consider having another array which stores the answers of your quizzes and can keep track of every item in your RecyclerView.
I would like to suggest modifying your adapter like the following. I have commented in some places. Hope that helps you to understand your problem.
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder> {
private int mItemSelected = -1;
private List<DmLiveQuiz> questionList;
private int[] answerList; // Get a list of your answers here.
private DmLiveQuiz questionsList;
private Context context;
final DataHolder dh = new DataHolder();
public List<Integer> myResponse = new ArrayList<Integer>();
public int qno;
public String myQno;
public int afterSub;
DataHolder dataHolder;
public LiveTestAdapter(List<DmLiveQuiz> questionList, Context context) {
this.questionList = questionList;
this.context = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.live_quiz_display_format, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
questionsList = questionList.get(holder.getAdapterPosition());
holder.tvQNo.setText(questionsList.getQuestionId() + "");
holder.tvquestion.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
holder.tvquestion.setText(questionsList.getQuestion());
holder.optA.setText(questionsList.getOptA());
holder.optB.setText(questionsList.getOptB());
holder.optC.setText(questionsList.getOptC());
holder.optD.setText(questionsList.getOptD());
// Now you need to modify the backgrounds of your option buttons like the following.
if (answerList[position] == 1) holder.optA.setBackgroundResource(R.drawable.button_border);
else holder.optA.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 2) holder.optB.setBackgroundResource(R.drawable.button_border);
else holder.optB.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 3) holder.optC.setBackgroundResource(R.drawable.button_border);
else holder.optC.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 4) holder.optD.setBackgroundResource(R.drawable.button_border);
else holder.optD.setBackgroundResource(R.drawable.button_question_style);
holder.optA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_border);
answerList[position] = 1; // Selected first option which is A
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optB.setBackgroundResource(R.drawable.button_border);
answerList[position] = 2; // Selected second option which is B
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optC.setBackgroundResource(R.drawable.button_border);
answerList[position] = 3; // Selected third option which is C
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optD.setBackgroundResource(R.drawable.button_border);
answerList[position] = 4; // Selected fourth option which is D
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.tvClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
answerList[position] = 0; // Clear the value in the answerList
}
});
}
// Use this function to set the question list in the adapter
public void setQuestionList(List<DmLiveQuiz> questionList) {
this.questionList = questionList;
this.answerList = new int[questionList.size()]; // This initializes the answer list having the same size as the question list
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return questionList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
TextView tvquestion, tvClear, tvQNo;
Button optA, optB, optC, optD;
public CustomViewHolder(View itemView) {
super(itemView);
tvQNo = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestionNo);
tvquestion = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestion);
optA = (Button) itemView.findViewById(R.id.buttonOptionA);
optB = (Button) itemView.findViewById(R.id.buttonOptionB);
optC = (Button) itemView.findViewById(R.id.buttonOptionC);
optD = (Button) itemView.findViewById(R.id.buttonOptionD);
tvClear = (TextView) itemView.findViewById(R.id.tvClearSelection);
}
}
}
Update - Please check that I have added setQuestionList function in the adapter. Please use this function to set your question list. Because, I think while initializing your adapter, the question list which is being passed is having a size of zero.

Related

How can make other button disable when one is clicked android studio?

I have a scenario where I have 5 ImageView and when one ImageView is clicked i want to set other 4 ImageView as Disabled. Please help to get logic for that.
My Logic for this : when 1 image is click set other 4 imageView as disable but imageView.setClickable(false) is not working.
This Attached Image is a dialog box that appears when users wants to edit something from recycler view. Recycler view contains data like : "Amount", "Item name", "Price", "Expense Type" and expense type image is set to On corresponding to "Expense Type".
I am stuck in this moment. Please help me out to solve this.
I have attached my scenario images Please check it out.
Here's my code for this
public class MyAdapter extends FirebaseRecyclerAdapter<ExpenseModel, MyAdapter.MyViewHolder> {
Context context;
private int lastPosition = -1;
private String whichCategorySelected = "";
private int calImgClick = 0;
private int groceryClick = 0;
private int bikeClick = 0;
private int rentClick = 0;
private int foodsClick = 0;
private int beerClick = 0;
public MyAdapter(#NonNull FirebaseRecyclerOptions<ExpenseModel> options, Context context) {
super(options);
this.context = context;
}
#SuppressLint("SetTextI18n")
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, #SuppressLint("RecyclerView") int position, #NonNull ExpenseModel model) {
holder.expenseItem.setText(model.getDescription());
holder.expenseAmount.setText("Rs. " + model.getAmount());
holder.expenseDate.setText(model.getTime());
String expType = model.getExType();
switch (expType) {
case "Beer":
holder.category.setBackgroundResource(R.drawable.beer);
break;
case "Grocery":
holder.category.setBackgroundResource(R.drawable.grocery);
break;
case "Bike":
holder.category.setBackgroundResource(R.drawable.bike);
break;
case "Rent":
holder.category.setBackgroundResource(R.drawable.rent);
break;
default:
holder.category.setBackgroundResource(R.drawable.fd);
break;
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopMenuOnItemClicked(view, holder.getLayoutPosition(), model.getDescription(), model.getAmount(), model.getTime(), model.getExType());
}
});
}
private void showPopMenuOnItemClicked(View v, int pos, String getExpTitle, String getExpAmt, String getDate, String whichCatSelected) {
PopupMenu popupMenu = new PopupMenu(context, v);
popupMenu.getMenu().add("Edit");
popupMenu.getMenu().add("Delete");
popupMenu.getMenu().add("Delete All");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getTitle().equals("Edit")) {
showUpdateDialogBox(v, getExpTitle, getExpAmt, getDate, whichCatSelected);
} else if (menuItem.getTitle().equals("Delete")) {
FirebaseReference.expenseReference(context)
.child(String.valueOf(getRef(pos).getKey()))
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(context.getApplicationContext(), "Delete everything", Toast.LENGTH_SHORT).show();
}
return true;
}
});
popupMenu.show();
}
#SuppressLint("ClickableViewAccessibility")
private void showUpdateDialogBox(View v, String getExpTitle, String getExpAmt, String getDate, String whichCatSelected) {
DialogPlus dialog = DialogPlus.newDialog(context)
.setContentHolder(new ViewHolder(R.layout.update_expense_layout))
.setExpanded(false)
.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogPlus dialog) {
onDismissSetClickCountToZero();
Utility.hideKeyboard(context, v);
}
})
.create();
View myView = dialog.getHolderView();
TextView update_expense_date = myView.findViewById(R.id.update_expense_date);
EditText update_expense_title = myView.findViewById(R.id.update_expense_title);
EditText update_expense_amount = myView.findViewById(R.id.update_expense_amount);
ImageView update_calendarImg = myView.findViewById(R.id.update_calendar);
Button update_button = myView.findViewById(R.id.update_btn);
LinearLayout linearLayout = myView.findViewById(R.id.update_linearCalenderLayout);
linearLayout.setVisibility(View.GONE);
CalendarView calendarView = myView.findViewById(R.id.update_calenderView);
LinearLayout categoryLayout = myView.findViewById(R.id.update_categoryIconsLayout);
TextView categoryTextView = myView.findViewById(R.id.update_selectCategory_heading);
update_expense_title.setText(getExpTitle);
update_expense_amount.setText(getExpAmt);
update_expense_date.setText(getDate);
ImageView beer = myView.findViewById(R.id.update_beer);
ImageView bike = myView.findViewById(R.id.update_bike);
ImageView grocery = myView.findViewById(R.id.update_grocery);
ImageView foods = myView.findViewById(R.id.update_foods);
ImageView rent = myView.findViewById(R.id.update_rent);
TextView desc_grocery = myView.findViewById(R.id.update_desc_grocery);
TextView desc_bike = myView.findViewById(R.id.update_desc_bike);
TextView desc_beer = myView.findViewById(R.id.update_desc_beer);
TextView desc_foods = myView.findViewById(R.id.update_desc_foods);
TextView desc_rent = myView.findViewById(R.id.update_desc_rent);
setIconVisible(whichCatSelected, bike, grocery, foods, beer, rent,
desc_bike, desc_grocery, desc_foods, desc_beer, desc_rent);
setWhichCategorySelected(whichCatSelected);
Toast.makeText(context, "Default select = " + getWhichCategorySelected() + " click = " + rentClick, Toast.LENGTH_SHORT).show();
update_calendarImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calImgClick++;
if (calImgClick >= 2) {
linearLayout.setVisibility(View.GONE);
categoryLayout.setVisibility(View.VISIBLE);
categoryTextView.setVisibility(View.VISIBLE);
calImgClick = 0;
} else {
linearLayout.setVisibility(View.VISIBLE);
categoryLayout.setVisibility(View.GONE);
categoryTextView.setVisibility(View.GONE);
}
}
});
rent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getWhichCategorySelected().equals("") || getWhichCategorySelected().equals("Rent")){
rentClick ++;
if (rentClick >= 2) {
setWhichCategorySelected("");
rent.setBackgroundResource(R.drawable.rent_off);
desc_rent.setVisibility(View.GONE);
grocery.setClickable(true);
bike.setClickable(true);
foods.setClickable(true);
beer.setClickable(true);
rentClick = 0;
} else {
setWhichCategorySelected("Rent");
rent.setBackgroundResource(R.drawable.rent);
desc_rent.setVisibility(View.VISIBLE);
grocery.setClickable(false);
bike.setClickable(false);
foods.setClickable(false);
beer.setClickable(false);
}
}else {
Toast.makeText(context, "Category is selected " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "whichCategorySelected = " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
});
grocery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getWhichCategorySelected().equals("") || getWhichCategorySelected().equals("Grocery")){
groceryClick ++;
if (groceryClick >= 2) {
setWhichCategorySelected("");
grocery.setBackgroundResource(R.drawable.grocery_off);
desc_grocery.setVisibility(View.GONE);
rent.setClickable(true);
bike.setClickable(true);
foods.setClickable(true);
beer.setClickable(true);
rentClick = 0;
} else {
setWhichCategorySelected("Grocery");
grocery.setBackgroundResource(R.drawable.grocery);
desc_grocery.setVisibility(View.VISIBLE);
rent.setClickable(false);
bike.setClickable(false);
foods.setClickable(false);
beer.setClickable(false);
}
}else {
Toast.makeText(context, "Category is selected " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "whichCategorySelected = " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
});
update_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateChildren(update_expense_amount, update_expense_title, update_expense_date, whichCatSelected);
}
});
dialog.show();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
return new MyViewHolder(v);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView expenseItem, expenseAmount, expenseDate;
ImageView category;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
expenseItem = itemView.findViewById(R.id.recyclerItemView);
expenseAmount = itemView.findViewById(R.id.recyclerAmountView);
expenseDate = itemView.findViewById(R.id.recyclerDateView);
category = itemView.findViewById(R.id.recyclerCategory);
}
}

How to highlight a selected RecyclerView item and use its values in Activity

I have a list of words with translations in RecyclerView. I want the selected word to be highlighted, but at the same time I could use these values in Activity. I can highlight selected values or use the values of a selected item, but the combination of the both fails.
Please, maybe You see where I am wrong and can help solve my problem.
p.s. Please don’t judge me for the not enough clean code and my English, I’m learning. :)
MyListActivity.java
public class MyListActivity extends AppCompatActivity {
public ArrayList<MyWord> myWordList = new ArrayList<>();
SelectData sd = new SelectData();
int wordId;
String word;
String translation;
public RecyclerView mRecycleView;
public MyAdapter mAdapter;
public RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_list);
sd.selectMyWords(myWordList);
buildRecycleView();
Button btnInsert = findViewById(R.id.mywords_button_insert);
Button btnEdit = findViewById(R.id.mywords_button_edit);
Button btnDelete = findViewById(R.id.mywords_button_delete);
Button btnMain = findViewById(R.id.mywords_button_backttomain);
mAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// **This is my selected item values**
wordId = myWordList.get(position).getWordId();
word = myWordList.get(position).getWord();
translation = myWordList.get(position).getTranslation();
Toast.makeText(MyListActivity.this, "Selected -> " + word, Toast.LENGTH_SHORT).show();
}
});
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(word == null)) {
Intent intentInsert = new Intent(MyListActivity.this, InsertActivity.class);
intentInsert.putExtra("W", word);
intentInsert.putExtra("TR", translation);
intentInsert.putExtra("ACTION", "ED");
startActivity(intentInsert);
} else {
Toast.makeText(MyListActivity.this, "Select word", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void buildRecycleView(){
mRecycleView = findViewById(R.id.mywords_RecycleView);
mRecycleView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MyAdapter(myWordList);
mRecycleView.setLayoutManager(mLayoutManager);
mRecycleView.setAdapter(mAdapter);
if (myWordList.isEmpty()){
Toast.makeText(this, "word list is empty", Toast.LENGTH_SHORT).show();
}
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<MyWord> mMyWordList;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewEN;
public TextView mTextViewLT;
public ImageView imageViewLearned;
public MyViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextViewEN = itemView.findViewById(R.id.myList_textView_word);
mTextViewLT = itemView.findViewById(R.id.myList_textView_translation);
imageViewLearned = itemView.findViewById(R.id.iV_learned);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public MyAdapter(ArrayList<MyWord> myWordList){
mMyWordList = myWordList;
}
int selectedItem = -1;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_view_layout, parent, false);
MyViewHolder mvh = new MyViewHolder(v, mListener);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
MyWord currentMyWord = mMyWordList.get(position);
holder.mTextViewEN.setText(currentMyWord.getWord());
holder.mTextViewLT.setText(currentMyWord.getTranslation());
// TODO - START (select item highlight) - if I activate highlighting, the assignment of values no longer works in MyListActivity.
/* holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedItem = position;
notifyDataSetChanged();
}
});
if (selectedItem == position) {
holder.itemView.setBackgroundColor(Color.parseColor("#C0C0C0"));
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#F8F8F8"));
} */
//TODO -END
}
#Override
public int getItemCount() {
return mMyWordList.size();
}
}
Looks like your commented code would overwrite your click listener with one that only hightlights. Try combining them:
public MyViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextViewEN = itemView.findViewById(R.id.myList_textView_word);
mTextViewLT = itemView.findViewById(R.id.myList_textView_translation);
imageViewLearned = itemView.findViewById(R.id.iV_learned);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
selectedItem = position;
notifyDataSetChanged();
listener.onItemClick(position);
}
}
}
});
}

How To Refresh Item Positions In Recylcerview for filtering?

I want to filter recyclerView items, my code is working well in terms of displaying filtered items but when I am clicking on those items it's clicking on previous items though those items are not visible. I thought the problem is on item clickListener implementation but I have tried two recylcerview onitemClickListener implementation but both of them aren't working.
Can You Please Help? Thanks In Advance.
Here is the filter code in Recyclerview Adapter.
public void updateList(List<ProductInfo> list){
mProductList = list;
notifyDataSetChanged();
}
Here is the Clicklistener on Recyclerview in Activity.
mProductAdapter = new AdapterTest(mProductInfos, new AdapterTest.ClickListener(){
#Override
public void onPositionClicked(View v, int position) {
ProductInfo productInfo = mProductInfos.get(position);
Intent intent = new Intent(VegetableActivity.this, DescriptionActvity.class);
intent.putExtra(MainActivity.EXTRA_OBJECT, productInfo);
startActivity(intent);
}
#Override
public void onLongClicked(View v, int position) {
}
});
And This is the Adapter Class.
public class AdapterTest extends RecyclerView.Adapter<AdapterTest.MyviewHolder> {
private List<ProductInfo> mProductList;
private ClickListener listener;
public class MyviewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
private TextView mProductName, mProductPrice, mProductRating;
private ImageView mProductImage;
private WeakReference<ClickListener> listenerRef;
public MyviewHolder(View itemView, ClickListener listener) {
super(itemView);
listenerRef = new WeakReference<>(listener);
mProductName = itemView.findViewById(R.id.product_name);
mProductPrice = itemView.findViewById(R.id.product_price);
//mProductRating = itemView.findViewById(R.id.product_rating);
mProductImage = itemView.findViewById(R.id.product_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
// if(view.getId() == decreaseView.getId()){
// Toast.makeText(view.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
// }else {
// Toast.makeText(view.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
// }
listenerRef.get().onPositionClicked(view, getAdapterPosition());
}
#Override
public boolean onLongClick(View view) {
return false;
}
}
public AdapterTest(List<ProductInfo> productList, ClickListener listener){
mProductList = productList;
this.listener = listener;
}
#Override
public MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.vegetable_layout, parent, false);
return new MyviewHolder(itemView, listener);
}
#Override
public void onBindViewHolder(MyviewHolder holder, int position) {
ProductInfo productInfo = mProductList.get(position);
holder.mProductName.setText(productInfo.getProductName());
holder.mProductPrice.setText(productInfo.getProductPrice());
//holder.mProductRating.setText(productInfo.getProductRating());
Picasso.get()
.load(productInfo.getProductImage())
.into(holder.mProductImage);
}
#Override
public int getItemCount() {
return mProductList.size();
}
public interface ClickListener {
void onPositionClicked(View v, int position);
void onLongClicked(View v, int position);
}
public void updateList(List<ProductInfo> list){
mProductList = list;
notifyDataSetChanged();
}
}
you can move below code segement to onCLick evenet of the recycle item
Intent intent = new Intent(VegetableActivity.this, DescriptionActvity.class);
intent.putExtra(MainActivity.EXTRA_OBJECT, productInfo);
startActivity(intent);
you donot need the onPositionClicked listener for that and you can remove ProductInfo productInfo = mProductInfos.get(position); as well. I have no clear idea about what u doing. but let say u want to nevigate to another page when u click on recycle item. u can add it like below
#Override
public void onBindViewHolder(MyviewHolder holder, int position) {
ProductInfo productInfo = mProductList.get(position);
holder.mProductName.setText(productInfo.getProductName());
holder.mProductPrice.setText(productInfo.getProductPrice());
//holder.mProductRating.setText(productInfo.getProductRating());
Picasso.get()
.load(productInfo.getProductImage())
.into(holder.mProductImage);
//new code - start here
holder.anyuielementInItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Do things you want
}
});
//
}

how to get values from sqlite in view holder

product Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductViewHolder>{
private Context context;
private List<Product> listProducts;
private SqliteDatabase mDatabase;
public ProductAdapter(Context context, List<Product> listProducts) {
this.context = context;
this.listProducts = listProducts;
mDatabase = new SqliteDatabase(context);
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_list_layout, parent, false);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
final Product singleProduct = listProducts.get(position);
holder.name.setText(singleProduct.getName());
// holder.quantity.setText(singleProduct.getQuantity());
//when i call quantity(the ABOVE value) the application crashes and when i call only name the field the values gets displayed
holder.editProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTaskDialog(singleProduct);
}
});
holder.deleteProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabase.deleteProduct(singleProduct.getId());
((Activity)context).finish();
context.startActivity(((Activity) context).getIntent());
}
});
}
#Override
public int getItemCount() {
return listProducts.size();
}
private void editTaskDialog(final Product product){
LayoutInflater inflater = LayoutInflater.from(context);
View subView = inflater.inflate(R.layout.add_product_layout, null);
final EditText nameField = (EditText)subView.findViewById(R.id.enter_name);
final EditText quantityField = (EditText)subView.findViewById(R.id.enter_quantity);
if(product != null){
nameField.setText(product.getName());
quantityField.setText(String.valueOf(product.getQuantity()));
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Edit product");
builder.setView(subView);
builder.create();
builder.setPositiveButton("EDIT PRODUCT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String name = nameField.getText().toString();
final String quantityStr = quantityField.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(quantityStr))
{
Toast.makeText(context, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
}
else
{
final int quantity = Integer.parseInt(quantityStr);
if(quantity<=0)
{
Toast.makeText(context,"input is less than or equal to zero",Toast.LENGTH_LONG).show();
}
else {
mDatabase.updateProduct(new Product(product.getId(), name, quantity));
//refresh the activity
((Activity)context).finish();
context.startActivity(((Activity)context).getIntent());
}
}
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Task cancelled", Toast.LENGTH_LONG).show();
}
});
builder.show();
}
}
product viewHolder
public class ProductViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView quantity;
public ImageView deleteProduct;
public ImageView editProduct;
public ProductViewHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.product_name);
deleteProduct = (ImageView)itemView.findViewById(R.id.delete_product);
editProduct = (ImageView)itemView.findViewById(R.id.edit_product);
quantity=(TextView)itemView.findViewById(R.id.product_name2);
}
}
Now the issue here is when is use holder.quantity.setText(singleProduct.getQuantity()) the application crashes.
I also wanted to add date picker dialog and want to display it in the recycler view so for date the code is same like holder.object.setText or something else and can we use a form for alert dialog like
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_dark);
dialog.setCancelable(true);
I have created the database file but the issue is mainly related to recycler view contents and if i wanted multiple holder is it possible to get the contents?
getQuantity() returns a int. So, Android is trying to search for a resource with id == getQuantity() leading to the crash (since you probably any resource with that id.
In other words, you are invoking TextView.setText(int resourceId) and not TextView.setText(String text)).
To fix, change this:
holder.quantity.setText(singleProduct.getQuantity());
To this:
holder.quantity.setText(String.valueOf(singleProduct.getQuantity()));

RecyclerView getting wrong position When Apply Search with Search Filter

I use RecyclerView and I have implemented Search Filter on it and i am facing a problem here
After I search when I press on item I get wrong position not one I searched it please help me to solve this problem
For example item number 2 name "Android" after search "android" the position go number one .. why get this problem ? .. thank you
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<RecyclerItem> listItems;
private Context mContext;
public MyAdapter(List<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = holder.getAdapterPosition();
if (position == 0) {
Toast.makeText(mContext,"iOS",Toast.LENGTH_SHORT).show();
}
if (position == 1) {
Toast.makeText(mContext,"Android",Toast.LENGTH_SHORT).show();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
holder.txtDescription.setText(itemList.getDescription());
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Display option menu
PopupMenu popupMenu = new PopupMenu(mContext, holder.txtOptionDigit);
popupMenu.inflate(R.menu.option_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_item_save:
Toast.makeText(mContext, "Saved " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.mnu_item_delete:
//Delete item
Toast.makeText(mContext, "Deleted " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
listItems.remove(position);
notifyDataSetChanged();
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button buttoncalling;
public TextView txtTitle;
public TextView txtDescription;
public TextView txtOptionDigit;
public ViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDescription);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
buttoncalling = (Button) itemView.findViewById(R.id.bbbbbbbbbb);
buttoncalling.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
Filter
TextWatcher mTextWatcher = 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) {
if (s.toString().equals("")){
initAdapter();
} else {
searchItem(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
private void initAdapter(){
adapter.listItems.clear();
for (int i = 0; i < 10; i++) {
listItems.add(new RecyclerItem("Item " + (i + 1), "Welcome to Torisan channel, this is description of item " + (i+1)));
}
adapter.notifyDataSetChanged();
}
private void searchItem(String itemname){
int resultCount = 0;
adapter.listItems.clear();
for (int i = 0; i < tempListItems.size(); i++){
if (tempListItems.get(i).getTitle().contains(itemname)){
listItems.add(new RecyclerItem("Item " + (i + 1), "Welcome to Torisan channel, this is description of item " + (i+1)));
resultCount ++;
}
}
if (resultCount == 0){
showToast();
}
adapter.notifyDataSetChanged();
}
public void showToast() {
// Set the toast and duration
int toastDurationInMilliSeconds = 1000;
mToastToShow = Toast.makeText(this, "No results found.", Toast.LENGTH_LONG);
// Set the countdown to display the toast
CountDownTimer toastCountDown;
toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
public void onTick(long millisUntilFinished) {
mToastToShow.show();
}
public void onFinish() {
mToastToShow.cancel();
}
};
// Show the toast and starts the countdown
mToastToShow.show();
toastCountDown.start();
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<RecyclerItem> listItems;
private Context mContext;
public MyAdapter(List<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setTag(getAdapterPosition());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = Integer.parse(v.getTag().toString());
if (position == 0) {
Toast.makeText(mContext,"iOS",Toast.LENGTH_SHORT).show();
}
if (position == 1) {
Toast.makeText(mContext,"Android",Toast.LENGTH_SHORT).show();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
holder.txtDescription.setText(itemList.getDescription());
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Display option menu
PopupMenu popupMenu = new PopupMenu(mContext, holder.txtOptionDigit);
popupMenu.inflate(R.menu.option_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_item_save:
Toast.makeText(mContext, "Saved " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.mnu_item_delete:
//Delete item
Toast.makeText(mContext, "Deleted " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
listItems.remove(position);
notifyDataSetChanged();
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button buttoncalling;
public TextView txtTitle;
public TextView txtDescription;
public TextView txtOptionDigit;
public ViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDescription);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
buttoncalling = (Button) itemView.findViewById(R.id.bbbbbbbbbb);
buttoncalling.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
Please use this
for (int i = 0; i < tempListItems.size(); i++) {
if (listItems.get(getAdapterPosition()).getName().equals(tempListItems.get(i).getName())) {
int selectedPos = i; //SelectedPos is that index
break;
}
}

Categories

Resources