Custom adapter returning wrong row Textview Text - android

I am implementing a custom adapter for listview. In which i have some textview and one checkbox.for checkbox i have implemented setOnCheckedChangeListener.But the problem is when i check a checkbox i am trying to get that row textview text. but it returning last row textview text.
Code
public class CustomStoreAdapter extends BaseAdapter implements Filterable {
ItemFilter mFilter;
int price;
private int lastPosition = -1;
ViewHolder mHolder;
ArrayList<String> favHotel;
private static SparseBooleanArray positionArray=new SparseBooleanArray();
SharedPreferences sharedPreferences;
public static ArrayList<HashMap<String,String>> finalHashList;
public static ArrayList<HashMap<String,String>> tempName;
public static ArrayList<Integer> selectedIds = new ArrayList<Integer>();
Context context;
String flag;
String favId;
ArrayList<String> htlId;
String [] favArr;
public CustomStoreAdapter(String flag, Context context, ArrayList<HashMap<String, String>> finalHashList, String favId) {
System.out.println("custom size>>"+finalHashList.size());
this.context = context;
CustomStoreAdapter.finalHashList =finalHashList;
for (int i=0;i<finalHashList.size();i++) {
htlId.add(finalHashList.get(i).get("id"));
}
tempName=finalHashList;
selectedIds=new ArrayList<>();
this.flag=flag;
this.favId=favId;
if (!favId.equals(""))
{
favId=favId.substring(6,favId.length());
//Log.e("substring favId",favId);
favArr=favId.split(",");
}
Log.e("flag is>>>",flag);
}
#Override
public int getCount() {
return finalHashList.size();
}
#Override
public Object getItem(int position) {
return finalHashList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public static void append( ArrayList<HashMap<String, String>> finalHashList1) {
}
public static StringBuilder getCheckedItems() {
StringBuilder mTempArry = new StringBuilder();
mTempArry.append("htlid=");
for(int i=0;i<finalHashList.size();i++) {
if(positionArray.get(i)) {
mTempArry.append(finalHashList.get(i).get("id"));
mTempArry.append(",");
}
}
return mTempArry;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
favHotel=new ArrayList<>();
View v = convertView;
sharedPreferences = context.getSharedPreferences("hotelDekho", Context.MODE_PRIVATE);
if(finalHashList.size() > position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TypefaceUtil.overrideFont(context.getApplicationContext(), "SERIF", "fonts/splash-font.ttf");
if (v == null) {
v = inflater.inflate(R.layout.serch_result_page, parent, false);
mHolder = new ViewHolder();
mHolder.txtId=(TextView)v.findViewById(R.id.txtId);
mHolder.txthotelRating = (TextView) v.findViewById(R.id.txtRating);
mHolder.txthotelName = (TextView)v.findViewById(R.id.Hotel_name);
mHolder.txtFavorite=(CheckBox) v.findViewById(R.id.imgFavorite);
mHolder.txthotelLocation = (TextView) v.findViewById(R.id.Hotel_location);
mHolder.txthotelPrice = (TextView) v.findViewById(R.id.price);
mHolder.txthotelPrice2 = (TextView) v.findViewById(R.id.price2);
mHolder.txthotelIconPlace = (TextView)v.findViewById(R.id.locIcon);
mHolder.txtLock = (TextView)v.findViewById(R.id.txtLock);
mHolder.txthotelIconR1 = (TextView) v.findViewById(R.id.txtR1);
mHolder.txthotelIconR2 = (TextView) v.findViewById(R.id.txtR2);
mHolder.rhotelRating = (CustomRatingBar) v.findViewById(R.id.ratingBar1);
mHolder.lnrPrice=(LinearLayout)v.findViewById(R.id.lnrPrice);
mHolder.imgHotel = (ImageView) v.findViewById(R.id.hotel_image);
mHolder.lnrRating=(LinearLayout)v.findViewById(R.id.lnrRating);
mHolder.lnrSignHotelList=(LinearLayout)v.findViewById(R.id.lnrSignHotelList);
mHolder.txthotelIconPlace.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder.txthotelIconR1.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder. txthotelIconR2.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder.txtLock.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder.txtFavorite.setTag(position);
v.setTag(mHolder);
}else
{
mHolder = (ViewHolder) v.getTag();
mHolder.txtFavorite.setOnCheckedChangeListener(null);
}
Animation animation = AnimationUtils.loadAnimation(context, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
v.startAnimation(animation);
lastPosition = position;
mHolder.txtId.setText(finalHashList.get(position).get("id"));
mHolder.txthotelName.setText(finalHashList.get(position).get("name"));
mHolder.txthotelLocation.setText(finalHashList.get(position).get("location"));
mHolder.txthotelRating.setText(finalHashList.get(position).get("rating") + "/5");
// mHolder.txtFavorite.setChecked(positionArray.get(position));
mHolder.txtFavorite.setChecked(positionArray.get(position));
for (int i=0;i<favArr.length;i++)
{
if(favArr[i].equals(finalHashList.get(position).get("id")))
{
mHolder.txtFavorite.setChecked(true);
}
}
mHolder.txtFavorite.setOnCheckedChangeListener(mCheckedChangeListener);
if (!flag.equals("favHtl")) {
mHolder.lnrPrice.setVisibility(View.VISIBLE);
Float price1 = Float.parseFloat(finalHashList.get(position).get("price"));
mHolder.txthotelPrice2.setText(String.valueOf(Math.round(price1)));
if (SearchHotelResults.flag.equals("offer")) {
price = Math.round(price1 + price1);
} else
price = Math.round(price1 + ((price1 * 20) / 100));
mHolder.txthotelPrice.setText(String.valueOf(price));
mHolder.txthotelPrice.setPaintFlags(mHolder.txthotelPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
mHolder.rhotelRating.refreshDrawableState();
if (!sharedPreferences.getString("email","").equals(""))
{
mHolder.lnrSignHotelList.setVisibility(View.GONE);
}
mHolder.rhotelRating.setScore(Float.parseFloat(finalHashList.get(position).get("star")));
if (finalHashList.get(position).get("img").startsWith("hoteldekho")) {
loadImagePicaso( mHolder.imgHotel, Config.storeImagePath + finalHashList.get(position).get("img"));
} else {
loadImagePicaso( mHolder.imgHotel, finalHashList.get(position).get("img"));
}
}
return v;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Animation zoomOutAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
buttonView.startAnimation(zoomOutAnimation);
positionArray.put(htlId.indexOf(mHolder.txtFavorite.getText().toString()), isChecked);
Log.e("array is>>",getCheckedItems().toString()+">>>>"+ finalHashList.indexOf(mHolder.txtId.getText().toString()));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("favHotelId", getCheckedItems().toString());
editor.apply();
}
};
private class ViewHolder {
private TextView txtId;
private TextView txthotelRating;
private TextView txthotelName;
private TextView txthotelLocation;
private TextView txthotelPrice;
private TextView txthotelPrice2;
private TextView txthotelIconPlace;
private TextView txtLock;
private CheckBox txtFavorite;
LinearLayout lnrPrice;
private TextView txthotelIconR1;
private TextView txthotelIconR2;
private TextView txthotelIconArrow;
private CustomRatingBar rhotelRating;
private ImageView imgHotel;
private Button btnSubmit;
private LinearLayout lnrRating;
private LinearLayout lnrSignHotelList;
}
}
Please help me to how to get same row textview text on checkbox click

Problem:
Currently you're storing your ViewHolder in a class level field, which is being set in getView(), its going to be set to the latest ViewHolder every time ListView is calling getView() and there's absolutely no guarantee in the order of the position the getView() is called for. Its going to get random ViewHolder references, creating problems for you to track position So a class level ViewHolder isn't good solution.
Solution:
You need to keep track of position related to every check box. Tag the position to checkbox and get it in the listener as follow:
mHolder.txtFavorite.setOnCheckedChangeListener(mCheckedChangeListener);
mHolder.txtFavorite.setTag(position+""); //tag position as String object
Now you can get this position in your listener:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Since we set position in form of String, we need to convert String to int
int position = Integer.parseInt(buttonView.getTag());
}

You save position of mHolder.txtFavorite to tag, so you should just read the right position from tag, not from text
positionArray.put(htlId.indexOf(mHolder.txtFavorite.getTag()), isChecked);

Related

How to modify only one row at a time while using Customized ListView

I have used Customized ListView And not ExtendedListView. i have taken relative layout in order to show it as sub_list. By default i have set the visibilty of this sub_list relative layout as GONE. And on the click of any listItem that relative layout(by default set as gone) will appear on the screen respectively. But When I click on any of the rows the sub_list appear for each row simultaneously. What i want is that it should be shown only for one row at a time. I have already checked this similar [question]: How to modify only one row at a time in Listview? and modified my code but still i am unable to achieve my goal.
Here is my pieace of code:
public class CustomAdapter extends BaseAdapter {
Activity context;
ArrayList<String> s_date,c_number,d_ration,s_time,download_path,a_number,a_name,dt_number;
int flag=0,temp=1,position;
String mUrl;
int posview;
private int selectedIndex;
CustomAdapter(Activity context, ArrayList<String> start_date, ArrayList<String> caller_number, ArrayList<String> duration,ArrayList<String> start_time, ArrayList<String> download_path, ArrayList<String> agent_number, ArrayList<String> agent_name,ArrayList<String> dt_num)
{
this.context=context;
this.s_date=start_date;
this.c_number=caller_number;
this.d_ration=duration;
this.s_time=start_time;
this.download_path=download_path;
this.a_number=agent_number;
this.a_name=agent_name;
this.dt_number=dt_num;
selectedIndex = -1;
}
public void setSelectedIndex(int ind)
{
selectedIndex = ind;
notifyDataSetChanged();
}
#Override
public int getCount() {
return s_date.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int pos, final View v, ViewGroup g)
{
//LayoutInflater l=context.getLayoutInflater();
//View rowView=l.inflate(R.layout.log_layout,null,true);
posview=pos;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row = inflater.inflate(R.layout.list_item, g, false);
TextView start_date = (TextView) row.findViewById(R.id.start_date);
start_date.setText(s_date.get(pos));
TextView caller_number = (TextView) row.findViewById(R.id.caller_number);
caller_number.setText(c_number.get(pos));
TextView duration = (TextView) row.findViewById(R.id.duration);
duration.setText(d_ration.get(pos));
TextView start_time = (TextView) row.findViewById(R.id.start_time);
start_time.setText(s_time.get(pos));
TextView agent_name = (TextView) row.findViewById(R.id.agent_name);
agent_name.setText(a_name.get(pos));
TextView agent_number = (TextView) row.findViewById(R.id.agent_number);
agent_number.setText(a_number.get(pos));
TextView dt_numb=(TextView)row.findViewById(R.id.dt_number);
dt_numb.setText("MHL No. -"+dt_number.get(pos));
RelativeLayout r = (RelativeLayout)row.findViewById(R.id.sub_layout);
r.setVisibility(position == posview ? View.VISIBLE : View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
posview=pos;
notifyDataSetChanged();
}
});
return row;
}
}
Previously my code was:
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setSelectedIndex(view.getId());
RelativeLayout sub_list = (RelativeLayout) row.findViewById(R.id.sub_layout);
sub_list.setVisibility(View.VISIBLE);
//notifyDataSetChanged();
}
});
I am getting all the data dynamically. This is how i'm using the adapter in MainActivity:
CustomAdapter a=new CustomAdapter(MainScreen.this,start_date,caller_number,duration,start_time,download_path,agent_number,agent_name,dt_number);
data_list.setAdapter(a);
In this start_date caller_number etc are arraylist.This is how i'm parsing data in MainActivity.
JSONObject responseObject = new JSONObject(response);
JSONObject callLog = responseObject.getJSONObject("call_log");
Iterator<String> phoneNumbers = callLog.keys();
while (phoneNumbers.hasNext()) {
String number = phoneNumbers.next();
// Log.v("string number",number);
JSONObject numberLog = callLog.getJSONObject(number);
Iterator<String> callEntries = numberLog.keys();
while (callEntries.hasNext()) {
String entry = callEntries.next();
//Log.v("unique keys are",entry);
JSONObject entryObject = numberLog.getJSONObject(entry);
jsonArray.put(entryObject.getString("start_date"));
jsonArray.put(entryObject.getString("start_time"));
jsonArray.put(entryObject.getString("end_date"));
jsonArray.put(entryObject.getString("end_time"));
jsonArray.put(entryObject.getString("recording_path"));
String startDate = entryObject.getString("start_date");
start_date.add(startDate);
String startTime = entryObject.getString("start_time");
start_time.add(startTime);
String endDate = entryObject.getString("end_date");
String endTime = entryObject.getString("end_time");
String call_sdate = entryObject.getString("call_sdate");
String call_edate = entryObject.getString("call_edate");
String call_type = entryObject.getString("call_type");
String caller = entryObject.getString("caller");
caller_number.add(caller);
String duartion = entryObject.getString("duartion");
String call_duartion = entryObject.getString("call_duartion");
duration.add(call_duartion);
String dtmf = entryObject.getString("dtmf");
String dt_num = entryObject.getString("dt_number");
dt_number.add((dt_num));
String recording_path = entryObject.getString("recording_path");
download_path.add(recording_path);
String agent_mobile = entryObject.getString("agent_mobile");
agent_number.add(agent_mobile);
String a_name = entryObject.getString("agent_name");
agent_name.add(a_name);
Create two variables :
Map<Integer, View> lastExpanded = new HashMap<>();
int lastExpandedPosition =-1;
Create a function in your adapter :
private void expand(int i, View layout){
if(!lastExpanded.containsKey(i)){
layout.setVisibility(View.VISIBLE);
lastExpanded.put(i, layout);
if(lastExpanded.containsKey(lastExpandedPosition)){
expand(lastExpandedPosition, lastExpanded.get(lastExpandedPosition));
}
lastExpanded.remove(lastExpandedPosition);
lastExpandedPosition = i;
lastExpanded.put(lastExpandedPosition, layout);
}else{
layout.setVisibility(View.GONE);
lastExpandedPosition = -1;
lastExpanded.remove(i);
}
}
now,
final RelativeLayout layout = (RelativeLayout) row.findViewById(R.id.b);
layout.setVisibility(View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expand(i, layout);
}
});
You can acheive this easily with expandable listview and your adapter class should extend BaseExpandableListAdapter
in activity
private int lastExpandedPosition = -1;
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
final int groupPosition, long id) {
// TODO Auto-generated method stub
if (parent.isGroupExpanded(groupPosition)) {
expListView
.collapseGroup(lastExpandedPosition);
} else {
expListView.expandGroup(groupPosition);
}
return true;
}
});
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
// TODO Auto-generated method stub
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
expListView
.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
You have to use ArrayList which contents as your data while you click on the item.
public class DataModel{
private String s_date,c_number,d_ration,s_time,download_path,a_number,a_name,dt_number;
private boolean isChildVisible;
..... create it's setter and getter methods.
}
when itemclick is called that time you should update the flag of isChildVisible for that position.
public void setSelectedIndex(int ind)
{
arrayListDataModel.get(ind).setIsChildVisible(true);
notifyDataSetChanged();
}
In your getview method :
public View getView(final int pos, final View v, ViewGroup g)
{
----your initialization code.
RelativeLayout r = (RelativeLayout)row.findViewById(R.id.sub_layout);
r.setVisibility(arrayListDataModel.get(pos).isChildVisible() ? View.VISIBLE : View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setSelectedIndex(pos);
}
});
return row;
}
parse the data with below code :
final ArrayList<DataModel> dataModelList = new ArrayList<>();
while (callEntries.hasNext()) {
DataModel dataModel = new DataModel();
String entry = callEntries.next();
//Log.v("unique keys are",entry);
JSONObject entryObject = numberLog.getJSONObject(entry);
jsonArray.put(entryObject.getString("start_date"));
jsonArray.put(entryObject.getString("start_time"));
jsonArray.put(entryObject.getString("end_date"));
jsonArray.put(entryObject.getString("end_time"));
jsonArray.put(entryObject.getString("recording_path"));
String startDate = entryObject.getString("start_date");
dataModel.setStartDate(startDate);
String startTime = entryObject.getString("start_time");
dataModel.setStartTime(startTime);
...... same as above for others fields
dataModelList.add(dataModel);
}

