Android ListView with Custom Array adaptor image reoccuring - android

i am trying to setVisible a play icon on click of listview item just like in music player.
I am using a custom array adapter, all is working good but when i scroll up/down and select any item on the list the previous play icon dosent go away.
But if i dont scroll and just click on the item it works perfectly fine.
OnclickListener :
listChannels.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if (oldView != null) {
oldView.setDrawingCacheEnabled(true);
ImageView icon = (ImageView) oldView
.findViewById(R.id.icon);
icon.setImageBitmap(null);
icon.setVisibility(ImageView.GONE);
icon.invalidate();
}
oldView = arg1;
selectedItem = arg2;
ImageView icon = (ImageView) arg1.findViewById(R.id.icon);
icon.setImageResource(R.drawable.play);
icon.setVisibility(ImageView.VISIBLE);
}
});
Array Adapter :
private class ListArrayAdapter extends ArrayAdapter<String> {
public ListArrayAdapter(Context context, int textViewResourceId,
String[] arrTitle) {
super(context, textViewResourceId, arrTitle);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.listitem_row, parent, false);
TextView label = (TextView) row.findViewById(R.id.station);
ImageView imageView = (ImageView) row
.findViewById(R.id.imageViewDisplay);
String areaStr = feeds.get(position).getStrLocation();
imageLoader.DisplayImage(feeds.get(position).getStrImage()
.toString(), activity, imageView);
if (!areaStr.equals("")) {
TextView area = (TextView) row.findViewById(R.id.area);
area.setText(areaStr);
area.setVisibility(TextView.VISIBLE);
}
if (selectedItem == position) {
ImageView icon = (ImageView) row.findViewById(R.id.icon);
icon.setImageResource(R.drawable.play);
icon.setVisibility(ImageView.VISIBLE);
}
return row;
}
}

You shoud have your custom adapter class like this:
public class ListArrayAdapter extends ArrayAdapter<String>{
Context context;
ArrayList<String> array=new ArrayList<String>();
LayoutInflater mInflater;
int selected;
public ListArrayAdapter(Context context,int textViewResourceId,ArrayList<String> list)
{
super(context, textViewResourceId, list);
this.context=context;
array=list;
mInflater = LayoutInflater.from(context);
selected=list.size()+1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.label = (TextView) convertView.findViewById(R.id.station);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageViewDisplay);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.area = (TextView) row.findViewById(R.id.area);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
// your code goes here
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
selected=position;
holder.icon.setImageResource(R.drawable.play);
holder.icon.setVisibility(View.VISIBLE);
}
});
if(selected==position)
{
holder.icon.setImageResource(R.drawable.play);
holder.icon.setVisibility(View.VISIBLE);
}
else
holder.icon.setVisibility(View.GONE);
return convertView;
}
static class ViewHolder
{
TextView label;
ImageView imageView;
ImageView icon;
TextView area;
}
}
and you don't need to worry for your this proble in your listview.onItemClick().

Related

ListView setOnItemClicklistener NullPointerException

