Data from parsed XML is fed into an ArrayList itemList. Results meeting the criteria are then added to filteredList, which in turn is bound to the adapter to be displayed in my ListView. However, the data being added to filteredList is being repeated (twice) and I do not understand why. Could anyone perhaps point it out for me? I've been staring at it for a while now lol.
Here is the function from MainActivity.java
private void FilterList() {
ListView lv = (ListView) findViewById(R.id.info); //locate listview
for (int i = 0; i < itemList.size(); i++) //cycle arraylist
{
try {
//convert startdate, endDate
Date cDate = dateFormat.parse(currDate); //get/convert selected date
Date stDate = dateFormat.parse(itemList.get(i).startDate);
Date enDate = dateFormat.parse(itemList.get(i).endDate);
//compare, if active true then add
if ((cDate.after(stDate)) && (cDate.before(enDate))){
//add itemList element to filterList
filteredList.add(itemList.get(i));
Log.d("DEBUG CHECKME", "added to filteredList: ");
}
} catch (java.text.ParseException e) {
e.printStackTrace();
}
}
itemAdapter = new PostItemAdapter(mcontext, R.layout.postitem, filteredList); //pass results into adapter
lv.setAdapter(itemAdapter); //bind listview & adapter
Log.d("DEBUG CHECKME", "lv.setAdapter");
}
And here is my adapter class:
public class PostItemAdapter extends ArrayAdapter<Item>
{
private LayoutInflater inflater;
private ArrayList<Item> datas;
public PostItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects)
{
super(context, textViewResourceId, objects);
inflater = ((Activity) context).getLayoutInflater();
datas = objects;
}
//class to hold view object references
static class ViewHolder
{
TextView itemTitleView;
ImageView itemThumbView;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.postitem, null);
viewHolder = new ViewHolder();
viewHolder.itemThumbView = (ImageView) convertView.findViewById(R.id.itemThumb);
viewHolder.itemTitleView = (TextView) convertView.findViewById(R.id.itemTitleLabel);
//viewHolder.itemDateView = (TextView) convertView.findViewById(R.id.itemDateLabel);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (datas.get(position).itemThumbUrl == null)
{
viewHolder.itemThumbView.setImageResource(R.drawable.test);
}
viewHolder.itemTitleView.setText(datas.get(position).itemTitle);
return convertView;
}
}
try this i hope it will help you
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.postitem, parent, false);
} else {
row = convertView;
}
filteredList datas= rowItems.get(position);
try {
TextView itemTitleView = (TextView) convertView.findViewById(R.id.itemTitleLabel);
itemTitleView.setText(datas.itemTitle);
} catch (Exception e) {
}
try {
ImageView itemThumbView = (ImageView) convertView.findViewById(R.id.itemThumb);
itemThumbView.setImageResource(R.drawable.test);
} catch (Exception e) {
}
});
return row;
}
Related
I'm having a ListView with a custom ArrayAdapter. The problem is that I cannot hide (setVisibility(View.GONE)) TextView in some elements of choice. Here is a minimized-readable summary part of my code:
public class ListViewAdapter extends ArrayAdapter<ItemModel> {
private int listItemLayout;
static class ViewHolder {
private TextView description;
}
public ListViewAdapter(Context context, int layoutId, List<ItemModel> itemList) {
super(context, layoutId, itemList);
this.listItemLayout = layoutId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemModel item = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(listItemLayout, parent, false);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.description = convertView.findViewById(R.id.text_desription);
viewHolder.description.setText(item.getDescription());
if (TextUtils.isEmpty(item.getDescription())) {
viewHolder.description.setVisibility(View.GONE);
}
return convertView;
}
}
What am I doing wrong here? How can I hide a view inside item in ListView if its content String is empty?
Add else part of if condition to change visibility from GONE to VISIBLE as in below code.
public class ListViewAdapter extends ArrayAdapter {
private int listItemLayout;
static class ViewHolder {
private TextView description;
}
public ListViewAdapter(Context context, int layoutId, List itemList) {
super(context, layoutId, itemList);
this.listItemLayout = layoutId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemModel item = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(listItemLayout, parent, false);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.description = convertView.findViewById(R.id.text_desription);
viewHolder.description.setText(item.getDescription());
if (TextUtils.isEmpty(item.getDescription())) {
viewHolder.description.setVisibility(View.GONE);
}else{
viewHolder.description.setVisibility(View.VISIBLE);
}
return convertView;
}
}
OR try if (item.getDescription()==null || item.getDescription().trim().length() == 0)
instead of if (TextUtils.isEmpty(item.getDescription()))
Check any white space should not be in your text. Try this-
if (TextUtils.isEmpty(item.getDescription().trim()) ||item.getDescription().trim().length()==0 ) {
viewHolder.description.setVisibility(View.GONE);
}
else{
viewHolder.description.setVisibility(View.VISIBLE);
}
I have to replace the white image in the clicked position of GridView with green one to indicate its selected in onItemClickListener method. I have used custom adapter to preset the images in first look in my grid. What should i do to change the image of selected image only.
gridView.setAdapter(new CustomGridViewAdapter(ctx, R.layout.seatrow_grid, seat_list));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
String selectedItem;
Seat_Availabe st_av = (Seat_Availabe) arg0.getItemAtPosition(position);
if ((st_av.getAvailable().equals("true")) && (st_av.getLadiesSeat().equals("false"))) {
}
else{
Toast.makeText(getApplicationContext(), "Already Booked", Toast.LENGTH_LONG).show();
}
}
});
my adapter class to set images in first look
public class CustomGridViewAdapter extends ArrayAdapter<Seat_Availabe>
{
Context context;
int layoutResourceId;
List<Seat_Availabe> data = new ArrayList<Seat_Availabe>();
public CustomGridViewAdapter(Context context, int layoutResourceId, List<Seat_Availabe> data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
RecordHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
row.setTag(holder);
}
else
{
holder = (RecordHolder) row.getTag();
}
Seat_Availabe seat = data.get(position);
String avail = seat.getAvailable();
String ladies = seat.getLadiesSeat();
if ((seat.getAvailable().equals("true")) && (seat.getLadiesSeat().equals("false"))) {
holder.imageItem.setImageResource(R.drawable.white);
}
else if((seat.getAvailable().equals("false")) && (seat.getLadiesSeat().equals("true")))
{
holder.imageItem.setImageResource(R.drawable.pink);
}
else if(seat.getAvailable().equals("false")){
holder.imageItem.setImageResource(R.drawable.gray);
}
else if(seat.getAvailable().equals("NA")){
holder.imageItem.setImageResource(R.drawable.whitenew);
}
else{
holder.imageItem.setImageResource(R.drawable.gray);
}
return row;
}
public static class RecordHolder
{
public ImageView imageItem;
}
}
I suppose you get the view object in the variable v of the click event, you could set the image of the view by:
v.setBackgroundResource(R.drawable.filename);//add your filename here
I have
public class MainActivity extends FragmentActivity
I wrote Loader class which implements AsyncResponse:
public class Loader implements AsyncResponse {
public Activity contextActivity;
Loader(Activity context) {
this.contextActivity = context;
}
Class "Loader" has method "DrawTabInfo" which calling from AsyncResponse callback.
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView);
}
if (tabId == 1) {
View view = inflater.inflate(R.layout.listviewlayout2, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView2);
}
list.setAdapter(adapter);
adapter.setNotifyOnChange(true);
Log.d("COUNT") shows - "4", what means array is built fine.
public class Adapter extends ArrayAdapter<JSONObject> {
private final Activity context;
private final ArrayList<JSONObject> profiles;
public String header;
public String preText;
public String imageURL;
static class ViewHolder {
public TextView header;
public ImageView image;
public TextView preText;
public LinearLayout linearItemLayout;
}
public Adapter(Activity context, ArrayList<JSONObject> array) {
super(context, R.layout.tab1_list_layout, array);
Log.d("ADAPTER", "SETTING ADAPTER");
this.context = context;
this.profiles = array;
Log.d("COUNT", "" + profiles.size());
}
#Override
public int getCount()
{
return profiles.size();
}
My getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.i("GetView Log", "Adapters GetView hasbeen called");// thats never calling
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
JSONObject item = null;
try {
item = profiles.get(position);
header = item.getString("header");
preText = item.getString("previewText");
imageURL = item.getString("previewImageUrl");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("ADAPTER LOG", header);
holder.header.setText(header);
holder.preText.setText(preText);
int headerHeight = (int) Math.round(header.length() * 1.5);
holder.linearItemLayout.setMinimumHeight(40 + headerHeight + preText.length());
Picasso.with(context).setIndicatorsEnabled(true);
Picasso.with(context).load(imageURL).resize(140,100).into(holder.image);
return rowView;
}
In MainActivity i calling, where "this" = MainActivity;
Loader loader = new Loader(this);
loader.loadTabInfo(0);
Method getView never calling. What I'am doing wrong?
UPD:
Solved:
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
//LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
//View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) contextActivity.findViewById(R.id.listView);
Your code is fine .. just you need a little bit change in get view method
add a return statement.. like return rowView;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.d("GETVIEaW", "GETVIEW");
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.preText.setText("Type your name");
return rowView;
}
Are you sure that Log.d() is not called? You may want to change logging scope, usually default scope is info and it doesn't show debug messages. You can try to use Log.i() or change scope.
Try posting your adapter.setNotifyOnChange(true); to handler. Follow this link
Could anybody explain me, how to realize?
I have an activity with listview and footer with some elements(textview).
Listview built with custom adapter. Each listview item has few elements. And my question: how can i change textview in footer, from custom adapter, when i clicking on some listview's element?
Thx a lot!
/**** My adapter ****/
public class MyListAdapter extends ArrayAdapter<Product> implements UndoAdapter {
private final Context mContext;
private HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
ArrayList<Product> products = new ArrayList<Product>();
final int INVALID_ID = -1;
LayoutInflater lInflater;
String imagePath;
public MyListAdapter(Context context, int textViewResourceId, List<Product> prod) {
//super(context, textViewResourceId, prod);
super(prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
for (int i = 0; i < prod.size(); i++) {
//add(prod.get(i));
mIdMap.put(prod.get(i),i);
}
}
#Override
public long getItemId(final int position) {
//return getItem(position).hashCode();
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;;
Product p = getItem(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.item, null);
//convertView.setBackgroundResource(R.drawable.rounded_corners);
int currentTheme = Utils.getCurrentTheme(convertView.getContext());
switch (currentTheme) {
case 0:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
case 1:
convertView.setBackgroundResource(R.drawable.border);
break;
default:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
}
holder = new ViewHolder();
holder.tvDescr = (TextView) convertView.findViewById(R.id.tvDescr);
holder.list_image = (ImageView) convertView.findViewById(R.id.list_image);
holder.products_amount = (TextView) convertView.findViewById(R.id.amountDigits);
holder.products_price = (TextView) convertView.findViewById(R.id.priceDigits);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
holder.unit = (TextView) convertView.findViewById(R.id.unit);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(p.getProductImageBitmap() != null && p.getProductImageBitmap() != "") {
Log.d("PATH -- ", p.getProductImageBitmap());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
/*.showImageOnLoading(R.id.progress_circular)*/
.build();
imageLoader.displayImage(p.getProductImageBitmap(), holder.list_image, options);
} else {
holder.list_image.setImageResource(R.drawable.ic_launcher);
}
holder.tvDescr.setText(p.getProductName());
holder.ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String deletedItem = getItem(position).getProductName();
MyListAdapter.this.remove(getItem(position));
if (MyListAdapter.this.getCount() > 0) {
Toast.makeText(mContext, deletedItem + " " + mContext.getString(R.string.deleted_item), Toast.LENGTH_SHORT).show();
MyListAdapter.this.notifyDataSetChanged();
} else {
Toast.makeText(mContext,mContext.getString(R.string.sklerolist_empty), Toast.LENGTH_SHORT).show();
}
}
});
//Функционал для большой картинки продукта
//открывается новое активити с большой картинкой
holder.list_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePath = getItem(position).getProductImageBitmap();
if(imagePath != null && imagePath != "") {
Pattern normalPrice = Pattern.compile("^file");
Matcher m2 = normalPrice.matcher(imagePath);
if (m2.find()) {
Intent myIntent = new Intent(view.getContext(), ViewImage.class).putExtra("imagePath", imagePath);
view.getContext().startActivity(myIntent);
}
}
}
});
holder.products_price.setText(fmt(p.getProductPrice()));
holder.products_amount.setText(fmt(p.getProductAmount()));
holder.unit.setText(p.getProductUnit());
return convertView;
}
public static String fmt(double d){
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
static class ViewHolder {
ImageView list_image;
TextView tvDescr;
TextView products_amount;
TextView products_price;
TextView unit;
ImageView ivImage;
ProgressBar circleProgress;
}
#NonNull
#Override
public View getUndoView(final int position, final View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
if (view == null) {
//view = LayoutInflater.from(mContext).inflate(R.layout.undo_row, parent, false);
view = lInflater.inflate(R.layout.undo_row, parent, false);
}
return view;
}
#NonNull
#Override
public View getUndoClickView(#NonNull final View view) {
return view.findViewById(R.id.undo_row_undobutton);
}
public View getHeaderView(final int position, final View convertView, final ViewGroup parent) {
TextView view = (TextView) convertView;
//View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_header, parent, false);
//view = lInflater.inflate(R.layout.list_header, parent, false);
}
//view.setText(mContext.getString(R.string.header, getHeaderId(position)));
return view;
}
public long getHeaderId(final int position) {
return position / 10;
}
}
Your ListView has a listener for the click events on list elements.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something when a list item is clicked
}
But if you want to pas something else back from the adapter to the Activity or the Fragment that contains that ListView and Adapter, you should create a simple interface and set it as listener to your adapter. After that, set click events on your rows from within the adapter, and notify the Activity or Fragment using your own interface.
For example you have the interface defined like this
public interface OnItemClickedCustomAdapter {
public void onClick(ItemPosition position);
}
and in your Adapter class you will have a private member
private OnItemClickedCustomAdapter mListener;
and a method used to set the listener
public void setOnItemClickedCustomAdapter(OnItemClickedCustomAdapter listener){
this.mListener = listener;
}
From your Activity or Fragment where your ListView is defined, and your adapter is set, you will be able to call setOnItemClickedCustomAdapter with this as parameter, and there you go. Your activity will now listen for your events. To trigger an event, just call mListener.onClick() from your custom adapter. You can pass back data you need back to the Activity or Fragment, and from there you have access to your Header or Footer directly, and you can change the text on them.
I'm developing an app with a custom layout and an arrayAdapter:
The problem is when I check one Box the app automatically check another 2 boxes!
I created a list where I put the positions of checkboxes and show that nothing its wrong! I think the problem is when I do the recycle!
Lets view some code; This is my ArrayAdapter:
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
VivzAdapter(Context context, String[] titles, int[] images, String[] description) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.ºtime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
holder.box.setTag(position);
holder.box.setOnCheckedChangeListener(this);
return row;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
int position = (Integer)buttonView.getTag();
Toast.makeText(getContext(), ""+position, Toast.LENGTH_SHORT).show();
positions.add(position);
Log.d("VIVZ", "+ "+position);
} else {
int position = (Integer)buttonView.getTag();
Toast.makeText(getContext(), ""+position, Toast.LENGTH_SHORT).show();
Log.d("VIVZ", "- "+position);
positions.remove(position);
}
Log.d("VIVZ", positions.toString());
}
}
I was stucked in same problem and found the solution.
Create a boolean array having size same as no. of elements in the list and initial value false for each list item. Then in getView set position in Id through setId for checkbox. Now set the value of checkbox from boolean array through setChecked method of checkbox. Add onClickListener for checkbox and in this listener change the value in boolean array not checkbox value directly.
I hope this resolve your problem also.
Just replace your adapter class with this code :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.ºtime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
At the end of getView method you should check if the current position is in the positions array or not, this should fix the problem
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.ºtime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
holder.box.setTag(position);
holder.box.setOnCheckedChangeListener(this);
////// Here you should update the checlbox status by checking if the current index is in the position array or not ////////////
boolean isFound = false;
for(int i =0;i<position.size();i++){
if(positions.get(i) == position){ // this line might need casting
isFound = true;
break;
}
holder.box.setChecked(isFound);
}
return row;
}
Use this sample project for ur problem. link to download complete project
https://drive.google.com/file/d/0B6C9Pqrvc_CWZHFDcmxKR01rc3c/edit?usp=sharing