TabHost onTabChangeListener - Setting up listview adapter

I'm trying to change a few parts in my app. I can't figure out how to set up my app so each tab changes the data in my listview. Any help appreciated.
My tab setup class:
public class WorkoutDaysActivity extends BaseActivity {
ListView mListView = new ListView(this);
ArrayList < CustomObject > w29w1m;
CustomListViewAdapter mCustomListViewAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_days);
mToolBar = activateToolbar();
setUpNavigationDrawer();
w29w1m.add(new CustomObject("Squat", "65%", "6", "150", false));
final ArrayList < CustomObject > w29w1w = new ArrayList < CustomObject > ();
w29w1w.add(new CustomObject("Dead", "65%", "6", "150", false));
final ArrayList < CustomObject > w29w1f = new ArrayList < CustomObject > ();
w29w1f.add(new CustomObject("Bench", "65%", "6", "150", false));
TabHost tabHost = (TabHost) findViewById(R.id.TabHost1);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("1").setIndicator("Monday").setContent(objects));
tabHost.addTab(tabHost.newTabSpec("1").setIndicator("Wednesday").setContent(objects));
tabHost.addTab(tabHost.newTabSpec("1").setIndicator("Friday").setContent(objects));
}
private TabHost.OnTabChangeListener mOnTabChangeListener = new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (tabId.equalsIgnoreCase("1"))
mListView.setAdapter(mCustomListViewAdapter, w29w1m);
}
};
private final TabHost.TabContentFactory objects = new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
return mListView;
}
};
}
customObject class:
public class CustomObject implements Serializable {
private String exercise;
private String percent;
private String reps;
private String weight;
private boolean check1;
public CustomObject(String exercise, String percent, String reps, String weight, boolean check1) {
this.exercise = exercise;
this.percent = percent;
this.reps = reps;
this.weight = weight;
this.check1 = check1;
}
public String getExercise() {
return exercise;
}
public String getPercent() {
return percent;
}
public String getReps() {
return reps;
}
public String getWeight() {
return weight;
}
Adapter class
public class CustomListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ArrayList < CustomObject > objects;
boolean[] checkBoxState;
private CustomObject[] dataToBePopulated;
private class ViewHolder {
TextView txtExercise;
TextView txtPercent;
TextView txtReps;
TextView txtWeight;
CheckBox check1;
}
public void addAdapterItem(CustomObject item) {
objects.add(item);
}
public CustomListViewAdapter(Context context, ArrayList < CustomObject > objects){
inflater = LayoutInflater.from(context);
this.objects = objects;
checkBoxState = new boolean[objects.size()];
}
public int getCount() {
return dataToBePopulated != null ? dataToBePopulated.length : 0;
}
public CustomObject getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.workout_item, null);
holder.txtExercise = (TextView) convertView.findViewById(R.id.txtExercise);
holder.txtPercent = (TextView) convertView.findViewById(R.id.txtPercentage);
holder.txtReps = (TextView) convertView.findViewById(R.id.txtReps);
holder.txtWeight = (TextView) convertView.findViewById(R.id.txtWeight);
holder.check1 = (CheckBox) convertView.findViewById(R.id.check1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtExercise.setText(objects.get(position).getExercise());
holder.txtPercent.setText(objects.get(position).getPercent());
holder.txtReps.setText(objects.get(position).getReps());
holder.txtWeight.setText(objects.get(position).getWeight());
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
}
});
return convertView;
}
}
The problem is I don't know how to set up my adapter to show the custom array lists Im making (w29w1m for example). Any help greatly appreciated! thanks!
If you're just going to change the data inside the adapter, try changing the list that you've set on the adapter. Then call notifyDataSetChanged() on the adapter. For example, if you've instantiated the adapter like LVAdapter lvAdapter = new LVAdapter(context, list); (or whatever parameter you use in your adapter), just change list to what you want the ListView to contain, then call lvAdapter.notifyDataSetChanged();.
But if you'd also change the adapter, try to set another adapter to the listview every time the tab is changed.
Also, I suggest making the tabSpec ids unique for each one.