public class CustomAdapter extends ArrayAdapter<Plan> implements View.OnClickListener {
private ArrayList<Plan> planArrayList;
int position;
Context context;
private static class ViewHolder{
TextView workType;
TextView zone;
TextView division;
TextView station;
TextView Msg;
}
public CustomAdapter(ArrayList<Plan> plan,Context context){
super(context,R.layout.plan_list,plan);
this.planArrayList=plan;
this.context=context;
}
#Override
public void onClick(View v) {
}
private int lastPosition = -1;
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Plan plans = getItem(position);
ViewHolder viewHolder;
final View result;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
viewHolder = new ViewHolder();
//LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.plan_list,parent,false);
viewHolder.workType = (TextView) convertView.findViewById(R.id.plan_worktype);
viewHolder.zone = (TextView) convertView.findViewById(R.id.plan_zone);
viewHolder.division = (TextView) convertView.findViewById(R.id.plan_division);
viewHolder.station = (TextView) convertView.findViewById(R.id.plan_station);
viewHolder.Msg = (TextView) convertView.findViewById(R.id.)
result=convertView;
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
Animation animation = AnimationUtils.loadAnimation(context, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
Plan plan = planArrayList.get(position);
lastPosition = position;
viewHolder.workType.setText(plans.getWorkType());
viewHolder.zone.setText(plans.getZone());
viewHolder.division.setText(plans.getDiv());
viewHolder.station.setText(plans.getSTA());
viewHolder.workType.setText(plan.getWorkType());
viewHolder.zone.setText(plan.getZone());
viewHolder.division.setText(plan.getDiv());
viewHolder.station.setText(plan.getSTA());
if (this.position == position){
View view2 = inflater.inflate(R.layout.list_dialog,null);
TextView worktype= (TextView) view2.findViewById(R.id.dlg_worktype);
TextView zone = (TextView) view2.findViewById(R.id.dlg_zone);
TextView div = (TextView) view2.findViewById(R.id.dlg_division);
TextView sta = (TextView) view2.findViewById(R.id.dlg_station);
TextView msg = (TextView) view2.findViewById(R.id.dlg_msg);
worktype.setText(plan.getWorkType());
zone.setText(plan.getZone());
div.setText(plan.getDiv());
sta.setText(plan.getSTA());
msg.setText(plan.getMsg());
return view2;
}
return convertView;
}
public void selectedItem(int position){
this.position=position;
}
}
When I called setOnItemClickListener on listView item those item values need to display in dialog box.
By the above code I'm getting java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.example.nsurekha.entry_ex.CustomAdapter$ViewHolder.workType' on a null object reference
If you want to use onClick on listView
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
String title=adapter.getItem(arg2).getTitle();
String description=adapter.getItem(arg2).getDescription();
String addedby=adapter.getItem(arg2).getAddedby();
}
});
Now you can easily show dialogbox with the desired data. Hope it works for you.

Dynamically change custom list item background

I am creating a custom list view with favorite functionality, but I don't know how to change favorite image background on click. When I simply change the background of favorite icon than it automatically change background of another favorite image background at the time of scrolling. Please check below code :
public class CustomArrayAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater = null;
ArrayList<Customlist> list;
DecimalFormat formatter = new DecimalFormat("#,##,###");
public CustomArrayAdapter(Activity a, ArrayList<Customlist> list) {
activity = a;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
TextView txt_unit, txt_state, txt_price, term_left, customr;
TextView install_date;
final ImageView fav;
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.list_item, null);
customr = (TextView) view.findViewById(R.id.customr);
txt_state = (TextView) view.findViewById(R.id.txt_state);
install_date = (TextView) view.findViewById(R.id.install_date);
term_left = (TextView) view.findViewById(R.id.term_left);
txt_price = (TextView) view.findViewById(R.id.txt_price);
fav = (ImageView) view.findViewById(R.id.fav);
txt_unit = (TextView) view.findViewById(R.id.txt_unit);
fav.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// fav = (ImageView)v.findViewById(R)
fav.setBackgroundResource(R.drawable.favourite_select);
Toast.makeText(activity, "click", 1).show();
}
});
// set values
customr.setText(list.get(position).getCUSTOMER());
txt_state.setText(list.get(position).getSTATE_NAME());
install_date.setText(list.get(position).getINSTALL_DATE());
term_left.setText(list.get(position).getTREM_LEFT());
String price = formatter.format(Integer.parseInt(list.get(position)
.getRUPEES()));
return view;
}
}
First, you need to implement the adapter on ViewHolder pattern:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHoldler holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(ctx).inflate(
R.layout.frag_home_gridview_item, null, false);
holder = new ViewHoldler();
holder.iv = (ImageView) convertView
.findViewById(R.id.gridview_item_label);
holder.tv = (TextView) convertView
.findViewById(R.id.gridview_item_name);
convertView.setTag(holder);
} else {
holder = (ViewHoldler) convertView.getTag();
}
holder.tv.setText(getItem(position));
holder.iv.setImageResource(this.ids[position]);
return convertView;
}
private class ViewHoldler {
ImageView iv;
TextView tv;
}
Second, use partial refreshment mechanism to change the target View's background:
private void refreshPartially(int position){
int firstVisiblePosition = listview.getFirstVisiblePosition();
int lastVisiblePosition = listview.getLastVisiblePosition();
if(position>=firstVisiblePosition && position<=lastVisiblePosition){
View view = listview.getChildAt(position - firstVisiblePosition);
if(view.getTag() instanceof ViewHolder){
ViewHolder vh = (ViewHolder)view.getTag();
//holder.play.setBackgroundResource(resId);//Do something here.
...
}
}
}
Third, add AdapterView.OnItemClickListener to your ListView:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
refreshPartially(position);
}
});
You need to implement the adapter on ViewHolder pattern:
http://www.vogella.com/tutorials/AndroidListView/article.html

