i have Recycler view with radio group and its 4 radio buttons. but when i scroll down the list the middle of item is acting like first one . means if i have 10 items, if select first item button then the 6 button also got selecting with user selection.
what to do for issue in recycler view. Any Suggestions will be appreciable.
Thanks in Advance.
enter code here
public class ViewHolder extends RecyclerView.ViewHolder {
TextView quest, timestamp, answer;
RadioGroup rg;
RadioButton rb1, rb2, rb3, rb4;
Button submit;
public ViewHolder(View view) {
super(view);
quest = (TextView) itemView.findViewById(R.id.ques);
timestamp = (TextView) itemView.findViewById(R.id.tym);
answer = (TextView) itemView.findViewById(R.id.answer);
rb1 = (RadioButton)itemView.findViewById(R.id.rb1);
rb2 = (RadioButton)itemView.findViewById(R.id.rb2);
rb3 = (RadioButton)itemView.findViewById(R.id.rb3);
rb4 = (RadioButton)itemView.findViewById(R.id.rb4);
rb4 = (RadioButton)itemView.findViewById(R.id.rb4);
rg = (RadioGroup)itemView.findViewById(R.id.radio);
submit = (Button)itemView.findViewById(R.id.submit);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int radioButtonID = group.getCheckedRadioButtonId();
View radioButton = group.findViewById(radioButtonID);
int clickedPos= (int) group.getTag();
Log.v("currentpos",""+clickedPos);
messageArrayList.get(clickedPos).setSelectedRadioButtonId(checkedId);
int radioId = group.indexOfChild(radioButton);
RadioButton btn = (RadioButton) group.getChildAt(radioId);
final int currentPosition = getAdapterPosition();
if (messageArrayList.get(clickedPos).getSelectedRadioButtonId() != -1 && checkedId != -1) {
try {
String selection = btn.getText().toString();
if (selection.equalsIgnoreCase(messageArrayList.get(clickedPos).getAnswer().toString())) {
Log.v("TAG", "USER OPTION" + "\t" + selection + "\n" + "CORRECT ANSWER IS" + "\t" + messageArrayList.get(clickedPos).getAnswer());
// rg.setVisibility(View.INVISIBLE);
// answer.setVisibility(View.VISIBLE);
// answer.setText("Congrats, you are right. The answer is " + messageArrayList.get(clickedPos).getAnswer().toString());
Toast.makeText(group.getContext(), "YOu are Right", Toast.LENGTH_SHORT).show();
} else {
// rg.setVisibility(View.INVISIBLE);
// answer.setVisibility(View.VISIBLE);
// answer.setText("Oops, you're wrong, the correct answer is " + messageArrayList.get(clickedPos).getAnswer().toString());
Toast.makeText(group.getContext(), "You are Worng", Toast.LENGTH_SHORT).show();
}
Log.v("hello", selection);
String qusnn = quest.getText().toString();
Log.v("question", qusnn);
String read = "1";
try {
helper = new DBHelper(group.getContext());
database = helper.getWritableDatabase();
statement = database.compileStatement("update quiz set USERANS =? where QUESTION ='" + qusnn + "'");
statement.bindString(1, read);
statement.executeInsert();
database.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("exception for send data in table");
} finally {
database.close();
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v("hello", exceptionAsString);
}
Log.v("hello" + clickedPos, messageArrayList.get(clickedPos).getSelectedRadioButtonId() + "");
}
}});
}
}
public ChatRoomThreadAdapter( ArrayList<Message> messageArrayList) {
this.messageArrayList = messageArrayList;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == SELF) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_items, parent, false);
}else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.secondlayout, parent, false);
}
return new ViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if (message.getUsans().equals("0")) {
return SELF;
}
return position;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder,final int position) {
final Message message = messageArrayList.get(position);
((ViewHolder) holder).quest.setText(message.getMessage());
((ViewHolder) holder).rb1.setText(message.getOpt1());
((ViewHolder) holder).rb2.setText(message.getOpt2());
((ViewHolder) holder).rb3.setText(message.getOpt3());
((ViewHolder) holder).rb4.setText(message.getOpt4());
((ViewHolder) holder).answer.setText(message.getAnswer());
String timestam= getTimeStamp(message.getCreatedAt());
((ViewHolder) holder).timestamp.setText(timestam);
// ((ViewHolder) holder).rg.clearCheck();
// ((ViewHolder) holder).rg.setTag(position);
// Log.e("select" + position, messageArrayList.get(position).getSelectedRadioButtonId() + "");
((ViewHolder) holder).rg.setTag(position);
if (message.getSelectedRadioButtonId()!= -1){
((ViewHolder) holder).rg.check(message.getSelectedRadioButtonId());
}else{
//your always need to write else condition
((ViewHolder) holder).rg.clearCheck();
}
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
public static String getTimeStamp(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "";
today = today.length() < 2 ? "0" + today : today;
try {
Date date = format.parse(dateStr);
SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
String dateToday = todayFormat.format(date);
format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
String date1 = format.format(date);
timestamp = date1.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
}
enter code here
public class Message implements Serializable {
String id, message, opt1, opt2, opt3, opt4, answer, createdAt,usans;
public Message() {
}
public Message(String id, String message, String opt1, String opt2, String opt3, String opt4, String answer, String createdAt,String usans) {
this.id = id;
this.message = message;
this.opt1 = opt1;
this.opt2 = opt2;
this.opt3 = opt3;
this.opt4 = opt4;
this.answer = answer;
this.createdAt = createdAt;
this.usans = usans;
}
private int checkedId = -1;
public int getSelectedRadioButtonId() {
return checkedId;
}
public void setSelectedRadioButtonId(int checkedId) {
this.checkedId = checkedId;
}
public String getUsans() {
return usans;
}
public void setUsans(String usans) {
this.usans = usans;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setOpt1(String opt1) {
this.opt1 = opt1;
}
public String getOpt1() {
return opt1;
}
public void setOpt2(String opt2) {
this.opt2 = opt2;
}
public String getOpt2() {
return opt2;
}
public void setOpt3(String opt3) {
this.opt3 = opt3;
}
public String getOpt3() {
return opt3;
}
public void setOpt4(String opt4) {
this.opt4 = opt4;
}
public String getOpt4() {
return opt4;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getAnswer() {
return answer;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
}
Write this in your onBindViewHolder() of adapter class:
holder.setIsRecyclable(false);
I had the same issue and adding this code had helped me.
Edit:The issue is caused because when we scroll in Recycler View the cells gets recycled and in order to make sure the cells don't get recycled, the above method is used.
Looking at your code and comments I think you know how RecyclerView works especially re-using views.. The only thing you missed is setting view status on all scenarios, what I mean is - you always need to write else part of code
class MyViewHolder extends RecyclerView.ViewHolder {
RadioGroup vRadioGroup;
public MyViewHolder(View itemView) {
super(itemView);
vRadioGroup = (RadioGroup) itemView.findViewById(R.id.group1);
//your other stuff
vRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int clickedPos= (int) radioGroup.getTag();
messageArrayList.get(clickedPos).setSelectedRadioButtonId(radioButtonID);
}
});
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Message message = messageArrayList.get(position);
//your other stuff
holder.vRadioGroup.setTag(position);
if (message.getSelectedRadioButtonId()!= -1){
holder.vRadioGroup.check(message.getSelectedRadioButtonId());
}else{
//your always need to write else condition
holder.vRadioGroup.clearCheck();
}
}
hope this helps..
Related
I am working on a chat app and I am very new to using ListViews and ArrayAdapters, as well as Custom Adapters. I am having a problem that causes all my items in my list to be of one layout, even they are supposed to change according to a booleans(true would be an outgoing chat bubble, and false would be an incoming chat bubble).
Here is my code for the retreival of the chat(It isn't the whole file, just a snippet):
Variable declarations:
final ArrayList<chatBubble> objects = new ArrayList<>();
final CustomAdapter customAdapter = new CustomAdapter(this, objects);
listView.setAdapter(customAdapter);
Code to get messages and add to list:
mDatabase.child("chat").child("publicDump").child("dumpedMessages").child("message" + i).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String message = dataSnapshot.getValue(String.class);
if (message != null) {
final String extract = message.substring(message.lastIndexOf("<") + 1, message.indexOf(">"));
mDatabase.child("users").child("c").child("emailToUsername").child(mAuth.getCurrentUser().getEmail().replace(".", ",")).child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue(String.class);
if (username != null) {
if (username.equals(extract)) {
Log.i("Extract", extract);
int semicnt = 0;
int num = 0;
//Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, true);
objects.add(chat);
}
}
}
} else {
int semicnt = 0;
int num = 0;
// Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, false);
objects.add(chat);
}
}
}
}
customAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is my code for my chatBubble:
package com.tejasmehta.codeychat;
public class chatBubble {
private String msg;
private String date;
private boolean myMessage;
public chatBubble(String msg, String date, boolean myMessage) {
this.msg = msg;
this.date = date;
this.myMessage = myMessage;
}
public String Msg() {
return msg;
}
public String Date() {
return date;
}
public boolean myMessage() {
return myMessage;
}
}
And here is my code for my customAdapter(which shows that if the boolean, myMessage, is true, it will load a different layout, and a different one for false):
public class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<chatBubble> objects;
private class ViewHolder {
TextView msg;
TextView date;
}
public CustomAdapter(Context context, ArrayList<chatBubble> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public chatBubble getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}
}
Thank You for all of your help!
the problem is your getview
The view is being recycled so convertview already has a layout. so its not being reinflated to the correct layout.
you need to use getViewType() and getViewTypeCount() to tell the listview you want to use different layouts
http://android.amberfog.com/?p=296
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).myMessage()?0:1;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}
CODE:
private static final String CREATE_DETAILEDMEALS = "CREATE TABLE "
+ TABLE_DetailedMeals + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
+ mealsName + " TEXT unique," + categoryId + " INTEGER,"
+ desc + " TEXT," + size + " TEXT,"
+ price + " TEXT" + ")";
public void addDetailedMeals(String name, int catId, String d, String s, String p){
ContentValues values = new ContentValues(1);
values.put(mealsName, name);
values.put(categoryId, catId);
values.put(desc, d);
values.put(size, s);
values.put(price, p);
getWritableDatabase().insert(TABLE_DetailedMeals, null, values);
}
public Cursor getMeals2(int id)
{
Cursor cursor = getReadableDatabase().rawQuery("SELECT Name, Description, Size, Price FROM " + TABLE_DetailedMeals + " WHERE " + categoryId + "=" + String.valueOf(id), null);
return cursor;
}
// ID1 = MEALS
public ArrayList<DetailedMeals> GetDetailedMeals(int ID1)
{
ArrayList<DetailedMeals> list = new ArrayList<DetailedMeals>();
Cursor cursor = getMeals2(ID1);
int i = 0; // Iterator for 'do-while'. While it gets Categories names, it shall catch all the url's from array as well.
if (cursor.moveToFirst())
{
do
{
DetailedMeals cat = new DetailedMeals();
cat.setName(cursor.getString(cursor.getColumnIndex(mealsName))); //mealsName
cat.setDescription(cursor.getString(cursor.getColumnIndex(mealsName)));
cat.setSize(cursor.getString(cursor.getColumnIndex(mealsName)));
cat.setPrice(cursor.getString(cursor.getColumnIndex(mealsName)));
switch (ID1) {
case 1: cat.setImage(PIZZA_image_urls[i]);
break;
case 2: cat.setImage(BEER_image_urls[i]);
break;
default:
break;
}
list.add(cat);
i++;
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}
Adapter:
public class DifferentRowAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
FragmentActivity c;
ArrayList<DetailedMeals> MealsList;
private final int MEAL = 0, DETAIL = 1;
public DifferentRowAdapter(FragmentActivity c, ArrayList<DetailedMeals> MealsList) {
this.c = c;
this.MealsList = MealsList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case MEAL:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rec_item, parent, false);
return new mViewHolder(view);
case DETAIL:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.details_item, parent, false);
return new dViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
DetailedMeals object = MealsList.get(position);
if (object != null) {
switch (object.getmType()) {
case MEAL:
((mViewHolder) holder).mNameTextView.setText(object.getName());
Glide.with(c)
.load(MealsList.get(position).getImage())
.diskCacheStrategy(DiskCacheStrategy.ALL) // Saves the media item after all transformations to cache and
// Saves just the original data to cache.
.placeholder(R.mipmap.ic_launcher)
.into(((mViewHolder) holder).img);
break;
case DETAIL:
((dViewHolder) holder).descTextView.setText(object.getDescription());
((dViewHolder) holder).sizeTextView.setText(object.getSize());
((dViewHolder) holder).priceTextView.setText(object.getPrice());
break;
}
}
}
#Override
public int getItemCount() {
if (MealsList == null)
return 0;
return MealsList.size();
}
#Override
public int getItemViewType(int position) {
if (MealsList != null) {
DetailedMeals object = MealsList.get(position);
if (object != null) {
return object.getmType();
}
}
return 0;
}
public class dViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView descTextView;
TextView sizeTextView;
TextView priceTextView;
detailsItemClickListener icl;
public dViewHolder(View itemView) {
super(itemView);
// Get references to desc, size, price
descTextView = (TextView) itemView.findViewById(R.id.desc);
sizeTextView = (TextView) itemView.findViewById(R.id.size);
priceTextView = (TextView) itemView.findViewById(R.id.price);
itemView.setOnClickListener(this);
}
public void setItemClickListener(detailsItemClickListener icl)
{
this.icl = icl;
}
#Override
public void onClick(View v){
this.icl.onItemClick(v, getPosition());
}
}
public class mViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mNameTextView;
ImageView img;
mealsItemClickListener icl;
public mViewHolder(View itemView) {
super(itemView);
// Get references to image and name.
mNameTextView = (TextView) itemView.findViewById(R.id.name);
img = (ImageView) itemView.findViewById(R.id.category_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(mealsItemClickListener icl)
{
this.icl = icl;
}
#Override
public void onClick(View v){
this.icl.onItemClick(v, getPosition());
}
}
}
DetailedMeals.class
public class DetailedMeals {
private String name;
private String image;
private String description;
private String size;
private String price;
private int id;
private int mType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public int getmType() {
return mType;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Right now, GetDetailedMeals(..) returns only details name (not name/desc/price/size) ect. and also, it tries to return it before I get recyclerview with only Meal names.
My goal here is: https://img.exs.lv/l/a/lat-deels/fragm_1.png
Change your DifferentRowAdapter extends to RecyclerView.Adapter because the viewholder you are using is within the DifferentRowAdapter.
list.add(cat); in your code you are putting a DetailedMeals in a DiffRowAdapter list
So change the
public ArrayList<DifferentRowAdapter> GetDetailedMeals(int ID1)
to
public ArrayList<DetailedMeals> GetDetailedMeals(int ID1)
to have a same list and adapter.
then put result hear to know what happens.
Update:
after changing them you have just showing the name in your view so add more items like price or desc in mViewHolder:
public mViewHolder(View itemView) {
super(itemView);
// Get references to image and name.
mNameTextView = (TextView) itemView.findViewById(R.id.name);
// Add them hear
mPriceTextView = (TextView) itemView.findViewById(R.id.price);
mDescTextView = (TextView) itemView.findViewById(R.id.desc);
img = (ImageView) itemView.findViewById(R.id.category_image);
itemView.setOnClickListener(this);
}
I am getting value from checking page adapter.If click the plus image in one list item the count value get increase.I want to update that particular value of child item in expandablelistview adapter.How to update that particular child value from checking page adapter.
Checkinapadater:
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Movie1 m = movieItems.get(position);
if (m.getfood_totalprice() != null) {
if (!m.getfood_totalprice().equals("null")) {
holder.amount.setText(m.getfood_totalprice());
}
}
if (m.getfood_count() != null) {
if (!m.getfood_count().equals("null")) {
holder.item_count.setText(m.getfood_count());
}
}
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(holder.item_count.getText().toString());
if(i>=0){
int count = i + 1;
holder.item_count.setText(Integer.toString(count));
value = Integer.toString(count);
}
});
holder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(holder.item_count.getText().toString());
if(i>0){
int count = i - 1;
holder.item_count.setText(Integer.toString(count));
}
});
}
Exapanadablelistapater:
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Child child = (Child) getChild(groupPosition, childPosition);
final Child modelChild = groups.get(groupPosition).getItems().get(childPosition);
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(parent.getContext());
convertView = inflator.inflate(R.layout.detail_list, null);
viewHolder = new ViewHolder();
viewHolder.minus = (ImageView) convertView.findViewById(R.id.minus);
viewHolder.plus = (ImageView) convertView.findViewById(R.id.plus);
viewHolder.green = (ImageView) convertView.findViewById(R.id.green);
viewHolder.red = (ImageView) convertView.findViewById(R.id.red);
viewHolder.item_count = (TextView) convertView.findViewById(R.id.count);
//viewHolder.txtView = (TextView) ((AppCompatActivity)context).findViewById(R.id.checked_item);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv.setText(child.getName());
viewHolder.amount.setText(child.getPrice());
viewHolder.item_count.setText(Integer.toString(child.getCount()));
viewHolder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(modelChild.getCount()>=0) // set your count default 0 when you bind data initially
{
int count = (modelChild.getCount()) + 1;
modelChild.setCount(count);
int s= Integer.parseInt(Detailpage.item.getText().toString());
itemname.setText(Integer.toString(count1));
// viewHolder.txtView.setText(Integer.toString(count1)+"items");
count1=s+1;
Detailpage.item.setText(Integer.toString(count1));
int foodprice=0;
foodprice=Integer.parseInt(child.getPrice());
total1=child.getPrice();
value=Integer.toString(modelChild.getcount());
//
name = modelChild.getName();
id=child.getId();
new AsyncT().execute(user_id,res_id,id,name,total1,value);
groups.get(groupPosition).getItems().set(childPosition, modelChild);
notifyDataSetChanged();
}
}});
viewHolder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(modelChild.getCount()>0) // set your count default 0 when you bind data initially
{ int count = modelChild.getCount() - 1;
modelChild.setCount(count);
int s= Integer.parseInt(Detailpage.item.getText().toString());
count1=s-1;
Detailpage.item.setText(Integer.toString(count1));
name=modelChild.getName();
//
int foodprice=0;
foodprice=Integer.parseInt(child.getPrice());
int total = foodprice * child.getcount();
total1=child.getPrice();
// total1=Integer.toString(total);
value=Integer.toString(count);
id=child.getId();
if(count>0) {
new AsyncT().execute(user_id, res_id, id, name, total1, value);
}
}
modelChild.setChildName(modelChild.getChildName());
// set your other items if any like above
groups.get(groupPosition).getItems().set(childPosition, modelChild);
notifyDataSetChanged();
}
});
return convertView;
}
Movie1 model(checkin page):`
public class Movie1 {
public String food_id,food_count,food_item,food_price,food_resid,food_totalprice;
public void setfood_id(String food_id) {
this.food_id = food_id;
}
public void setfood_count(String food_count) {
this.food_count = food_count;
}
public void setfood_price(String food_price) {
this.food_price = food_price;
}
public void setfood_item(String food_item) {
this.food_item = food_item;
}
public String getfood_item() {
return food_item;
}
public String getfood_count() {
return food_count;
}
public String getfood_price() {
return food_price;
}
public void setfood_resid(String food_resid) {
this.food_resid = food_resid;
}
public String getfood_resid() {
return food_resid;
}
public String getfood_id() {
return food_id;
}
public void setfood_totalprice(String food_totalprice) {
this.food_totalprice = food_totalprice;
}
public String getfood_totalprice() {
return food_totalprice;
}
}
`
Child model:(Expandable listview)
public class Child {
private String Name,childName,item_status,image1,available_from,available_to,price,id,status;
private int Image,count;
public Object getstatus;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getImage() {
return Image;
}
public void setImage(int Image) {
this.Image = Image;
}
public void setcount(int count) {
this.count = count;
}
public int getcount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getChildName() {
return childName;
}
public int getCount() {
return count;
}
public void setChildName(String childName) {
this.childName = childName;
}
public void setItem_status(String item_status) {
this.item_status = item_status;
}
public void setImage1(String image1) {
this.image1 = image1;
}
public void setAvailable_to(String available_to) {
this.available_to = available_to;
}
public void setAvailable_from(String available_from) {
this.available_from = available_from;
}
public void setPrice(String price) {
this.price = price;
}
public void setId(String id) {
this.id = id;
}
public String getPrice() {
return price;
}
public String getImage1() {
return image1;
}
public String getItem_status() {
return item_status;
}
public String getId() {
return id;
}
public void setstatus(String status) {
this.status = status;
}
public String getstatus() {
return status;
}
}
`checkin
Expandablelist adapter
I am working on a screen where i am populating a list view using base adapter.Each row of list view contains a circular image view,Text View and Check box .On clicking single tick on toolbar ,i am displaying the id of user corresponding to checked button But it is displayed wrongly.I am implementing the following screen:
1.Bean_Friends
public class Bean_Friends {
private String name, url, extension, friendsID;
private String friendSelected = "false";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFriendsID() {
return friendsID;
}
public void setFriendsID(String friendsID) {
this.friendsID = friendsID;
}
public String getFriendSelected() {
return friendSelected;
}
public void setFriendSelected(String friendSelected) {
this.friendSelected = friendSelected;
}
}
2.Adapter_Friends_Group.java
public class Adapter_Friends_Group extends BaseAdapter {
private Context context;
public List<Bean_Friends> listBeanFriends;
private LayoutInflater inflater;
private ApiConfiguration apiConfiguration;
private Bean_Friends bean_friends;
public Adapter_Friends_Group(Context context, List<Bean_Friends> listBeanFriends) {
this.context = context;
this.listBeanFriends = listBeanFriends;
}
#Override
public int getCount() {
return listBeanFriends.size();
}
#Override
public Object getItem(int i) {
return listBeanFriends.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (view == null) {
view = inflater.inflate(R.layout.feed_item_friends, null);
}
//finding different views
ImageView pic = (ImageView) view.findViewById(R.id.friendsImage);
TextView txtName = (TextView) view.findViewById(R.id.nameFriends);
CheckBox chkFriends = (CheckBox) view.findViewById(R.id.chkFriends);
bean_friends = listBeanFriends.get(i);
String name = bean_friends.getName();
String url = bean_friends.getUrl();
String extension = bean_friends.getExtension();
apiConfiguration = new ApiConfiguration();
String api = apiConfiguration.getApi();
String absolute_url = api + "/" + url + "." + extension;
//loading image into ImageView iew
Picasso.with(context).load(absolute_url).error(R.drawable.default_avatar).into(pic);
//Setting name in the textview
txtName.setText(name);
//If check box is checked,then add true to bean else add false to bean
if (chkFriends.isChecked()) {
bean_friends.setFriendSelected("true");
} else {
bean_friends.setFriendSelected("false");
}
chkFriends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
if (cb.isChecked()) {
bean_friends.setFriendSelected("true");
Toast.makeText(context, "Check Box is checked : " + cb.isChecked(), Toast.LENGTH_SHORT).show();
} else {
bean_friends.setFriendSelected("false");
}
}
});
return view;
}
}
3. Code of Activity containing view
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_new_group, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.createGroup:
createNewGroup();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void createNewGroup() {
Toast.makeText(NewGroupActivity.this, "clicked", Toast.LENGTH_SHORT).show();
List<Bean_Friends> listBeanFriends = new ArrayList<>();
//Log.e("Size of listbeanFriends", String.valueOf(listBeanFriends.size()));
listBeanFriends = adapter_friends_group.listBeanFriends;
// Log.e("Size of adapter_friends", String.valueOf(adapter_friends_group.listBeanFriends.size()));
Log.e("Size of listbeanFriends", String.valueOf(listBeanFriends.size()));
for (int i = 0; i < listBeanFriends.size(); i++) {
Log.e("Loop Working", String.valueOf(i));
Bean_Friends bean_friends = listBeanFriends.get(i);
String friendID = bean_friends.getFriendsID();
String friendSelected = bean_friends.getFriendSelected();
String friendName = bean_friends.getName();
Log.e("FriendsName", friendName);
Log.e("FriendID", friendID);
Log.e("friendSelected", friendSelected);
if (friendSelected.equals("true")) {
Toast.makeText(NewGroupActivity.this, friendID, Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(NewGroupActivity.this,"true",Toast.LENGTH_SHORT).show();
}
}
}
Updated code:
Solved the issue after doing the following changes:
Adapter
public class Adapter_Friends_Group extends BaseAdapter {
private Context context;
public List<Bean_Friends> listBeanFriends;
private LayoutInflater inflater;
private ApiConfiguration apiConfiguration;
private Bean_Friends bean_friends;
public Adapter_Friends_Group(Context context, List<Bean_Friends> listBeanFriends) {
this.context = context;
this.listBeanFriends = listBeanFriends;
}
private class ViewHolder {
ImageView imageView;
TextView txtName;
CheckBox chkFriend;
}
#Override
public int getCount() {
return listBeanFriends.size();
}
#Override
public Object getItem(int i) {
return listBeanFriends.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (inflater == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (view == null) {
view = inflater.inflate(R.layout.feed_item_friends, null);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) view.findViewById(R.id.friendsImage);
viewHolder.txtName = (TextView) view.findViewById(R.id.nameFriends);
viewHolder.chkFriend = (CheckBox) view.findViewById(R.id.chkFriends);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
bean_friends = listBeanFriends.get(i);
String name = bean_friends.getName();
String url = bean_friends.getUrl();
String extension = bean_friends.getExtension();
apiConfiguration = new ApiConfiguration();
String api = apiConfiguration.getApi();
String absolute_url = api + "/" + url + "." + extension;
//loading image into ImageView iew
Picasso.with(context).load(absolute_url).error(R.drawable.default_avatar).into(viewHolder.imageView);
//Setting name in the textview
viewHolder.txtName.setText(name);
//Setting boolean isSelected if the Checkbox is checked
viewHolder.chkFriend.setChecked(bean_friends.isSelected());
viewHolder.chkFriend.setTag(bean_friends);
viewHolder.chkFriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Bean_Friends bean_friends = (Bean_Friends) cb.getTag();
Toast.makeText(context, "Clicked on Checkbox: " + bean_friends.getName() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
bean_friends.setIsSelected(cb.isChecked());
}
});
return view;
}
}
Bean
public class Bean_Friends {
private String name, url, extension, friendsID;
boolean isSelected;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFriendsID() {
return friendsID;
}
public void setFriendsID(String friendsID) {
this.friendsID = friendsID;
}
public boolean isSelected() {
return isSelected;
}
public void setIsSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
Method inside Activity
public void createNewGroup() {
StringBuffer responseText = new StringBuffer();
listBeanFriends = adapter_friends_group.listBeanFriends;
// Log.e("Size of adapter_friends", String.valueOf(adapter_friends_group.listBeanFriends.size()));
Log.e("Size of listbeanFriends", String.valueOf(listBeanFriends.size()));
for (int i = 0; i < listBeanFriends.size(); i++) {
Log.e("Loop Working", String.valueOf(i));
Bean_Friends bean_friends = listBeanFriends.get(i);
String friendID = bean_friends.getFriendsID();
String friendName = bean_friends.getName();
Log.e("FriendsName", friendName);
Log.e("FriendID", friendID);
Log.e("FriendSelected", String.valueOf(bean_friends.isSelected()));
if (bean_friends.isSelected()) {
responseText.append("\n" + bean_friends.getName() + " " + bean_friends.getFriendsID());
}
}
Toast.makeText(NewGroupActivity.this, responseText, Toast.LENGTH_SHORT).show();
}
I think the mistake is in this line :-
//If check box is checked,then add true to bean else add false to bean
if (chkFriends.isChecked()) {
bean_friends.setFriendSelected("true");
} else {
bean_friends.setFriendSelected("false");
}
Here you are setting 'setFriendSelected' based on whether the chkFriends is checked or not. In list View the views are reused and if say you have checked 'A' as friend and then you scrolls down then the view of 'A' maybe reused in 'C' and by this code 'C' now will be checked as friend. Here you instead want to inflate your checkBox view according to whether 'C' is your friend or not. Try this instead:-
//If check box is checked,then add true to bean else add false to bean
if (bean_friends.getFriendSelected().equals("true")) {
chkFriends.setChecked(true);
} else {
chkFriends.setChecked(false);
}
P.S : you can use view holder pattern here for better performance.
I have an issue in RecycleView. My screen has two tabs, both tabs contain recycleview.It call normally most of the time but sometimes give empty screen. Just I wrote log & system.out and found this issue. I will paste my adapter class code here.
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
List<ContentTitle> titles;
Context context;
private List<Item> titleData = new ArrayList<Item>();
public ExpandableListAdapter(List<Item> data) {
this.titleData = data;
System.out.println("===this.titleData===" + this.titleData.size());
}
public void replaceContentFragment(String title,int id,int bookmarked) {
try {
SkillsApp SkillsApp = (SkillsApp) context.getApplicationContext();
Fragment fragment = new ContentActivityFragment();
FragmentManager fragmentManager = skillsUSAApp.mainActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
SkillsApp.subtitleID = id;
SkillsApp.isbookmark = (bookmarked == 0)? false:true;
SkillsApp.mainActivity.getSupportActionBar().setTitle(title);
SkillsApp.selectedSubtitleID = id;
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
try{
context = parent.getContext();
final SkillsApp skillsApp = (SkillsAApp)context.getApplicationContext();
if(!skillsApp.isDrawer){
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.main_title, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
LayoutInflater inflater1 = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater1.inflate(R.layout.sub_title, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Child", "child");
TextView text = (TextView) view.findViewById(R.id.header_title);
}
});
return new RecyclerView.ViewHolder(view) {
};
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try{
System.out.println("==========##########");
final Item item = titleData.get(position);
final SkillsAApp skillsAApp = (SkillsAApp)context.getApplicationContext();
System.out.println("===onBindViewHolder item===" + item.mainTitle.title);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.mainTitle.title);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
}
itemController.layoutItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(!skillsAApp.isDrawer){
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = titleData.indexOf(itemController.refferalItem);
while (titleData.size() > pos + 1 && titleData.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(titleData.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
int pos = titleData.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
titleData.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.down_arrow);
item.invisibleChildren = null;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
case CHILD:
View itemTextView = (View) holder.itemView;
TextView view = (TextView) itemTextView.findViewById(R.id.header_title);
view.setText(titleData.get(position).subtitle.title);
final int pos = position;
itemTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(!skillsUSAApp.isDrawer){
TextView text = (TextView) view.findViewById(R.id.header_title);
FlurryAgent.logEvent("Sub Category Item");
replaceContentFragment(text.getText().toString(), titleData.get(pos).subtitle.subtitleId, titleData.get(pos).subtitle.bookMarked);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public int getItemViewType(int position) {
return titleData.get(position).type;
}
#Override
public int getItemCount() {
return titleData.size();
}
#Override
public long getItemId(int position) {
return position;
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public RelativeLayout layoutItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
try{
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
layoutItem = (RelativeLayout) itemView.findViewById(R.id.ll_title);
}catch (Exception e){
e.printStackTrace();
}
}
}
public static class Item {
public int type;
public String text;
public ContentTitle mainTitle;
public ContentSubTitle subtitle;
public List<Item> invisibleChildren;
public Item(int type, String text, List<Item> children) {
this.type = type;
this.text = text;
this.invisibleChildren = children;
}
public Item(int type, ContentTitle title,ContentSubTitle stitle) {
this.type = type;
this.mainTitle = title;
this.subtitle=stitle;
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
Here is a calling adapter from tab fragment
recyclerview = (RecyclerView) v.findViewById(R.id.recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext(), LinearLayoutManager.VERTICAL, false));
// recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext()));
ExpandableListAdapter adapter = new ExpandableListAdapter(items);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
could you please advice me what is an issue? I didn't get any console error message.Could you please help me anyone here