how to maintain inflated radio button state in listView

So I have a listView that I'm populating with a static xml, but inside that xml I have a dynamic container that I inflate items into when the user clicks on an item in the listView.
Basically the view(s) I'm inflating looks like (x) amount of radio buttons and a textView.
The reason I have to do it this way is that the amount of radio buttons inflated could change depending on what type of list item it is.
The issue I'm running into is that once the radio buttons are inflated and the user selects a button, the list doesn't save the state from which the user last selected the radio button. Or rather, it recycles the radio button state to another position in the list. Which is somewhat correct since that's what listview does. I want it to only save the user selected answer at the position they selected in the listView.
I've been working on this for about a week and can't find a good solution. If anyone would like to help I'd greatly appreciate it. I'll post the relevant code below.
SurveyView (Custom container to inflate views into)
public class SurveyView extends LinearLayout {
private LinearLayout pollContainer;
private Context context;
private String type;
private int numOfAnswers;
private ListView answersList;
private ArrayList<String> answers;
private boolean visibility = true;
private OnClickListener listener;
private ArrayList<View> options;
private static int tag = 88888888;
private ArrayList<Boolean> checked;
private Integer[] percent = {33, 25, 15, 20, 7};
private int position;
/**
* #param context the context of the activity
* #param type the type of poll
* #param numOfAnswers if the poll is multiple choice (most likely) provide number of answers.
*/
public void setLayout(final Context context, String type, int numOfAnswers, final int position) {
this.type = type;
this.numOfAnswers = numOfAnswers;
this.context = context;
this.position = position;
switch (type) {
case "Multiple":
if (visibility) {
for (int i = 0; i < numOfAnswers; i++) {
View v = LayoutInflater.from(getContext()).inflate(R.layout.poll_multiple_choice_answers_row, null);
View space = LayoutInflater.from(getContext()).inflate(R.layout.space, null);
v.setTag(tag);
options.add(v);
final RadioButton rb = (RadioButton) v.findViewById(R.id.answer_voted_button);
rb.setClickable(false);
rb.setFocusable(false);
tag++;
addView(v);
addView(space);
}
}
break;
case "Slider":
break;
case "Tree":
break;
case "Sentiment":
break;
}
}
public SurveyView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
options = new ArrayList<>();
}
public boolean isVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
public void setAnswers(int position) {
RadioButton rb;
for (int i = 0; i < options.size(); i++) {
if (i != position) {
rb = (RadioButton) options.get(i).findViewById(R.id.answer_voted_button);
rb.setChecked(false);
}
else {
rb = (RadioButton) options.get(position).findViewById(R.id.answer_voted_button);
rb.setChecked(true);
for (int p = 0; p < options.size(); p++) {
TextView answer = (TextView) options.get(p).findViewById(R.id.poll_answer);
answer.setText("Abraham Lincoln");
TextView tv = (TextView) options.get(p).findViewById(R.id.answer_percent);
tv.setText(Integer.toString(percent[p]));
options.get(p).setBackground(new PercentDrawable(percent[p], context.getResources().getColor(R.color.icitizen_poll_opaque_gold)));
}
}
}
}
Adapter for the listview
PollsAdapter extends BaseAdapter {
private LayoutInflater inflater;
private Context context;
private ArrayList<Card> data;
private ArrayList<RelativeLayout.LayoutParams> params;
private ArrayList<Integer> pollAnswers;
private int selectedPosition = 0;
public PollsAdapter(Context context, ArrayList<Card> data,
ArrayList<RelativeLayout.LayoutParams> params,
ArrayList<Integer> pollAnswers) {
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
this.params = params;
this.pollAnswers = pollAnswers;
}
public static class ViewHolder {
TextView type;
TextView time;
TextView text;
TextView space;
TextView pollSpace;
ImageView type_icon;
SurveyView answerView;
RadioButton rb;
ArrayList<View> options;
private ViewHolder() {
}
private ViewHolder(TextView type, TextView time, TextView text, ImageView type_icon, SurveyView answerView) {
this.type = type;
this.time = time;
this.text = text;
this.type_icon = type_icon;
this.answerView = answerView;
}
public TextView getType() {
return type;
}
public void setType(TextView type) {
this.type = type;
}
public TextView getTime() {
return time;
}
public void setTime(TextView time) {
this.time = time;
}
public TextView getText() {
return text;
}
public void setText(TextView text) {
this.text = text;
}
public ImageView getType_icon() {
return type_icon;
}
public void setType_icon(ImageView type_icon) {
this.type_icon = type_icon;
}
public SurveyView getAnswerView() {
return answerView;
}
public void setAnswerView(SurveyView answerView) {
this.answerView = answerView;
}
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.polls_card_layout, null);
viewHolder.type = (TextView)convertView.findViewById(R.id.card_type);
viewHolder.time = (TextView)convertView.findViewById(R.id.card_poll_time);
viewHolder.text = (TextView)convertView.findViewById(R.id.card_text);
viewHolder.space = (TextView)convertView.findViewById(R.id.card_space);
viewHolder.pollSpace = (TextView)convertView.findViewById(R.id.poll_space);
viewHolder.type_icon = (ImageView)convertView.findViewById(R.id.card_icon);
viewHolder.answerView = (SurveyView)convertView.findViewById(R.id.poll_component);
viewHolder.rb = (RadioButton)viewHolder.answerView.findViewById(R.id.answer_voted_button);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.type.setText(data.get(position).getType());
viewHolder.time.setText(data.get(position).getTime());
viewHolder.text.setText(data.get(position).getText());
viewHolder.answerView.setLayoutParams(params.get(position));
viewHolder.answerView.setLayout(context, "Multiple", 5, position);
viewHolder.answerView.setVisibility(false);
viewHolder.answerView.setAnswers(pollAnswers.get(position));
return convertView;
}
The fragment for the listview
SurveyListFragment extends ListFragment {
private ArrayList<Card> cardList;
private PollsAdapter adapter;
private ArrayList<Answer> answers;
ArrayList<Integer> visible;
private ArrayList<RelativeLayout.LayoutParams> params;
private ArrayList<Integer> pollAnswers;
/**
when user clicks on a poll display the poll options for it
*/
#Override
public void onListItemClick(ListView l, View view, final int position, long id) {
final PollsAdapter.ViewHolder holder = (PollsAdapter.ViewHolder)adapter.getView(position, view, l).getTag();
if (holder.getAnswerView().getHeight() == 0) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.poll_space);
params.addRule(RelativeLayout.RIGHT_OF, R.id.card_icon);
//holder.getAnswerView().setLayoutParams(params);
this.params.set(position, params);
for (int i = 0; i < holder.getAnswerView().getOptions().size(); i++) {
holder.getAnswerView().getOptions().get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int p = 0; p < holder.getAnswerView().getOptions().size(); p++) {
if (holder.getAnswerView().getOptions().get(p) == v) {
holder.getAnswerView().setAnswers(p);
pollAnswers.set(position, p);
adapter = new PollsAdapter(getActivity(), cardList, SurveyListFragment.this.params, pollAnswers);
setListAdapter(adapter);
}
}
}
});
}
}
else {
holder.getAnswerView().setVisibility(false);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 0);
params.addRule(RelativeLayout.BELOW, R.id.poll_space);
params.addRule(RelativeLayout.RIGHT_OF, R.id.card_icon);
this.params.set(position, params);
// holder.getAnswerView().setLayoutParams(params);
adapter.notifyDataSetChanged();
}
super.onListItemClick(l, view, position, id);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setListAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
cardList = new ArrayList<>();
answers = new ArrayList<>();
visible = new ArrayList<>();
params = new ArrayList<>();
pollAnswers = new ArrayList<>();
Answer answer = new Answer();
answer.setText("one");
answers.add(answer);
answer = new Answer();
answer.setText("two");
answers.add(answer);
answer = new Answer();
answer.setText("three");
answers.add(answer);
answer = new Answer();
answer.setText("four");
answers.add(answer);
Card card = new Card();
card.setType("Polls");
card.setText("What issue listed below would you like to see as a priority for Nashville’s next mayor?");
card.setTime("Closing Soon");
for (int i = 0; i < cardList.size(); i++) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 0);
params.addRule(RelativeLayout.BELOW, R.id.poll_space);
params.addRule(RelativeLayout.RIGHT_OF, R.id.card_icon);
this.params.add(params);
pollAnswers.add(-1);
}
adapter = new PollsAdapter(getActivity(), cardList, params, pollAnswers);
}
Parse the survey object to the view class when you create the convertView. And parse a new object every time recycle previous views. Here are some codes.
1) Initialize the views in ProductListItemView
public ProductListItemView(Context context, ProductItem item) {
super(context);
mProductItem = item;
initView(context);
}
/**
* This function sets up all the Views contained in the FrameLayout
*
* #param context
*/
private void initView(Context context) {
addView(LayoutInflater.from(context).inflate(R.layout.list_item_product, null));
ButterKnife.inject(this);
if (mProductItem != null) {
setProductItem(mProductItem);
}
}
2) set object to the view
public void setProductItem(final ProductItem item) {
/**
* Clear Listener. Important!! Cause by Android Recycle View
* Do whatever you want to reset the recycled view or new view
*/
mPurchase.setOnClickListener(null);
endorsed_by_image.setVisibility(INVISIBLE);
endorsed_by_name.setVisibility(INVISIBLE);
mBtnEndorse.setOnCheckedChangeListener(null);
mProductItem = item;
mProductName.setText(mProductItem.getName());
3) In your adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ProductItem item = mProducts.get(position);
if (convertView == null) {
convertView = new ProductListItemView(getActivity(), item);
} else {
((ProductListItemView) convertView).setProductItem(item);
}
}
Hope I explain it well.
And in getView(), it is better to implement ViewHolder. Visit http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html