Wrong row deleted from listview android

I know there are many Stack Overflow questions resolved for my issue. I tried most of the solutions, but none succeeded for me.
I am trying to implement the listrow deletion of listview.On longclick of listrow alert will popup where there are two option delete and cancel.When delete is pressed that row will be deleted in custom adapter as well as row in mysql table using async task. But only the last row gets deleted.
I have set notifyDataSetChanged() to my adapter. Even then it is not working fine.
This is my code:
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
System.out.println("postition value::" + position);
removeItemFromList(position);
return true;
}
});
protected void removeItemFromList(int position) {
final int deletePosition = position;
System.out.println("deleting postition::"+deletePosition);
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Delete");
alert.setMessage("Do you want delete this item?");
alert.setPositiveButton("YES", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TOD O Auto-generated method stub
// main code on after clicking yes
new removefromfav().execute();
courselist.remove(deletePosition);
// dataAdapter.remove(dataAdapter.getItem(deletePosition));
dataAdapter.notifyDataSetChanged();
listView.setAdapter(dataAdapter);
// dataAdapter.notifyDataSetInvalidated();
}
});
alert.setNegativeButton("CANCEL", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alert.show();
}
My Adapter Class,
private class MyCustomAdapter extends ArrayAdapter<Course> {
private ArrayList<Course> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Course> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Course>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
ImageView cover;
TextView cost;
ImageView ratingshow;
ImageView promoimage;
TextView enroll;
}
public void add(Course country) {
this.countryList.add(country);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.course_overview, null);
holder = new ViewHolder();
holder.code = (TextView) convertView
.findViewById(R.id.coursename);
holder.name = (TextView) convertView.findViewById(R.id.author);
holder.cost = (TextView) convertView.findViewById(R.id.cost);
holder.cover = (ImageView) convertView.findViewById(R.id.cover);
holder.ratingshow = (ImageView) convertView
.findViewById(R.id.ratingimage);
holder.promoimage = (ImageView) convertView
.findViewById(R.id.promoimage);
holder.enroll = (TextView) convertView
.findViewById(R.id.enroll);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Course country = this.countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.cost.setText("$ " + country.getRegion());
holder.cover.setImageBitmap(country.getBitmap());
return convertView;
}
}
Anyone can help me???
You are not deleting anything from your countryList in MyCustomAdapter.
I see a function where you add stuff, but I don't see one removing stuff.
Add a function to remove items from your countryList:
private class MyCustomAdapter extends ArrayAdapter<Course> {
private ArrayList<Course> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Course> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Course>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
ImageView cover;
TextView cost;
ImageView ratingshow;
ImageView promoimage;
TextView enroll;
}
public void add(Course country) {
this.countryList.add(country);
}
//ADD THIS FUNCTION
public void remove(int index) {
this.countryList.remove(index)
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.course_overview, null);
holder = new ViewHolder();
holder.code = (TextView) convertView
.findViewById(R.id.coursename);
holder.name = (TextView) convertView.findViewById(R.id.author);
holder.cost = (TextView) convertView.findViewById(R.id.cost);
holder.cover = (ImageView) convertView.findViewById(R.id.cover);
holder.ratingshow = (ImageView) convertView
.findViewById(R.id.ratingimage);
holder.promoimage = (ImageView) convertView
.findViewById(R.id.promoimage);
holder.enroll = (TextView) convertView
.findViewById(R.id.enroll);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Course country = this.countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.cost.setText("$ " + country.getRegion());
holder.cover.setImageBitmap(country.getBitmap());
return convertView;
}
}
And call this in the onClick callback of your dialog
public void onClick(DialogInterface dialog, int which) {
// TOD O Auto-generated method stub
// main code on after clicking yes
new removefromfav().execute();
dataAdapter.remove(which);
dataAdapter.notifyDataSetChanged();
}
Ok sure i can help you you will add one more function on your custom adapter
public void removeElementAtPosition(int position){
this.countryList.remove(position);
notifyDataSetChanged();
}
and delete your adapter item in your long click function like
dataAdapter.removeElementAtPosition(position);
you don't want to update our adapter once again. And you will check and avoid the null pointer exception
All the adapters will work with this function
public int getCount(){
this.countryList.size();
}
so, you will affect the list in this adapter your list item will decreased if you check with this getcount function BASE ADAPTER
http://developer.android.com/reference/android/widget/BaseAdapter.html
All the best..

