I am getting wrong data after scrolling listview,after scrolling images are show on another listitem.
public class ContactListAdapter extends BaseAdapter {
private List<ContactBean> contactDataList;
private ArrayList<ContactBean> arraylist;
Context context;
ViewHolder v;
public ContactListAdapter(List<ContactBean> contactBeans, Context context) {
contactDataList = contactBeans;
this.context = context;
this.arraylist = new ArrayList<ContactBean>();
this.arraylist.addAll(contactDataList);
}
#Override
public int getCount() {
return contactDataList.size();
}
#Override
public Object getItem(int i) {
return contactDataList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.contact_list_item, null);
Log.e("Inside", "here--------------------------- In view1");
} else {
view = convertView;
Log.e("Inside", "here--------------------------- In view2");
}
v = new ViewHolder();
v.title = (TextView) view.findViewById(R.id.name);
v.phone = (TextView) view.findViewById(R.id.no);
v.imageView = (RoundedImageView) view.findViewById(R.id.pic);
v.firstChar = (TextView) view.findViewById(R.id.tv_firstChae);
final ContactBean data = contactDataList.get(i);
v.title.setText(contactDataList.get(i).getName());
v.phone.setText(contactDataList.get(i).getPhone());
// Set image if exists
try {
if (contactDataList.get(i).getThumb() != null) {
v.firstChar.setVisibility(View.GONE);
v.imageView.setVisibility(View.VISIBLE);
v.imageView.setImageBitmap(data.getThumb());
} else {
v.imageView.setVisibility(View.GONE);
String headerChar = (String) contactDataList.get(i).getName().subSequence(0, 1);
v.firstChar.setText(headerChar);
}
} catch (OutOfMemoryError e) {
// Add default picture
// v.imageView.setImageDrawable(this.context.getDrawable(R.mipmap.ic_launcher));
e.printStackTrace();
}
Log.e("Image Thumb", "--------------" + contactDataList.get(i).getThumb());
view.setTag(data);
return view;
}
static class ViewHolder {
RoundedImageView imageView;
TextView title, phone, firstChar;
}
}
in my contact list some contacts having image and which one not having a image thst show the first letter of initialletter of contact name
enter image description here
run the app i am geting this but scroool the listview the we getenter image description here
Try this:
UPD:
public class ContactListAdapter extends BaseAdapter {
private List<ContactBean> contactBeans;
private Context context;
public ContactListAdapter(List<ContactBean> contactBeans, Context context) {
this.context = context;
this.contactBeans = contactBeans;
}
#Override
public int getCount() {
return contactBeans.size();
}
#Override
public Object getItem(int i) {
return contactBeans.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
ViewHolder v;
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.contact_list_item, viewGroup, false);
v = new ViewHolder();
v.title = (TextView) view.findViewById(R.id.name);
v.phone = (TextView) view.findViewById(R.id.no);
v.imageView = (RoundedImageView) view.findViewById(R.id.pic);
v.firstChar = (TextView) view.findViewById(R.id.tv_firstChae);
view.setTag(v);
}
v = (ViewHolder)view.getTag();
final ContactBean data = contactBeans.get(i);
v.title.setText(data.getName());
v.phone.setText(data.getPhone());
// Set image if exists
try {
if (data.getThumb() != null) {
v.firstChar.setVisibility(View.GONE);
v.imageView.setVisibility(View.VISIBLE);
v.imageView.setImageBitmap(data.getThumb());
} else {
v.imageView.setVisibility(View.GONE);
String headerChar = (String) data.getName().subSequence(0, 1);
v.firstChar.setText(headerChar);
}
} catch (OutOfMemoryError e) {
// Add default picture
// v.imageView.setImageDrawable(this.context.getDrawable(R.mipmap.ic_launcher));
e.printStackTrace();
}
Log.e("Image Thumb", "--------------" + data.getThumb());
return view;
}
static class ViewHolder {
RoundedImageView imageView;
TextView title, phone, firstChar;
}
}
You should only initialize your viewHolder once, and thats when your convertView is null. Place this:
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.contact_list_item, null);
v = new ViewHolder();
convertView.setTag(v);
} else {
v = convertView.getTag();
}
Check this link for better understanding. It's from Google. Starts at about minute 6:00
https://www.youtube.com/watch?v=wDBM6wVEO70
Remove the global ViewHolder
ViewHolder v;
The scope of ViewHolder instance have to be inside the getView method only not whole adapter.
Replace the
v = new ViewHolder();
with
ViewHolder v = new ViewHolder();
here i cannot find any use of viewHolder actually,
you can simply try like this
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.contact_list_item, null);
Log.e("Inside", "here--------------------------- In view1");
TextView title = (TextView) view.findViewById(R.id.name);
TextView phone = (TextView) view.findViewById(R.id.no);
RoundedImageView imageView = (RoundedImageView) view.findViewById(R.id.pic);
TextView firstChar = (TextView) view.findViewById(R.id.tv_firstChae);
final ContactBean data = contactDataList.get(i);
title.setText(contactDataList.get(i).getName());
phone.setText(contactDataList.get(i).getPhone());
// Set image if exists
try {
if (contactDataList.get(i).getThumb() != null) {
firstChar.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
imageView.setImageBitmap(data.getThumb());
} else {
imageView.setVisibility(View.GONE);
String headerChar = (String) contactDataList.get(i).getName().subSequence(0, 1);
firstChar.setText(headerChar);
}
} catch (OutOfMemoryError e) {
// Add default picture
// v.imageView.setImageDrawable(this.context.getDrawable(R.mipmap.ic_launcher));
e.printStackTrace();
}
Log.e("Image Thumb", "--------------" + contactDataList.get(i).getThumb());
} else {
view = convertView;
Log.e("Inside", "here--------------------------- In view2");
}
return view;
}
Your simply missing to set the character visible, due to it possibly being invisible from being recycled.
The correct code (containing Ricardo Barroca's improvment):
public class ContactListAdapter extends BaseAdapter {
private List<ContactBean> contactDataList;
private ArrayList<ContactBean> arraylist;
Context context;
ViewHolder v;
public ContactListAdapter(List<ContactBean> contactBeans, Context context) {
contactDataList = contactBeans;
this.context = context;
this.arraylist = new ArrayList<ContactBean>();
this.arraylist.addAll(contactDataList);
}
#Override
public int getCount() {
return contactDataList.size();
}
#Override
public Object getItem(int i) {
return contactDataList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
ViewHolder v;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.contact_list_item, null);
v = new ViewHolder();
convertView.setTag(v);
} else {
v = convertView.getTag();
}
View view = convertView;
v.title = (TextView) view.findViewById(R.id.name);
v.phone = (TextView) view.findViewById(R.id.no);
v.imageView = (RoundedImageView) view.findViewById(R.id.pic);
v.firstChar = (TextView) view.findViewById(R.id.tv_firstChae);
final ContactBean data = contactDataList.get(i);
v.title.setText(contactDataList.get(i).getName());
v.phone.setText(contactDataList.get(i).getPhone());
// Set image if exists
try {
if (contactDataList.get(i).getThumb() != null) {
v.firstChar.setVisibility(View.GONE);
v.imageView.setVisibility(View.VISIBLE);
v.imageView.setImageBitmap(data.getThumb());
} else {
v.imageView.setVisibility(View.GONE);
String headerChar = (String) contactDataList.get(i).getName().subSequence(0, 1);
v.firstChar.setVisibility(View.VISIBLE);
v.firstChar.setText(headerChar);
}
} catch (OutOfMemoryError e) {
// Add default picture
// v.imageView.setImageDrawable(this.context.getDrawable(R.mipmap.ic_launcher));
e.printStackTrace();
}
Log.e("Image Thumb", "--------------" + contactDataList.get(i).getThumb());
view.setTag(data);
return view;
}
static class ViewHolder {
RoundedImageView imageView;
TextView title, phone, firstChar;
}
}
Related
I am using retrofit 2.0 and This code is part of my fragment and adapter. I don't get values from this method because of asyn. Values are date, soup, maindinner, thirdkind, fourtkind, fifthkind. I want to add them in mylistview. How can I get this values. I want to show them on listview.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_dining, container, false);
rowItemDinings = new ArrayList<RowItemDining>();
DiningInterface diningInterface = RetroClient.getClient().create(DiningInterface.class);
Call<Dining[]> call = diningInterface.getJsonValues();
call.enqueue(new Callback<Dining[]>()
{
#Override
public void onResponse(Call<Dining[]> call, Response<Dining[]> response)
{
dinings = Arrays.asList(response.body());
cacheVersion = dinings.get(0).cacheVersion;
for(int i=0; i<dinings.size(); i++)
{
date.add(dinings.get(i).date);
soup.add(dinings.get(i).soup);
mainDinner.add(dinings.get(i).mainDinner);
thirdKind.add(dinings.get(i).thirdKind);
fourthKind.add(dinings.get(i).fourthKind);
fifthKind.add(dinings.get(i).fifthKind);
RowItemDining item = new RowItemDining(date.get(i), soup.get(i), mainDinner.get(i), thirdKind.get(i), fourthKind.get(i), fifthKind.get(i));
rowItemDinings.add(item);
}
//Toast.makeText(getActivity(), "This is my date! " + soup.get(0) + "" + soup.get(4)+ "" + soup.get(5) + soup.get(6)+ "" + soup.get(7), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<Dining[]> call, Throwable t)
{
Log.e(TAG, "Error: " + t.toString());
}
});
mylistview = (ListView) getView().findViewById(R.id.dining_list);
CustomAdapterDining adapter = new CustomAdapterDining(getActivity(), rowItemDinings);
mylistview.setAdapter(adapter);
return view;
}
CustomAdapterDining.java
public class CustomAdapterDining extends BaseAdapter
{
Context context;
List<RowItemDining> rowItemDinings;
List<RowItemDining> data;
public ListView mylistview;
public CustomAdapterDining( List<RowItemDining> rowItemDinings)
{
this.rowItemDinings = rowItemDinings;
}
public CustomAdapterDining(Context context, List<RowItemDining> rowItemDinings)
{
this.context = context;
this.rowItemDinings = rowItemDinings;
}
#Override
public int getCount()
{
return rowItemDinings.size();
}
#Override
public Object getItem(int position)
{
return rowItemDinings.get(position);
}
#Override
public long getItemId(int position)
{
return rowItemDinings.indexOf(getItem(position));
}
/* private view holder class */
private class ViewHolder
{
TextView date;
TextView soup;
TextView mainDinner;
TextView thirdKind;
TextView fourthKind;
TextView fifthKind;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_row_dining, null);
holder = new ViewHolder();
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.soup = (TextView) convertView.findViewById(R.id.soup);
holder.mainDinner = (TextView) convertView.findViewById(R.id.main_dinner);
holder.thirdKind = (TextView) convertView.findViewById(R.id.third_kind);
holder.fourthKind = (TextView) convertView.findViewById(R.id.fourth_kind);
holder.fifthKind = (TextView) convertView.findViewById(R.id.fifth_kind);
RowItemDining row_pos = rowItemDinings.get(position);
holder.date.setText(row_pos.getDate());
holder.soup.setText(row_pos.getSoup());
holder.mainDinner.setText(row_pos.getMainDinner());
holder.thirdKind.setText(row_pos.getThirdKind());
holder.fourthKind.setText(row_pos.getFourthKind());
holder.fifthKind.setText(row_pos.getFifthKind());
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
return convertView;
because the request turn in background and the response will be after the Adapter initialisation so you need to add in your adapter a setter for data example :
in Adapter
void setData(List<RowItemDining> data){
this.data=data;
notifyDataSetChanged();
}
in fragment :
mylistview = (ListView) view.findViewById(R.id.dining_list);
CustomAdapterDining adapter = new CustomAdapterDining(getActivity(), rowItemDinings);
mylistview.setAdapter(adapter);
call.enqueue(new Callback<Dining[]>()
{
#Override
public void onResponse(Call<Dining[]> call, Response<Dining[]> response)
{
dinings = Arrays.asList(response.body());
cacheVersion = dinings.get(0).cacheVersion;
for(int i=0; i<dinings.size(); i++)
{
[...]
}
adapter.setData(rowItemDinings);
}
UPDATE : Add adapter changes
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_row_dining, null);
holder = new ViewHolder();
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.soup = (TextView) convertView.findViewById(R.id.soup);
holder.mainDinner = (TextView) convertView.findViewById(R.id.main_dinner);
holder.thirdKind = (TextView) convertView.findViewById(R.id.third_kind);
holder.fourthKind = (TextView) convertView.findViewById(R.id.fourth_kind);
holder.fifthKind = (TextView) convertView.findViewById(R.id.fifth_kind);
RowItemDining row_pos = rowItemDinings.get(position);
holder.date.setText(row_pos.getDate());
holder.soup.setText(row_pos.getSoup());
holder.mainDinner.setText(row_pos.getMainDinner());
holder.thirdKind.setText(row_pos.getThirdKind());
holder.fourthKind.setText(row_pos.getFourthKind());
holder.fifthKind.setText(row_pos.getFifthKind());
return convertView;
}
I created custom adapter to bind with listview but it's showing duplicate songs in listview. please check out the code and let me know if anything is wrong
public class UnfavoriteSongAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<Media> data;
private static LayoutInflater inflater = null;
private Context context;
public UnfavoriteSongAdapter(Context context, Activity a, ArrayList<Media> d) {
activity = a;
this.context = context;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
GenreFavoriteClickListner genreFavoriteClickListner;
public interface GenreFavoriteClickListner {
public void onFavoriteClickListner(int position,Media media);
}
public void setGenreFavoriteClickListner(GenreFavoriteClickListner genreFavoriteClickListner) {
this.genreFavoriteClickListner = genreFavoriteClickListner;
}
public static class ViewHolder {
public TextView textView_title, textView_artist, textView_time;
public CircleImageView circleImageView_albumphoto, circleImageView_favorite;
public ImageView imageView_play;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder viewHolder;
try {
if (convertView == null) {
viewHolder = new ViewHolder();
final LayoutInflater inflater1 = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater1.inflate(R.layout.song_listitem_layout, null);
viewHolder.textView_title = (TextView) vi.findViewById(R.id.textView_song_songname);
viewHolder.textView_artist = (TextView) vi.findViewById(R.id.textView_song_artistname);
viewHolder.textView_time = (TextView) vi.findViewById(R.id.textView_song_time);
viewHolder.circleImageView_albumphoto = (CircleImageView) vi.findViewById(R.id.circleImageView_nowplaying_playing);
viewHolder.circleImageView_favorite = (CircleImageView) vi.findViewById(R.id.circleImageView_song_favorite);
viewHolder.imageView_play = (ImageView) vi.findViewById(R.id.imageView_song_playpause);
} else {
viewHolder = (ViewHolder) vi.getTag();
}
if (data.size() <= 0) {
//viewHolder.textview_albumtitle.setText("No Appointment");
} else {
final Media p = data.get(position);
viewHolder.textView_title.setText(p.getSongName());
viewHolder.textView_artist.setText(p.getArtistName());
long millis = Long.parseLong(p.getDuration());
String hms = ReusableModules.getCalculatedTime(millis);
viewHolder.textView_time.setText(hms);
String isplaying = p.getIsPlaying();
int playingid = R.mipmap.play;
if (isplaying != null) {
if(isplaying.contentEquals(Constants.ONE)){
playingid = R.mipmap.runing_music_play;
}
}
viewHolder.imageView_play.setImageResource(playingid);
ReusableModules.setFavoriteToggleButton(p.getIsFavorite(), viewHolder.circleImageView_favorite);
viewHolder.circleImageView_favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (genreFavoriteClickListner != null) {
genreFavoriteClickListner.onFavoriteClickListner(position,p);
}
}
});
final String finalUrl = p.getAlbumUrl();
viewHolder.circleImageView_albumphoto.post(new Runnable() {
#Override
public void run() {
BaseActivity.imageLoader.displayImage(finalUrl,
viewHolder.circleImageView_albumphoto, SplashScreenActivity.displayImageOptions, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(Bitmap loadedImage) {
}
});
}
});
vi.setTag(p);
}
} catch (Exception e) {
}
return vi;
}
}
Change in getView() method like this.
viewHolder = new ViewHolder();
if (convertView == null) {
final LayoutInflater inflater1 = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
vi = inflater1.inflate(R.layout.song_listitem_layout, null);
viewHolder.textView_title = (TextView) vi.findViewById(R.id.textView_song_songname);
viewHolder.textView_artist = (TextView) vi.findViewById(R.id.textView_song_artistname);
viewHolder.textView_time = (TextView) vi.findViewById(R.id.textView_song_time);
viewHolder.circleImageView_albumphoto = (CircleImageView) vi.findViewById(R.id.circleImageView_nowplaying_playing);
viewHolder.circleImageView_favorite = (CircleImageView) vi.findViewById(R.id.circleImageView_song_favorite);
viewHolder.imageView_play = (ImageView) vi.findViewById(R.id.imageView_song_playpause);
and remove this
else {
viewHolder = (ViewHolder) vi.getTag();
}
in last of getView() method
convertView.setTag(holder);
try this and tell me it works or not?
move
vi.setTag(viewholder);
inside
if(convert==null){
viewHolder = new ViewHolder();
final LayoutInflater inflater1 = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater1.inflate(R.layout.song_listitem_layout, null);
viewHolder.textView_title = (TextView) vi.findViewById(R.id.textView_song_songname);
viewHolder.textView_artist = (TextView) vi.findViewById(R.id.textView_song_artistname);
viewHolder.textView_time = (TextView) vi.findViewById(R.id.textView_song_time);
viewHolder.circleImageView_albumphoto = (CircleImageView) vi.findViewById(R.id.circleImageView_nowplaying_playing);
viewHolder.circleImageView_favorite = (CircleImageView) vi.findViewById(R.id.circleImageView_song_favorite);
viewHolder.imageView_play = (ImageView) vi.findViewById(R.id.imageView_song_playpause);
// here
vi.setTag(viewholder);
}
and remove this:
final String finalUrl = p.getAlbumUrl();
viewHolder.circleImageView_albumphoto.post(new Runnable() {
#Override
public void run() {
BaseActivity.imageLoader.displayImage(finalUrl,
viewHolder.circleImageView_albumphoto, SplashScreenActivity.displayImageOptions, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(Bitmap loadedImage) {
}
});
}
});
remove this **vi.setTag(p);**
Add vi.setTag(p) inside :
if(convertView == null){
vi.setTag(p);
}
set tag for view holder if view holder null. Add last line of code
if (convertView == null) {
viewHolder = new ViewHolder();
final LayoutInflater inflater1 = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater1.inflate(R.layout.song_listitem_layout, null);
viewHolder.textView_title = (TextView) vi.findViewById(R.id.textView_song_songname);
viewHolder.textView_artist = (TextView) vi.findViewById(R.id.textView_song_artistname);
viewHolder.textView_time = (TextView) vi.findViewById(R.id.textView_song_time);
viewHolder.circleImageView_albumphoto = (CircleImageView) vi.findViewById(R.id.circleImageView_nowplaying_playing);
viewHolder.circleImageView_favorite = (CircleImageView) vi.findViewById(R.id.circleImageView_song_favorite);
viewHolder.imageView_play = (ImageView) vi.findViewById(R.id.imageView_song_playpause);
/************ Set holder with LayoutInflater ************/
vi.setTag( viewHolder );
}
//check you data size getCount,its a good practice. not in getview method.
#Override
public int getCount() {
if(data!=null && data.size()> 0)
return data.size();
else
return 0;
}
I suggest you to replace getview method and check you data once because your adapter code seems perfect.
I want to set the visibility to true of btnProductDetailMinus to true on click of btnProductDetailAddToCart. This is my code.
public class ProductVariantAdapter extends BaseAdapter {
private Context context;
private ArrayList<ProductVariant> productVariants = new ArrayList<>();
/*private view holder class*/
private class ViewHolder {
TextView productVariantName;
TextView productVariantMrp;
TextView productVariantSellPrice;
Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailQty, btnProductDetailMinus;
}
public ProductVariantAdapter(Context context, ArrayList<ProductVariant> productVariants) {
this.context = context;
this.productVariants = productVariants;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listview_product_variant, null);
holder = new ViewHolder();
holder.productVariantName = (TextView) convertView.findViewById(R.id.productVariantName);
holder.productVariantMrp = (TextView) convertView.findViewById(R.id.productVariantMrp);
holder.productVariantSellPrice = (TextView) convertView.findViewById(R.id.productVariantSellPrice);
holder.btnProductDetailAddToCart = (Button) convertView.findViewById(R.id.btnProductDetailAddToCart);
holder.btnProductDetailPlus = (Button)convertView.findViewById(R.id.btnProductDetailPlus);
holder.btnProductDetailQty = (Button)convertView.findViewById(R.id.btnProductDetailQty);
holder.btnProductDetailMinus = (Button)convertView.findViewById(R.id.btnProductDetailMinus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ProductVariant productVariant = (ProductVariant) getItem(position);
if (productVariant != null) {
holder.productVariantName.setText(productVariant.getVariant().getVariantName());
holder.productVariantMrp.setText(productVariant.getMrp().toString());
holder.productVariantSellPrice.setText(productVariant.getSellPrice().toString());
holder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Utility.displayToast("wonderful");
holder.btnProductDetailMinus.setVisibility(View.VISIBLE);
}
});
} else {
Toast.makeText(context, "product variant is null", Toast.LENGTH_SHORT).show();
}
return convertView;
}
#Override
public int getCount() {
return productVariants.size();
}
#Override
public Object getItem(int position) {
return productVariants.get(position);
}
#Override
public long getItemId(int position) {
return productVariants.indexOf(getItem(position));
}
}
But its giving error "Variable holder is accessed from within inner class. needs to declared final"
This is the line giving error.
holder.btnProductDetailMinus.setVisibility(View.VISIBLE);
How to fix this?
Assign holder tot a final variabele:
final ViewHolder fHolder = holder;
Then in onClick:
fHolder.btnProductDetailMinus.setVisibility(View.VISIBLE);
Move this line out of the if (convertView == null)
holder = new ViewHolder();
You can declare final ViewHolder holder = null; instead of ViewHolder holder = null;
You can just make it a Global variable.
set public static class ViewHolder instead of private class ViewHolder
One of the approach that I follow is create a Map or List in Adapter class and onClick set value and that collection, and in adapter getView method check for the collection value. .
Checkout the below code.
public class ProductVariantAdapter extends BaseAdapter {
private Context context;
private ArrayList<ProductVariant> productVariants = new ArrayList<>();
private Map<Integer, Boolean> visibilityMap = new HashMap<>();
/*private view holder class*/
private class ViewHolder {
TextView productVariantName;
TextView productVariantMrp;
TextView productVariantSellPrice;
Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailQty, btnProductDetailMinus;
}
public ProductVariantAdapter(Context context, ArrayList<ProductVariant> productVariants) {
this.context = context;
this.productVariants = productVariants;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listview_product_variant, null);
holder = new ViewHolder();
holder.productVariantName = (TextView) convertView.findViewById(R.id.productVariantName);
holder.productVariantMrp = (TextView) convertView.findViewById(R.id.productVariantMrp);
holder.productVariantSellPrice = (TextView) convertView.findViewById(R.id.productVariantSellPrice);
holder.btnProductDetailAddToCart = (Button) convertView.findViewById(R.id.btnProductDetailAddToCart);
holder.btnProductDetailPlus = (Button)convertView.findViewById(R.id.btnProductDetailPlus);
holder.btnProductDetailQty = (Button)convertView.findViewById(R.id.btnProductDetailQty);
holder.btnProductDetailMinus = (Button)convertView.findViewById(R.id.btnProductDetailMinus);
holder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
Utility.displayToast("wonderful");
visibilityMap.put(position, true);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.btnProductDetailAddToCart.setTag(position);
ProductVariant productVariant = (ProductVariant) getItem(position);
if (productVariant != null) {
holder.productVariantName.setText(productVariant.getVariant().getVariantName());
holder.productVariantMrp.setText(productVariant.getMrp().toString());
holder.productVariantSellPrice.setText(productVariant.getSellPrice().toString());
} else {
Toast.makeText(context, "product variant is null", Toast.LENGTH_SHORT).show();
}
if(visibilityMap.containsKey(position) && visibilityMap.get(position)){
holder.btnProductDetailMinus.setVisibility(View.VISIBLE);
}else{
holder.btnProductDetailMinus.setVisibility(View.GONE);
}
return convertView;
}
#Override
public int getCount() {
return productVariants.size();
}
#Override
public Object getItem(int position) {
return productVariants.get(position);
}
#Override
public long getItemId(int position) {
return productVariants.indexOf(getItem(position));
}
}
I need a code to deal with an item in array inside a spinner to allow me to check
.....
if(item == "item name"){
do something
}
or
if(item.position == 1){
do something
}
You can change in adapter like this code
public class PlannedRideAdapter extends BaseAdapter {
// private LayoutInflater mInflater;
private Context context;
private RideData rideData = new RideData();
private List<RideData> ride_data;
public PlannedRideAdapter(Context context, List<RideData> ridedata) {
this.context = context;
this.ride_data = ridedata;
}
#Override
public int getCount() {
if (ride_data.size() > 0) {
return ride_data.size();
}
return 1;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewholder;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.plannedride_km_list, null);
viewholder = new ViewHolder();
convertView.setTag(viewholder);
} else {
viewholder = (ViewHolder) convertView.getTag();
}
rideData = ride_data.get(position);
// init view
viewholder.imageView = (ImageView) convertView
.findViewById(R.id.imageView1);
viewholder.date = (TextView) convertView.findViewById(R.id.date_value);
viewholder.source = (CustomFontTextView) convertView
.findViewById(R.id.source_icon);
viewholder.time = (TextView) convertView.findViewById(R.id.time_value);
viewholder.destination = (CustomFontTextView) convertView
.findViewById(R.id.dest_icon);
viewholder.rideId = (CustomFontTextView) convertView
.findViewById(R.id.rideId);
viewholder.ride_id = (TextView) convertView
.findViewById(R.id.rideIdText);
viewholder.distance = (CustomFontTextView) convertView
.findViewById(R.id.distance);
viewholder.source_value = (TextView) convertView
.findViewById(R.id.source_value);
viewholder.ride_id_value = (TextView) convertView
.findViewById(R.id.rideId_value);
viewholder.distance_value = (TextView) convertView
.findViewById(R.id.distance_value);
// viewholder.ride_detail = (TextView) convertView
// .findViewById(R.id.textRideDetail);
// setview
viewholder.date.setText("" + rideData.getDate());
viewholder.source.setText(context.getResources().getString(
R.string.font_awesome_marker_icon));
viewholder.source_value.setText("" + rideData.getSource());
viewholder.time.setText("" + rideData.getTime());
viewholder.rideId.setText(context.getResources().getString(
R.string.font_awesome_bookingnumber_icon));
viewholder.ride_id_value.setText("" + rideData.getRideId());
if (rideData.getRideType().equalsIgnoreCase("k")) {
viewholder.distance.setVisibility(View.VISIBLE);
viewholder.distance_value.setVisibility(View.VISIBLE);
viewholder.imageView.setImageResource((R.drawable.one_way));
viewholder.destination.setText(context.getResources().getString(
R.string.font_awesome_radio_tick_icon));
viewholder.distance.setText(context.getResources().getString(
R.string.font_awesome_distance_icon));
viewholder.distance_value.setText(""
+ rideData.getKilometerRide().getDestination());
} else {
viewholder.imageView.setImageResource((R.drawable.time));
viewholder.destination.setText(context.getResources().getString(
R.string.font_awesome_clock_icon));
viewholder.distance.setVisibility(View.GONE);
viewholder.distance_value.setVisibility(View.GONE);
// viewholder.ride_detail.setVisibility(View.GONE);
}
return convertView;
}
public List<RideData> getRide_data() {
return ride_data;
}
public void setRide_data(List<RideData> ride_data) {
this.ride_data = ride_data;
}
public static class ViewHolder {
public CustomFontTextView source;
public CustomFontTextView destination;
public CustomFontTextView rideId;
public CustomFontTextView distance;
public CustomFontTextView total_time;
public TextView date, time, distance_value, source_value,
destination_value, time_value, ride_id_value, ride_id;
public ImageView imageView;
}
}
I am showing list based on kilometer(rideType k) or hourly (rideType h) with same layout.
I have Implemented a ListView which loads news, but news changes position when I scroll the list. this is list
public class ListNewsFragment extends SherlockListFragment{
private ListNewsAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
mAdapter = new ListNewsAdapter(this, app.getAllNews());
setListAdapter(mAdapter);
super.onCreate(savedInstanceState);
}
}
public class ListNewsAdapter extends BaseAdapter{
private List<News> news;
private Context mContext;
private LayoutInflater inflater;
private ViewHolder holder;
public ListNewsAdapter(final Fragment c, List<News> news) {
super();
this.news = news;
this.mContext = c.getActivity();
inflater = LayoutInflater.from(mContext);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
v = inflater.inflate(R.layout.fragment_list_news, null);
holder.name = (TextView) v.findViewById(R.id.tittle);
holder.tweet = (TextView) v.findViewById(R.id.news);
holder.avatar = (ImageView) v.findViewById(R.id.image);
holder.name.setText(news.get(position).getTitulo());
holder.tweet.setText(news.get(position).getCopete());
new ImagefetcherTask(position).execute(holder);
v.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return v;
}
private class ViewHolder{
public TextView name, tweet;
public ImageView avatar;
}
private class ImagefetcherTask extends AsyncTask<ViewHolder, Void, ViewHolder> {
private Bitmap bitmap;
int position;
public ImagefetcherTask(int position) {
this.position = position;
}
#Override
protected ViewHolder doInBackground(ViewHolder... params) {
ViewHolder viewHolder = params[0];
try{
bitmap = BitmapFactory.decodeStream((InputStream) new URL("...."+ news.get(position).getImagen().toString()).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return viewHolder;
}
#Override
protected void onPostExecute(ViewHolder result) {
// TODO Auto-generated method stub
if (bitmap == null) {
result.avatar.setImageResource(com.dev.suma_intranet_v1.R.drawable.img_perfil);
} else {
result.avatar.setImageBitmap(bitmap);
}
}
}
}
Change your getView() method to this:
Map<Integer, View> views = new HashMap<Integer, View>;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (views.containsKey(position)) {
return views.get(position);
}
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
View v = inflater.inflate(R.layout.fragment_list_news, null);
holder.name = (TextView) v.findViewById(R.id.tittle);
holder.tweet = (TextView) v.findViewById(R.id.news);
holder.avatar = (ImageView) v.findViewById(R.id.image);
holder.name.setText(news.get(position).getTitulo());
holder.tweet.setText(news.get(position).getCopete());
new ImagefetcherTask(position).execute(holder);
v.setTag(holder);
views.put(position, v);
return v;
}
Call your ImageFetcher and TextView.seText after your else statement so that when the convertView isn't null and has been recycled, you're updating your row:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
v = inflater.inflate(R.layout.fragment_list_news, null);
holder.name = (TextView) v.findViewById(R.id.tittle);
holder.tweet = (TextView) v.findViewById(R.id.news);
holder.avatar = (ImageView) v.findViewById(R.id.image);
v.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(news.get(position).getTitulo());
holder.tweet.setText(news.get(position).getCopete());
new ImagefetcherTask(position).execute(holder);
return v;
}
I have fixed this by overriding these two methods in my adapter class.
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
Try to do lazy load an image by using this Universal image loader library. and try to catch image.
so as per this answer set the bitmap options as
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.build();
I am sure this will solve your problem