Getting value from the listview with custom adpter of selected checkbox to the activity

I am stuck when trying to get the value of selected checkbox listview values in my activity. I don't know how to do it, can any one suggest me a resolution to this issue?. Here is my code :
public class CandidateAdapter extends BaseAdapter implements OnCheckedChangeListener {
Context ctxt;
private LayoutInflater mInflater;
private ArrayList<CandidateModel> candidateList = new ArrayList<CandidateModel>();
private SparseBooleanArray mCheckStates;
public CandidateAdapter(Context context,ArrayList<CandidateModel> candidateList) {
mInflater = LayoutInflater.from(context);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.candidateList = candidateList;
mCheckStates = new SparseBooleanArray(candidateList.size());
}
#Override
public int getCount() {
return candidateList.size();
}
#Override
public CandidateModel getItem(int position) {
return candidateList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if(view == null){
view = mInflater.inflate(R.layout.table_row_candidate,null);
holder = new ViewHolder();
holder.candidateName = (TextView)view.findViewById(R.id.candidatenametxt);
holder.contactNumber = (TextView)view.findViewById(R.id.contactnumbertxt);
holder.email = (TextView)view.findViewById(R.id.emailtxt);
holder.contactCheckBox = (CheckBox)view.findViewById(R.id.contactchk);
view.setTag(holder);
}
else{
holder = (ViewHolder)view.getTag();
}
final CandidateModel cm = candidateList.get(position);
String contactNumber = cm.getContactNumber();
String candidateName = cm.getCandidateName();
String email = cm.getEmail();
if(!candidateName.equals("null") && candidateName!=null)
{
holder.candidateName.setText(cm.getCandidateName());
}
else{
holder.candidateName.setText("confidential");
}
if(!contactNumber.equals("null") && contactNumber!="" && contactNumber!=null && !contactNumber.equals("NA"))
{
holder.contactNumber.setText(cm.getContactNumber());
}
else{
holder.contactNumber.setVisibility(View.GONE);
}
if(!email.equals("null") && email!="" && email!=null && !email.equals("NA"))
{
holder.email.setText(cm.getEmail());
}
else{
holder.email.setVisibility(View.GONE);
}
holder.contactCheckBox.setTag(position);
holder.contactCheckBox.setChecked(mCheckStates.get(position, false));
holder.contactCheckBox.setOnCheckedChangeListener(this);
return view;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
private class ViewHolder{
public TextView candidateName;
public TextView contactNumber;
public TextView email;
public CheckBox contactCheckBox;
}
}
///Code in my activity. Here I am actually adding the data to the adapter.
i want the data of selected checkboxes from the list view, how would I achieve it?.
dataarray = datajsonobject.getJSONArray("candidateList");
CandidateAdapter ca = null;
final ArrayList<CandidateModel> candidateList = new ArrayList<CandidateModel>();
for (int i = 0; i < dataarray.length(); i++) {
JSONObject dataobject = new JSONObject();
dataobject = dataarray.getJSONObject(i);
String candidate_name = dataobject.getString("fullName");
String url = dataobject.getString("url");
String email = dataobject.getString("email");
String contactNumber = dataobject.getString("contactNumber");
String candidateId = dataobject.getString("candidateId");
//CandidateModel cm = new CandidateModel(candidate_name,score);
CandidateModel cm = new CandidateModel();
cm.setJobId(job_id);
cm.setCandidateName(candidate_name);
cm.setResumeURL(url);
cm.setContactNumber(contactNumber);
cm.setEmail(email);
cm.setSelected(false);
cm.setCandidateId(candidateId);
candidateList.add(cm);
}
ca = new CandidateAdapter(Candidate.this,candidateList);
clist.setAdapter(ca);
clist.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
CandidateModel selItem = candidateList.get(position);//get the selected RowItem from the list
Intent downloadResumeIntent = new Intent(
getApplicationContext(),
DownloadResume.class);
final String url = selItem.getResumeURL();
downloadResumeIntent.putExtra("url",url);
downloadResumeIntent.putExtra("jobId",job_id);
//downloadResumeIntent.putExtra("resumeUniqueID", uniqueResumeId);
startActivity(downloadResumeIntent);
Toast.makeText(getApplicationContext(), "CLICKED", Toast.LENGTH_SHORT).show();
}
});
Try to add one more boolean field in adapter item modle class CandidateModel :
public class CandidateModel {
private boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
Use isSelected field directly instead SparseBooleanArray or no need to SparseBooleanArray :
holder.contactCheckBox.setChecked(cm.isSelected());
holder.contactCheckBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
cm.setSelected(isChecked);
}
});
Get checked all item :
public ArrayList<CandidateModel> getCheckAllItem(){
ArrayList<CandidateModel> candidateModelArrayList = new ArrayList<CandidateModel>();
for(CandidateModel model :candidateList){
if(model.isSelected()){
candidateModelArrayList.add(model);
}
}
return candidateModelArrayList
}
Check item at position :
public boolean isItemChecked (int index){
return candidateList.get(index).isSelected();
}
maintain arraylist globally in adapter maintain the check box state in the arraylist now you can get the arraylist in activity by calling the adaptet.arraylist;
If candidateList order remains the same all the time, then it is ok to use position as Tag value.
Try putting this method in your adapter and call it from activity.
public ArrayList<CandidateModel> GetCheckedItems(){
ArrayList<CandidateModel> checkedItems = new ArrayList<CandidateModel>();
for(int position = 0; position < candidateList.size(); position++){
if(mCheckStates.get(position))
checkedItems.add(candidateList.get(position));
}
return checkedItems;
}
Maybe i misunderstand your question :). Best regards.
Use the getter methods from class CandidateModel to retrieve all the data you want. eg: selItem.getResumeURL();
why do you need to know the checkbox's state if you know the position in the list that has been clicked? regardless of the answer you can use the already present method adapter.isChecked(position) to see if the checkbox is checked or not.