How to set image postition as fixed in gridview

I have on gridview for displaying number of images just like a gallery in android mobiles.
But when I scroll down to lower part of gridview the position of displaying images are changing.
My custom Adapter..
class MyCustomArrayAdapter extends ArrayAdapter<ModelBean> {
private final Activity context;
private final List<ModelBean> listDownload;
public MyCustomArrayAdapter(Activity context, List<ModelBean> list) {
super(context, R.layout.gridview_layout, list);
this.context = context;
this.listDownload = list;
}
static class ViewHolder {
protected ImageView imageView;
protected ProgressBar pb;
protected ModelBean mb;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.gridview_layout, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
holder.imageView.setVisibility(View.GONE);
holder.pb = (ProgressBar) convertView.findViewById(R.id.progressBar1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageView.setTag(listDownload.get(position).getImage());
holder.imageView.setId(position);
PbAndImageBean pb_and_imageBean = new PbAndImageBean();
pb_and_imageBean.setImg(holder.imageView);
pb_and_imageBean.setPb(holder.pb);
pb_and_imageBean.setModelBean(listDownload.get(position));
new DownloadImageAsyncTask(context).execute(pb_and_imageBean);
holder.imageView.setOnClickListener(new OnImageClickListener(position));
return convertView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(context, FullScreenViewActivity.class);
i.putExtra("position", _postion);
context.startActivity(i);
}
}
}
I have used lazy loading concept to get images from server ,
so single image gets downloaded at single time.
But logically it doesn't affect on my problem.
What i want to do is , when an image get downloaded at any position it should get locked at that particular position , will solve my problem.
Try like this-
class MyCustomArrayAdapter extends ArrayAdapter<ModelBean> {
private final Activity context;
private final List<ModelBean> listDownload;
public MyCustomArrayAdapter(Activity context, List<ModelBean> list) {
super(context, R.layout.gridview_layout, list);
this.context = context;
this.listDownload = list;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.gridview_layout, null);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.imageView);
imageView.setVisibility(View.GONE);
ProgressBar pb = (ProgressBar) convertView
.findViewById(R.id.progressBar1);
imageView.setTag(listDownload.get(position).getImage());
imageView.setId(position);
PbAndImageBean pb_and_imageBean = new PbAndImageBean();
pb_and_imageBean.setImg(imageView);
pb_and_imageBean.setPb(pb);
pb_and_imageBean.setModelBean(listDownload.get(position));
new DownloadImageAsyncTask(context).execute(pb_and_imageBean);
imageView.setOnClickListener(new OnImageClickListener(position));
return convertView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(context, FullScreenViewActivity.class);
i.putExtra("position", _postion);
context.startActivity(i);
}
}
}
Change this one.
View view = null;
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
holder = new ViewHolder();
view = inflator.inflate(R.layout.gridview_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) view.findViewById(R.id.imageView);
viewHolder.imageView.setVisibility(View.GONE);
viewHolder.pb = (ProgressBar) view.findViewById(R.id.progressBar1);
view.setTag(viewHolder);
} else {
holder = (ViewHolder) view.getTag();
}

