How to deal with an array item from a spinner? - android

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.

Related

ListView to RecyclerView conversion, problem in converting get View method

I want to convert Listview to RecyclerView in my app, I tried to convert code but stucked at getView method, can any one explain how to use this getView code in Recylcer view.
Adapter for ListView CardAdapter.java
public class CardAdapter extends ArrayAdapter<CardDataModel> {
private Context context;
List<CardDataModel> cards;
SharedPreference sharedPreference;
public CardAdapter(Context context, List<CardDataModel> cards) {
super(context, R.layout.card_list_item, cards);
this.context = context;
this.cards = cards;
sharedPreference = new SharedPreference();
}
private class ViewHolder {
TextView CardNameTxt;
TextView CardDescTxt;
TextView CardPriceTxt;
ImageView favoriteImg;
}
#Override
public int getCount() {
return cards.size();
}
#Override
public CardDataModel getItem(int position) {
return cards.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.card_list_item, null);
holder = new ViewHolder();
holder.CardNameTxt = (TextView) convertView
.findViewById(R.id.txt_crd_name);
holder.CardDescTxt = (TextView) convertView
.findViewById(R.id.txt_crd_desc);
holder.CardPriceTxt = (TextView) convertView
.findViewById(R.id.txt_crd_no);
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.imgbtn_favorite);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
CardDataModel card = (CardDataModel) getItem(position);
holder.CardNameTxt.setText(card.getName());
holder.CardDescTxt.setText(card.getDescription());
holder.CardPriceTxt.setText(card.getPrice() + " ");
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(card)) {
holder.favoriteImg.setImageResource(R.drawable.heart_red);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.heart_grey);
holder.favoriteImg.setTag("grey");
}
return convertView;
}
public boolean checkFavoriteItem(CardDataModel checkCard) {
boolean check = false;
List<CardDataModel> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (CardDataModel card : favorites) {
if (card.equals(checkCard)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(CardDataModel card) {
super.add(card);
cards.add(card);
notifyDataSetChanged();
}
#Override
public void remove(CardDataModel card) {
super.remove(card);
cards.remove(card);
notifyDataSetChanged();
}
}
converted somecode like this in RecyclerView Adapter ... CardRvAdapter.java
public class CardRvAdapter extends RecyclerView.Adapter<CardRvAdapter.MyViewHolder> {
private Context context;
List<CardDataModel> cards;
SharedPreference sharedPreference;
public CardRvAdapter(Context context, List<CardDataModel> cards) {
this.context = context;
this.cards = cards;
sharedPreference = new SharedPreference(); }
#Override
public int getItemCount() {
return cards.size();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
// on create view holder code
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.card_list_item, viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
//on bind view holder code
myViewHolder.CardPriceTxt.setText(cards.get(i).getPrice());
myViewHolder.CardNameTxt.setText(cards.get(i).getName());
myViewHolder.CardDescTxt.setText(cards.get(i).getDescription());
if (checkFavoriteItem(card)) {
myViewHolder.favoriteImg.setImageResource(R.drawable.heart_red);
myViewHolder.favoriteImg.setTag("red");
} else {
myViewHolder.favoriteImg.setImageResource(R.drawable.heart_grey);
myViewHolder.favoriteImg.setTag("grey");
} }
// checking for favotites in shared preferences
public boolean checkFavoriteItem(CardDataModel checkCard) {
boolean check = false;
List<CardDataModel> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (CardDataModel card : favorites) {
if (card.equals(checkCard)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(CardDataModel card) {
super.add(card);
cards.add(card);
notifyDataSetChanged();
}
#Override
public void remove(CardDataModel card) {
super.remove(card);
cards.remove(card);
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView CardNameTxt;
TextView CardDescTxt;
TextView CardPriceTxt;
ImageView favoriteImg;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
this.CardDescTxt = (TextView) itemView.findViewById(R.id.txt_crd_desc);
this.CardNameTxt = (TextView) itemView.findViewById(R.id.txt_crd_name);
this.CardPriceTxt = (TextView) itemView.findViewById(R.id.txt_crd_no);
this.favoriteImg = (ImageView) itemView.findViewById(R.id.imgbtn_favorite);
}}}
The problem part..
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.card_list_item, null);
holder = new ViewHolder();
holder.CardNameTxt = (TextView) convertView
.findViewById(R.id.txt_crd_name);
holder.CardDescTxt = (TextView) convertView
.findViewById(R.id.txt_crd_desc);
holder.CardPriceTxt = (TextView) convertView
.findViewById(R.id.txt_crd_no);
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.imgbtn_favorite);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
CardDataModel card = (CardDataModel) getItem(position);
holder.CardNameTxt.setText(card.getName());
holder.CardDescTxt.setText(card.getDescription());
holder.CardPriceTxt.setText(card.getPrice() + " ");
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(card)) {
holder.favoriteImg.setImageResource(R.drawable.heart_red);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.heart_grey);
holder.favoriteImg.setTag("grey");
}
return convertView;
}
How to modify this code and where to add this checkFavItem, add , and remove methods..suggest me , i am new to android development.
Finishing RecyclerView Code
// specify the row layout file and click for each row
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(listItemLayout, parent, false);
ViewHolder myViewHolder = new ViewHolder(view);
return myViewHolder;
}
// load data in each row element
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView item = holder.item;
item.setText(itemList.get(listPosition).getName());
}

Get data from Async for Retrofit 2.0

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;
}

getting wrong data after scrolling listview in android

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;
}
}

Why Listview showing duplicate entries with custom adapter android?

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.

How to set visibility true of one button onclick of another button in listView - android

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));
}
}

Categories

Resources