How to get Values from the ArrayAdapter to the MainActivity for Custom ListView?

I would like to get a value ArrayAdapter to the MainActivity for Custom ListView with CheckBoxes.But Whenever I tried to get any value from the main activity the app crashes.Please give me a snippet on this,I am struck here for little while Thanks.Here is my code
public class ModelListViewActivity extends ListActivity {
public static final String KK_TAG="KK AHH!!!";
MyCustomArrayAdapter mas;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this,getModel());
setListAdapter(adapter);
}
private List<Model> getModel()
{
List<Model> list = new ArrayList<Model>();
list.add(get("Android +200","Google"));
list.add(get("Windows +500","Microsoft"));
list.add(get("iPhone +600","Apple"));
list.add(get("Ubuntu +700","Linux"));
list.add(get("Bada -800","Samsung"));
list.add(get("Android +1000","Google"));
list.add(get("Symbian -1000","Nokia"));
list.add(get("Windows XP +400","Microsoft"));
// select one item by default
return list;
}
private Model get(String s,String place)
{
return new Model(s,place);
}
}
Here is the adapter & in this I want to get the selcted String in the Main activity
public class MyCustomArrayAdapter extends ArrayAdapter<Model>
{
public static final String KK_TAG="KK AHH!!!";
String selected = "Karthik";
private final List<Model> list;
private final Activity context;
public MyCustomArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.list_layout, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text, sub;
protected CheckBox checkbox;
}
public void manipulation()
{
int valued=0;
selected = selected.replaceAll("\\s+", " ");
Log.v(KK_TAG,"selected:" +selected);
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(selected);
while (m.find())
{
Log.v(KK_TAG,m.group());
String test=m.group();
int aInt = Integer.parseInt(test);
valued=valued+aInt;
}
String conv=Integer.toString(valued);
Log.v(KK_TAG, "Conv: "+conv);
}
public void tester()
{
Log.v(KK_TAG, "Conv: ");
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.text.setTextColor(Color.BLACK);
viewHolder.sub = (TextView) view.findViewById(R.id.sub);
viewHolder.sub.setTextColor(Color.GRAY);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
{
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
Log.v(KK_TAG, "Checked : " + element.getName());
if(isChecked)
{
selected +=element.getName()+" ";
Log.v(KK_TAG, "Checked : " + selected);
}
else
{
String source = selected;
String find = element.getName();
String replace = "";
Pattern pattern = Pattern.compile(find);
Matcher matcher = pattern.matcher(source);
selected = matcher.replaceAll(replace);
Log.v(KK_TAG,"Source = " + source);
Log.v(KK_TAG,"UnChecked = " + selected);
}
} });
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else
{
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.sub.setText(list.get(position).getPlace());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}

Categories

Resources