Android listview using ViewHolder

I have a problem. I'm attempting to change an icon in my listview after it has been clicked. It works correctly although are not modified only the clicked icons but also those who are not displayed. For example if I click the icon in the first item of the listview, also the fifth icon changes. This behaviour is repeated for all the following items (every five items of the listview).
This is my getView method:
public class AlphabeticalAdapter extends ArrayAdapter<String>
{
int layoutResourceId;
private final Context context;
private List<String> data;
private ProgressDialog mProgressDialog;
private ImageView downloadImageButton;
public AlphabeticalAdapter(Context context, int resource, List<String> data){
super(context, resource, data);
this.layoutResourceId = resource;
this.context = context;
this.data = data;
}
public View getView(int position, View convertView, ViewGroup parent) {
// View rowView = convertView;
final ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.catalogslist_single_row, parent, false);
viewHolder = new ViewHolder();
viewHolder.catlogTitle=(TextView)convertView.findViewById(R.id.txtTitle);
viewHolder.icon=(ImageView)convertView.findViewById(R.id.imageView2);
viewHolder.downloadImageButton=(ImageView)convertView.findViewById(R.id.downloadImageButton);
//downloadImageButton = (ImageView)rowView.findViewById(R.id.downloadImageButton);
viewHolder.position = position;
viewHolder.downloadImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("DOWNLOAD PRESSED");
viewHolder.downloadImageButton = (ImageView)v.findViewById(R.id.downloadImageButton);
viewHolder.downloadImageButton.setImageResource(R.drawable.icon_ok);
viewHolder.downloadImageButton.setTag("downloaded");
//rowView.setTag("downloaded");
}
});
convertView.setTag(viewHolder);
}
else{
viewHolder= (ViewHolder)convertView.getTag();
}
viewHolder.catlogTitle.setText(data.get(position));
viewHolder.catlogTitle.setTypeface(regularDin);
viewHolder.icon.setImageResource(R.drawable.cata);
if(viewHolder.downloadImageButton.getTag() == "downloaded"){
downloadImageButton = (ImageView)convertView.findViewById(R.id.downloadImageButton);
downloadImageButton.setImageResource(R.drawable.icon_ok);
}
else{
downloadImageButton = (ImageView)convertView.findViewById(R.id.downloadImageButton);
downloadImageButton.setImageResource(R.drawable.icon_download);
}
viewHolder.position = position;
return convertView;
} //close getView
...
And this is my ViewHolder class:
static class ViewHolder{
ImageView downloadImageButton;
TextView catlogTitle;
ImageView icon;
int position;
}
Change your code at below. I think you're missing that.
public class AlphabeticalAdapter extends ArrayAdapter<String> {
int layoutResourceId;
private final Context context;
private List<String> data;
private List<String> tags;
private ProgressDialog mProgressDialog;
private ImageView downloadImageButton;
public AlphabeticalAdapter(Context context, int resource, List<String> data) {
super(context, resource, data);
this.layoutResourceId = resource;
this.context = context;
this.data = data;
tags = new ArrayList<String>();
int size = data.size();
for (int i = 0; i < size; i++) {
tags.add("tag");
}
}
static class ViewHolder {
ImageView downloadImageButton;
TextView catlogTitle;
ImageView icon;
int position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// View rowView = convertView;
final ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = inflater.inflate(R.layout.catalogslist_single_row,
// parent, false);
viewHolder = new ViewHolder();
viewHolder.position = position;
viewHolder.downloadImageButton
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("DOWNLOAD PRESSED");
viewHolder.downloadImageButton.setTag("downloaded");
tags.add(position, "downloaded");
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.catlogTitle.setText(data.get(position));
viewHolder.catlogTitle.setTypeface(regularDin);
viewHolder.icon.setImageResource(R.drawable.cata);
if (tags.get(position) == "downloaded") {
downloadImageButton.setImageResource(R.drawable.icon_ok);
} else {
downloadImageButton.setImageResource(R.drawable.icon_download);
}
viewHolder.position = position;
return convertView;
} // close getView
}
There are as many convertViews as many row visible in the same time in your ListView (the system reuses it). So you actually have 5 convertView, and because of that you have 5 ImageView for the icons. The problem is that you use those ImageView's tag to store the "downloaded" information. That is 5 state, and that is why you see every fifth row downloaded while you scroll in the list.
I guess now you see that it won't work. You need to store the downloaded state for every item, so you have to change the underlying List<String> to List<ListItem>, where ListItem can store the downloaded state for the actual row.
After that, all you have to do is to update the convertView's ImageView (in getView()) to show the correct icon.
Change your code like this. Add null check with convertView before your try block.
final MenuItem menuItem = getItem(position);
View view = convertView;
final ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater;
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.menu_item, parent, false);
viewHolder = new ViewHolder();
// viewHolder.half = (TextView) view.findViewById(R.id.half);
viewHolder.name = (TextView) view.findViewById(R.id.name);
viewHolder.description = (TextView) view.findViewById(R.id.description);
viewHolder.price = (TextView) view.findViewById(R.id.price);
viewHolder.add = (Button) view.findViewById(R.id.add);
viewHolder.selectedView = view.findViewById(R.id.selectedView);
viewHolder.remove = (Button) view.findViewById(R.id.remove);
viewHolder.total = (TextView) view.findViewById(R.id.itemTotal);
viewHolder.quantity = (TextView) view.findViewById(R.id.quantity);
view.setTag(viewHolder);
}else{
viewHolder= (ViewHolder)convertView.getTag();
}
You can try this
public class CustomArrayAdapter extends ArrayAdapter {
// declare your custom list with type;
private List<YourModelClass> allData = new ArrayList<YourModelClass>();
public CustomArrayAdapter(#NonNull Context context, List<YourModelClass> allData) {
super(context, R.layout.your_layout, allData); // add your_layout.xml
this.allData = allData;
}
class ViewHolder {
TextView name, phone; // declare your your_layout.xml view type
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.your_layout, parent, false); // inflate your_layout.xml
//initialize your your_layout.xml view
holder.name = convertView.findViewById(R.id.tv_item_name);
holder.phone = convertView.findViewById(R.id.tv_item_phone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//set value into your_layout.xml
holder.name.setText(allData.get(position).getName());
holder.phone.setText(allData.get(position).getNumber());
return convertView;
}
}
public class AndroidListViewActivity extends ListActivity
{
private ListView listView;
private String names[] = {
"HV CAPACITOR",
"LV CAPACITORCSS",
};
private String desc[] = {
"The Powerful Hypter Text Markup Language 5",
"Cascading Style Sheets",
};
private Integer imageid[] = {
R.drawable.hv_capacitor,
R.drawable.lv_capacitor,
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.capacitor_layout);
// storing string resources into Array
String[] product_name = getResources().getStringArray(R.array.product_name);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, product_name));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
}
});
CapacitorList capacitorList = new CapacitorList(this, names, desc, imageid);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(capacitorList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), CapacitorList.class);
// sending data to new activity
// startActivity(i);
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "You Clicked " + names[i], Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories

Resources