I have a ListView that fill from Sqlite . But when I fill the ListView I see Duplicate Data.
My Struct.class :
public class Struct{
public String IdS;
public String NameS;
public String Group;
}
My Activity.class :
ArrayAdapter adapter = new AdapterPSK(MPSK, activity, width, context);
ListView lstPa = (ListView) findViewById(R.id.lstPasokhgoo);
lstPa.setAdapter(adapter);
Struct stp = new Struct();
cursor_Sharee = sql.rawQuery("SELECT ID_P,Name_P,Group_P FROM ChatPasokhgo_tbl where Group_P = '" + "LOL" + "'", null);
try {
if (cursor_Sharee != null) {
if (cursor_Sharee.moveToFirst()) {
do {
stp.IdS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("ID_P"));
stp.NameS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Name_P"));
stp.Group = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Group_P"));
MPSK.add(stp);
} while (cursor_Sharee.moveToNext());
}
}
} catch (Exception e) {
// TODO: handle exception
}finally{
cursor_Sharee.close();
}
adapter.notifyDataSetChanged();
MPSK is:
public ArrayList<Struct> MPSK = new ArrayList<Struct>();
My AdapterPSK.class :
public class AdapterPSK extends ArrayAdapter<Struct> {
static boolean enable = true;
static Activity activity;
static int widths;
public AdapterPSK(ArrayList<Struct> array,Activity act,int WIDTH,Context context) {
super(context, R.layout.chat_page, array);
activity = act;
widths = WIDTH;
}
public ViewHolder(View view)
{
txtName = (TextView) view.findViewById(R.id.txtname);
layoutRoot = (ViewGroup) view.findViewById(R.id.layoutRoot);
txtname = (TextView) view.findViewById(R.id.txtname);
}
public void fill(ArrayAdapter<Struct> arrayAdapter,final Struct item , int position)
{
MarginLayoutParams txtN = (MarginLayoutParams) txtname.getLayoutParams();
txtN.rightMargin = MarginRight;
txtname.setTextSize(TextSize);
if (item.NameS != null) {
txtName.setText(item.NameS);
}else if(item.NameE != null){
txtName.setText(item.NameE);
}
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Struct item = getItem(position);
if(convertView == null)
{
convertView = G.inflater.inflate(R.layout.adapter_pasokhgoo,parent,false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
Notice : ListView show me last row of sqlite . But when I get Log see all of fetching data .My Query is true . My bug is from MPSK .
Your Struct stp = new Struct(); should be in :
do {
Struct stp = new Struct();
.....
......
} while (cursor_Sharee.moveToNext());
;)
Clear MPSK after retrieving cursor.. as
cursor_Sharee = sql.rawQuery("SELECT ID_P,Name_P,Group_P FROM ChatPasokhgo_tbl where Group_P = '" + "LOL" + "'", null);
MPSK.clear();
try
{
.....
Change this
if (cursor_Sharee != null) {
if (cursor_Sharee.moveToFirst()) {
do {
stp.IdS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("ID_P"));
stp.NameS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Name_P"));
stp.Group = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Group_P"));
MPSK.add(stp);
} while (cursor_Sharee.moveToNext());
}
To
if (cursor_Sharee != null)
{
while(cursor_Sharee.moveToNext())
{
stp.IdS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("ID_P"));
stp.NameS = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Name_P"));
stp.Group = cursor_Sharee.getString(cursor_Sharee.getColumnIndex("Group_P"));
MPSK.add(stp);
}
}
Related
I found some problem with my custom gridview adapter, i was adding positions from 1 to 10.
Everything is correct till number 6, after that instead of showing number 7 / 8 it shows number 2 and 1.
I have no idea whats wrong.
I'm newbie and I would appreciate for every help. Thanks
Here is a picture of a problem.
Here is code from gridview adapter
public class GvOrdersAdapter extends BaseAdapter
{
private Context context;
private final String[] nameValues;
private final String[] danieValues;
private final String[] danie2Values;
private final String[] zupaValues;
private final String[] statusValues;
GvOrdersAdapter(Context context, String[] nameValues, String[] danieValues, String[] danie2Values,
String[] zupaValues, String[] statusValues)
{
this.context = context;
this.nameValues = nameValues;
this.danieValues = danieValues;
this.danie2Values = danie2Values;
this.zupaValues = zupaValues;
this.statusValues = statusValues;
}
#SuppressLint({"ResourceAsColor", "SetTextI18n", "InflateParams"})
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null)
{
// get layout from mobile.xml
assert inflater != null;
gridView = inflater.inflate(R.layout.gv_ordered_list, null);
// set value into textview
TextView tvName = gridView.findViewById(R.id.tvName);
TextView tvDanie = gridView.findViewById(R.id.tvDanieGlowne);
TextView tvDanie2 = gridView.findViewById(R.id.tvDodatki);
TextView tvZupa = gridView.findViewById(R.id.tvZupa);
TextView tvStatus = gridView.findViewById(R.id.tvStatus);
tvName.setText(nameValues[position]);
tvDanie.setText((danieValues[position]));
tvDanie2.setText((danie2Values[position]));
tvZupa.setText((zupaValues[position]));
if (statusValues[position].contains("Poczekaj na akceptacje zamówienia"))
{
tvStatus.setText((statusValues[position]) + "\n");
}
else if (statusValues[position].contains("Przyjęto, w trakcie realizacji"))
{
tvStatus.setText((statusValues[position])+"\n");
tvStatus.setTextColor(context.getResources().getColor(R.color.ordered_wait_for_accept));
}
else if (statusValues[position].contains("W transporcie"))
{
tvStatus.setText((statusValues[position])+"\n");
tvStatus.setTextColor(context.getResources().getColor(R.color.ordered_accepted));
}
else if (statusValues[position].contains("Dostarczone"))
{
tvStatus.setText((statusValues[position])+"\n");
tvStatus.setTextColor(context.getResources().getColor(R.color.colorPrimary));
}
} else
{
gridView = convertView;
}
return gridView;
}
#Override
public int getCount()
{
return nameValues.length;
}
#Override
public Object getItem(int position)
{
return null;
}
public boolean isEnabled(int position)
{
return true;
}
#Override
public long getItemId(int position) {
return position;
}
}
collecting data from firebase from activity
private void ZlozoneZamowieniaList() {
DatabaseReference ordered = FirebaseDatabase.getInstance().getReference().child("Złożone zamówienia");
ordered.child(thisYear)
.child(thisMonth)
.child(thisDay)
.child(Firma)
.orderByChild("name")
.equalTo(id)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
ClearLists(); //WYCZYŚĆ LISTY
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
String imie = snapshot.child("imie").getValue(String.class);
String danie = snapshot.child("danie").getValue(String.class);//ITD
String dodatek = snapshot.child("dodatek").getValue(String.class);//ITD
String zupa = snapshot.child("zupa").getValue(String.class);//ITD
String id = snapshot.child("informacjeDlaObslugi").getValue(String.class);//ITD
String gotKey = snapshot.child("key").getValue(String.class);//ITD
String status = snapshot.child("status").getValue(String.class);//ITD
if (status != null && !status.contains("Zamówienie anulowane przez klienta"))
{
mListName.add(imie);
if (danie != null)
{
mListDish.add(danie);
}else
{
mListDish.add(" ");
}
if (dodatek != null)
{
mListDish2.add(dodatek);
} else {
mListDish2.add(" ");
}
if (zupa != null)
{
mListSoup.add(zupa);
} else {
mListSoup.add(" ");
}
if (id != null)
{
mListInfo.add(id);
} else {
mListInfo.add(" ");
}
mListStatus.add(status);
keyList.add(gotKey);
}
String[] sListName = mListName.toArray(new String[0]);
String[] sListDish = mListDish.toArray(new String[0]);
String[] sListDish2 = mListDish2.toArray(new String[0]);
String[] sListSoup = mListSoup.toArray(new String[0]);
String[] sListStatus = mListStatus.toArray(new String[0]);
GvOrdersAdapter GvAdapter = new GvOrdersAdapter(getContext(), sListName, sListDish,
sListDish2, sListSoup, sListStatus);
gvOrderedMeals.setAdapter(GvAdapter);
GvClear();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
data are collected properly, becouse when i create alertdaliog after clicking at gridview it shows me correct data.
Your problem was that if convertView was NOT null you never updated its text views but in following code it will always update
change getView() like this:
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//<----------------------- add following line
View gridView = convertView == null ? inflater.inflate(R.layout.gv_ordered_list, null) : convertView
//<----------------------- "if else" is removed from your code
// get layout from mobile.xml
assert inflater != null;
gridView = inflater.inflate(R.layout.gv_ordered_list, null);
// set value into textview
TextView tvName = gridView.findViewById(R.id.tvName);
TextView tvDanie = gridView.findViewById(R.id.tvDanieGlowne);
TextView tvDanie2 = gridView.findViewById(R.id.tvDodatki);
TextView tvZupa = gridView.findViewById(R.id.tvZupa);
TextView tvStatus = gridView.findViewById(R.id.tvStatus);
tvName.setText(nameValues[position]);
tvDanie.setText((danieValues[position]));
tvDanie2.setText((danie2Values[position]));
tvZupa.setText((zupaValues[position]));
if (statusValues[position].contains("Poczekaj na akceptacje zamówienia"))
{
tvStatus.setText((statusValues[position]) + "\n");
}
else if (statusValues[position].contains("Przyjęto, w trakcie realizacji"))
{
tvStatus.setText((statusValues[position])+"\n");
tvStatus.setTextColor(context.getResources().getColor(R.color.ordered_wait_for_accept));
}
else if (statusValues[position].contains("W transporcie"))
{
tvStatus.setText((statusValues[position])+"\n");
tvStatus.setTextColor(context.getResources().getColor(R.color.ordered_accepted));
}
else if (statusValues[position].contains("Dostarczone"))
{
tvStatus.setText((statusValues[position])+"\n");
tvStatus.setTextColor(context.getResources().getColor(R.color.colorPrimary));
}
return gridView;
}
I am working on a chat app and I am very new to using ListViews and ArrayAdapters, as well as Custom Adapters. I am having a problem that causes all my items in my list to be of one layout, even they are supposed to change according to a booleans(true would be an outgoing chat bubble, and false would be an incoming chat bubble).
Here is my code for the retreival of the chat(It isn't the whole file, just a snippet):
Variable declarations:
final ArrayList<chatBubble> objects = new ArrayList<>();
final CustomAdapter customAdapter = new CustomAdapter(this, objects);
listView.setAdapter(customAdapter);
Code to get messages and add to list:
mDatabase.child("chat").child("publicDump").child("dumpedMessages").child("message" + i).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String message = dataSnapshot.getValue(String.class);
if (message != null) {
final String extract = message.substring(message.lastIndexOf("<") + 1, message.indexOf(">"));
mDatabase.child("users").child("c").child("emailToUsername").child(mAuth.getCurrentUser().getEmail().replace(".", ",")).child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue(String.class);
if (username != null) {
if (username.equals(extract)) {
Log.i("Extract", extract);
int semicnt = 0;
int num = 0;
//Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, true);
objects.add(chat);
}
}
}
} else {
int semicnt = 0;
int num = 0;
// Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, false);
objects.add(chat);
}
}
}
}
customAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is my code for my chatBubble:
package com.tejasmehta.codeychat;
public class chatBubble {
private String msg;
private String date;
private boolean myMessage;
public chatBubble(String msg, String date, boolean myMessage) {
this.msg = msg;
this.date = date;
this.myMessage = myMessage;
}
public String Msg() {
return msg;
}
public String Date() {
return date;
}
public boolean myMessage() {
return myMessage;
}
}
And here is my code for my customAdapter(which shows that if the boolean, myMessage, is true, it will load a different layout, and a different one for false):
public class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<chatBubble> objects;
private class ViewHolder {
TextView msg;
TextView date;
}
public CustomAdapter(Context context, ArrayList<chatBubble> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public chatBubble getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}
}
Thank You for all of your help!
the problem is your getview
The view is being recycled so convertview already has a layout. so its not being reinflated to the correct layout.
you need to use getViewType() and getViewTypeCount() to tell the listview you want to use different layouts
http://android.amberfog.com/?p=296
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).myMessage()?0:1;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}
I have a listview, a row, two text, and one delete button. I can delete item, but sometimes it's deleting a different item, not clicked.
I checked IDs getting correct to the list. I used Retrofit, and I just respond when I clicked the delete button, and I used notifyDataSetChanged(); for list(setFavoriteMerchant())
public class FavoriteMerchantActivity extends AppCompatActivity implements IButtonCliclListener {
FavoriteMerchantAdapter favoriteMerchantAdapter;
#InjectView(R.id.ListFavoriteMerchant)
ListView ListFavoriteMerchant;
AlertDialogHelper alertDialogHelper;
List<ItemsFavoriteMerchant> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_merchant);
ButterKnife.inject(this);
alertDialogHelper = new AlertDialogHelper(this);
getFavoriteMerchant();
}
#Override
public void onClick(View v) {
int itemIndex = (int) v.getTag();
setFavoriteMerchant(itemIndex);
alertDialogHelper.showAlertSuccess("Removed from your favorites!");
}
void getFavoriteMerchant() {
Call<FavoriteMerchant> call = ToolApi.getApi().getFavoriteMerchant(BaseService.TOKEN);
call.enqueue(new Callback<FavoriteMerchant>() {
#Override
public void onResponse(Response<FavoriteMerchant> response, Retrofit retrofit) {
if (response.body() != null) {
FavoriteMerchant favoriteMerchant = response.body();
Integer errorCode = favoriteMerchant.getStatus().getErrorCode();
if (errorCode == 0) {
list = favoriteMerchant.getItems();
favoriteMerchantAdapter = new FavoriteMerchantAdapter(FavoriteMerchantActivity.this, alertDialogHelper, favoriteMerchant, list, getApplicationContext());
ListFavoriteMerchant.setAdapter(favoriteMerchantAdapter);
}
}
else {
startActivity(getIntent());
alertDialogHelper.showAlertError("Connection error...");
}
}
#Override
public void onFailure(Throwable t) {
startActivity(getIntent());
alertDialogHelper.showAlertError("Connection error...");
}
});
}
void setFavoriteMerchant(final int index) {
Call<SetFavoriteMerchant> call = ToolApi.getApi().setFavoriteMerchant(BaseService.TOKEN, index, true);
call.enqueue(new Callback<SetFavoriteMerchant>() {
#Override
public void onResponse(Response<SetFavoriteMerchant> response, Retrofit retrofit) {
for (ItemsFavoriteMerchant item : list) {
if (item.getID() == index) {
list.remove(item);
favoriteMerchantAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onFailure(Throwable t) {
alertDialogHelper.showAlertError("connection error...");
}
});
}
public class FavoriteMerchantAdapter extends BaseAdapter implements View.OnClickListener {
List<ItemsFavoriteMerchant> itemsFavoriteMerchant;
FavoriteMerchant favoriteMerchant;
Context context;
AlertDialogHelper alertDialogHelper;
private IButtonCliclListener iButtonCliclListener;
public FavoriteMerchantAdapter(IButtonCliclListener iButtonCliclListener, AlertDialogHelper alertDialogHelper, FavoriteMerchant favoriteMerchant, List<ItemsFavoriteMerchant> itemsFavoriteMerchant, Context context) {
this.favoriteMerchant = favoriteMerchant;
this.context = context;
this.itemsFavoriteMerchant = itemsFavoriteMerchant;
this.alertDialogHelper = alertDialogHelper;
this.iButtonCliclListener = iButtonCliclListener;
}
#Override
public int getCount() {
return itemsFavoriteMerchant.size();
}
#Override
public Object getItem(int position) {
return itemsFavoriteMerchant.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FavoriteMerchantAdapter.ViewHolder viewHolder;
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchant.get(position);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
viewHolder = new FavoriteMerchantAdapter.ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_favorite_merchant, null);
viewHolder.FavoriteMerchantPlaceDesc = (TextViewGothamBook) convertView.findViewById(R.id.FavoriteMerchantPlaceDesc);
viewHolder.FavoriteMerchantLocationDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantLocationDesc);
viewHolder.FavoriteMerchantCashDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantCashDesc);
viewHolder.FavoriteMerchantDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantDesc);
viewHolder.FavoriteMerchantLogo = (ImageView) convertView.findViewById(R.id.FavoriteMerchantLogo);
viewHolder.FavoriteMerchantDeleteButton = (ImageButton) convertView.findViewById(R.id.im_btn_deletemerchant);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID());
viewHolder.FavoriteMerchantDeleteButton.setOnClickListener(this);
convertView.setTag(item.getID());
//convertView.setTag(viewHolder);
}
else {
viewHolder = (FavoriteMerchantAdapter.ViewHolder) convertView.getTag();
}
/*
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchants.get(position);
*/
String ImageUrl = item.getCoverPageImageURL();
if (ImageUrl != null && !ImageUrl.isEmpty())
Picasso.with(context)
.load(CDnPath + ImageUrl)
.transform(new CircleTransform())
.into(viewHolder.FavoriteMerchantLogo);
String MerchantPlaceDesc = item.getName();
if (MerchantPlaceDesc != null && !MerchantPlaceDesc.isEmpty())
viewHolder.FavoriteMerchantPlaceDesc.setText(MerchantPlaceDesc);
String MerchantocationDesc = (String) item.getDistrict();
if (MerchantocationDesc != null && !MerchantocationDesc.isEmpty())
viewHolder.FavoriteMerchantLocationDesc.setText(MerchantocationDesc);
String MerchantCashDesc = "";
if (MerchantCashDesc != null && !MerchantCashDesc.isEmpty())
viewHolder.FavoriteMerchantCashDesc.setText(MerchantCashDesc);
return convertView;
}
#Override
public void onClick(View v) {
this.iButtonCliclListener.onClick(v);
}
public static class ViewHolder {
ImageView FavoriteMerchantLogo;
TextViewGothamBook FavoriteMerchantPlaceDesc;
TextViewGothamMedium FavoriteMerchantLocationDesc;
TextViewGothamMedium FavoriteMerchantCashDesc;
TextViewGothamMedium FavoriteMerchantDesc;
ImageButton FavoriteMerchantDeleteButton;
}
}
Use:
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
viewHolder = new FavoriteMerchantAdapter.ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_favorite_merchant, null);
viewHolder.FavoriteMerchantPlaceDesc = (TextViewGothamBook) convertView.findViewById(R.id.FavoriteMerchantPlaceDesc);
viewHolder.FavoriteMerchantLocationDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantLocationDesc);
viewHolder.FavoriteMerchantCashDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantCashDesc);
viewHolder.FavoriteMerchantDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantDesc);
viewHolder.FavoriteMerchantLogo = (ImageView) convertView.findViewById(R.id.FavoriteMerchantLogo);
viewHolder.FavoriteMerchantDeleteButton = (ImageButton) convertView.findViewById(R.id.im_btn_deletemerchant);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID());
viewHolder.FavoriteMerchantDeleteButton.setOnClickListener(this);
convertView.setTag(item.getID());
//convertView.setTag(viewHolder);
}
your setting tags only when convert view is null.
convertView.setTag(item.getID()); // This call should be made to all getview calls.
Solution (check comments):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FavoriteMerchantAdapter.ViewHolder viewHolder;
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchant.get(position);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
viewHolder = new FavoriteMerchantAdapter.ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_favorite_merchant, null);
viewHolder.FavoriteMerchantPlaceDesc = (TextViewGothamBook) convertView.findViewById(R.id.FavoriteMerchantPlaceDesc);
viewHolder.FavoriteMerchantLocationDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantLocationDesc);
viewHolder.FavoriteMerchantCashDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantCashDesc);
viewHolder.FavoriteMerchantDesc = (TextViewGothamMedium) convertView.findViewById(R.id.FavoriteMerchantDesc);
viewHolder.FavoriteMerchantLogo = (ImageView) convertView.findViewById(R.id.FavoriteMerchantLogo);
viewHolder.FavoriteMerchantDeleteButton = (ImageButton) convertView.findViewById(R.id.im_btn_deletemerchant);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID());
viewHolder.FavoriteMerchantDeleteButton.setOnClickListener(this);
//convertView.setTag(item.getID()); // Update
convertView.setTag(viewHolder);
}
else {
viewHolder = (FavoriteMerchantAdapter.ViewHolder) convertView.getTag();
}
/*
String CDnPath = favoriteMerchant.getCDNPath();
ItemsFavoriteMerchant item = itemsFavoriteMerchants.get(position);
*/
String ImageUrl = item.getCoverPageImageURL();
if (ImageUrl != null && !ImageUrl.isEmpty())
Picasso.with(context)
.load(CDnPath + ImageUrl)
.transform(new CircleTransform())
.into(viewHolder.FavoriteMerchantLogo);
String MerchantPlaceDesc = item.getName();
if (MerchantPlaceDesc != null && !MerchantPlaceDesc.isEmpty())
viewHolder.FavoriteMerchantPlaceDesc.setText(MerchantPlaceDesc);
String MerchantocationDesc = (String) item.getDistrict();
if (MerchantocationDesc != null && !MerchantocationDesc.isEmpty())
viewHolder.FavoriteMerchantLocationDesc.setText(MerchantocationDesc);
String MerchantCashDesc = "";
if (MerchantCashDesc != null && !MerchantCashDesc.isEmpty())
viewHolder.FavoriteMerchantCashDesc.setText(MerchantCashDesc);
viewHolder.FavoriteMerchantDeleteButton.setTag(item.getID()); // check update
return convertView;
}
I have a ListView,I am having a custom ListItem designed for it having some TextView's and an ImageView. I want to change that particular image when clicked . I have tried but when i click on that image from ListView, the below listItem's image is changing.
For example if i click on 0th position image then image is changing of 1st position ListIem and when i scroll up and down the List,it changes randomly.
I dont know what is happening with it,I have used notifydatasetChanged on my adapter,But its not working,My code is as below.
Please help me,Thank you,
Code
private class RssAdapter extends ArrayAdapter<RSSFeed_SelectedHotelResult> {
private List<RSSFeed_SelectedHotelResult> rssFeedLst;
int selectedPosition;
public RssAdapter(Context context, int textViewResourceId,
List<RSSFeed_SelectedHotelResult> rssFeedLst) {
super(context, textViewResourceId, rssFeedLst);
this.rssFeedLst = rssFeedLst;
Boolean addtoShotlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
if (convertView == null) {
view = View.inflate(HotelListActivity.this, R.layout.list_row,
null);
rssHolder = new RssHolder();
rssHolder.iv_add = (ImageView) view.findViewById(R.id.iv_add);
rssHolder.rssTitleView = (TextView) view
.findViewById(R.id.title);
rssHolder.tv_offer = (TextView) view.findViewById(R.id.tv_ofr);
rssHolder.rssImagHotel = (ImageView) view
.findViewById(R.id.hotelImage);
rssHolder.rssImageHotelRate = (ImageView) view
.findViewById(R.id.rateHotel2);
rssHolder.rssHotelPrice = (TextView) view
.findViewById(R.id.textHotelRate);
rssHolder.rssHotelAddress = (TextView) view
.findViewById(R.id.textHotelDesc);
// rssHolder.adres = (TextView) view.findViewById(R.id.adres);
// rssHolder.rssHotelRating = (TextView)
// view.findViewById(R.id.textHotelRating);
rssHolder.rating_hotel = (RatingBar) view
.findViewById(R.id.rateHotelImage);
rssHolder.tv_currcode = (TextView) view
.findViewById(R.id.tv_currcode);
view.setTag(rssHolder);
} else {
rssHolder = (RssHolder) view.getTag();
}
final RSSFeed_SelectedHotelResult rssFeed = rssFeedLst
.get(position);
rssHolder.rssTitleView.setText(rssFeed.getName());
imageLoader.DisplayImage(rssFeed.getHotel_image(),
rssHolder.rssImagHotel);
imageLoader.DisplayImage_rating(rssFeed.getHote_rate_image(),
rssHolder.rssImageHotelRate);
rssHolder.rssHotelPrice.setText(rssFeed.getHotel_price());
rssHolder.rssHotelAddress.setText(rssFeed.getHotel_desc());
rssHolder.rating_hotel.setRating(Float.valueOf(rssFeed
.getHotel_rate()));
rssHolder.tv_currcode.setText(Consts.currencyCode);
if (rssFeed.getoffer() != null) {
rssHolder.tv_offer.setText("**" + rssFeed.getoffer() + "**");
} else {
rssHolder.tv_offer.setText("");
}
rssHolder.iv_add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectedPosition = position;
try {
if (position == selectedPosition) {
rssHolder.iv_add
.setBackgroundResource(R.drawable.fill);
} else {
rssHolder.iv_add
.setBackgroundResource(R.drawable.plus12);
}
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println("::::::::::::My data in side hotel List activity:::::::::;"
+ position
+ ""
+ rssFeed.getName()
+ "\n"
+ rssFeed.getHotel_price());
/*
* RSSFeed_SelectedHotelResult rssFeed1 = rssFeedLst
* .get(position);
*/
}
});
return view;
}
}
For notify data-set changed your calling the wrong method the correct method is adapter.notifyDataSetChanged()
1.) Write this code inside your custom adapter getView :
if (position == selectedPosition) {
imageview.setBackgroundResource(R.drawable.image1);
} else {
imageview.setBackgroundResource(R.drawable.normal);
}
2.) Make a method in custom adapter :
public void setSelected(int position) {
selectedPosition = position;
}
//where selectPosition is private int selectedPosition = -1;
3.) Call this method from activity listitem click like :
((Category_Adapter) adapter).setSelected(position);
listview.invalidate();
Make sure your listview set to single choice mode.
private class RssAdapter extends ArrayAdapter<RSSFeed_SelectedHotelResult> {
private List<RSSFeed_SelectedHotelResult> rssFeedLst;
private int selectedPosition =-1;// initalize position
public RssAdapter(Context context, int textViewResourceId,
List<RSSFeed_SelectedHotelResult> rssFeedLst) {
super(context, textViewResourceId, rssFeedLst);
this.rssFeedLst = rssFeedLst;
Boolean addtoShotlist;
}
//make this method
public void setSelected(int position) {
selectedPosition = position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
if (convertView == null) {
view = View.inflate(HotelListActivity.this, R.layout.list_row,
null);
rssHolder = new RssHolder();
rssHolder.iv_add = (ImageView) view.findViewById(R.id.iv_add);
rssHolder.rssTitleView = (TextView) view
.findViewById(R.id.title);
rssHolder.tv_offer = (TextView) view.findViewById(R.id.tv_ofr);
rssHolder.rssImagHotel = (ImageView) view
.findViewById(R.id.hotelImage);
rssHolder.rssImageHotelRate = (ImageView) view
.findViewById(R.id.rateHotel2);
rssHolder.rssHotelPrice = (TextView) view
.findViewById(R.id.textHotelRate);
rssHolder.rssHotelAddress = (TextView) view
.findViewById(R.id.textHotelDesc);
// rssHolder.adres = (TextView) view.findViewById(R.id.adres);
// rssHolder.rssHotelRating = (TextView)
// view.findViewById(R.id.textHotelRating);
rssHolder.rating_hotel = (RatingBar) view
.findViewById(R.id.rateHotelImage);
rssHolder.tv_currcode = (TextView) view
.findViewById(R.id.tv_currcode);
view.setTag(rssHolder);
} else {
rssHolder = (RssHolder) view.getTag();
}
final RSSFeed_SelectedHotelResult rssFeed = rssFeedLst
.get(position);
rssHolder.rssTitleView.setText(rssFeed.getName());
imageLoader.DisplayImage(rssFeed.getHotel_image(),
rssHolder.rssImagHotel);
imageLoader.DisplayImage_rating(rssFeed.getHote_rate_image(),
rssHolder.rssImageHotelRate);
rssHolder.rssHotelPrice.setText(rssFeed.getHotel_price());
rssHolder.rssHotelAddress.setText(rssFeed.getHotel_desc());
rssHolder.rating_hotel.setRating(Float.valueOf(rssFeed
.getHotel_rate()));
rssHolder.tv_currcode.setText(Consts.currencyCode);
if (rssFeed.getoffer() != null) {
rssHolder.tv_offer.setText("**" + rssFeed.getoffer() + "**");
} else {
rssHolder.tv_offer.setText("");
}
rssHolder.iv_add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//remove selectposition = position
try {
if (position == selectedPosition) {
rssHolder.iv_add
.setBackgroundResource(R.drawable.fill);
} else {
rssHolder.iv_add
.setBackgroundResource(R.drawable.plus12);
}
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println("::::::::::::My data in side hotel List activity:::::::::;"
+ position
+ ""
+ rssFeed.getName()
+ "\n"
+ rssFeed.getHotel_price());
/*
* RSSFeed_SelectedHotelResult rssFeed1 = rssFeedLst
* .get(position);
*/
}
});
return view;
}
}
Finally call adapter selected method from activity listitem click and set position.
I have a set a variable in my Base Adapter class, now I want to get(pass) this variable in my related Activity. I am not getting how to do this.
Here is my code.
public class TourDescAdapter extends BaseAdapter {
private List<Descriptions> descriptList;
private LayoutInflater mInflater;
ViewHolder holder;
#SuppressWarnings("unused")
private OnClickListener clickListener;
Activity context;
//TourDescription tourDesc;
ArrayList<HashMap<String, Object>> obj = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> discountedTourDetails = null;
String price = null, prodId = null;
String promoTourname, tourName;
public TourDescAdapter(List<Descriptions> descriptList,
TourDescription activity) {
this.context = activity;
this.descriptList = descriptList;
mInflater = LayoutInflater.from(activity);
clickListener = (OnClickListener) activity;
}
#Override
public int getCount() {
return this.descriptList.size();
}
#Override
public Object getItem(int position) {
return this.descriptList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.tourlist, null);
/****
* Creates a ViewHolder and store references to the two children
* views we want to bind data to
****/
holder = new ViewHolder();
holder.rlayout = (RelativeLayout) convertView
.findViewById(R.id.tourlayout);
holder.title = (TextView) convertView
.findViewById(R.id.tourtitletext);
holder.desc = (TextView) convertView.findViewById(R.id.tourdes);
holder.amountButton = (Button) convertView
.findViewById(R.id.amtBtn);
holder.pinButton = (Button) convertView.findViewById(R.id.pinBtn);
holder.arrowButton = (Button)convertView.findViewById(R.id.arrowBtn);
holder.serialText = (EditText)convertView.findViewById(R.id.pinText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText((String) descriptList.get(position)
.getImageTitle());
holder.desc.setText((String) descriptList.get(position)
.getImageDescription());
((ImageView) holder.rlayout.getChildAt(0)).setImageBitmap(BitmapFactory
.decodeFile((RaconTours.PATH + RaconTours.city + File.separator
+ TourDescription.currentTour.getObjtourName()
+ File.separator + descriptList.get(position)
.getImagePath().split("/")[2]).replace(" ", "_")));
if (position == 0) {
SharedPreferences settings = context.getSharedPreferences("downloadDetails", 0);
String isTourDownloaded = settings.getString(TourDescription.currentTour.getObjtourName(), "");
if (isTourDownloaded.equals("true")) {
//if (!(TourDescription.downloadFile.exists())||TourDescription.downloadFile.exists() == false ) {
//if (TourDescription.currentTour.getIsTourDownloaded() == true) {
//holder.pinButton.setVisibility(View.INVISIBLE);
//holder.arrowButton.setVisibility(View.INVISIBLE);
//holder.serialText.setVisibility(View.INVISIBLE);
}
holder.amountButton.setVisibility(View.VISIBLE);
holder.amountButton.setText("Start");
} else {
File promoPlistPath = new File(RaconTours.PATH + "promocode.txt");
checkPromoCode(promoPlistPath);
if (discountedTourDetails != null) {
tourName = (String) discountedTourDetails.get("promoTour");
price = (String) discountedTourDetails.get("discountPrice");
prodId = (String) discountedTourDetails.get("disProId");
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText("$" +price);
//promoPlistPath.delete();
} else {
// Enabling the two buttons
holder.amountButton.setVisibility(View.VISIBLE);
// Setting the background color
holder.title
.setBackgroundColor(Color.parseColor("#993333"));
// Setting the Title color
holder.title.setTextColor(Color.WHITE);
// Centering the title
holder.title.setGravity(Gravity.LEFT);
// setting the city
((TextView) holder.rlayout.getChildAt(1))
.setText(RaconTours.city);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.VISIBLE);
// setting the Tour Amount
holder.amountButton.setText(TourDescription.currentTour
.getObjPrice());
}
}
} else {
holder.amountButton.setVisibility(View.INVISIBLE);
holder.pinButton.setVisibility(View.INVISIBLE);
holder.arrowButton.setVisibility(View.INVISIBLE);
holder.serialText.setVisibility(View.INVISIBLE);
holder.title.setBackgroundColor(Color.WHITE);
holder.title.setTextColor(Color.BLACK);
holder.title.setGravity(Gravity.CENTER_HORIZONTAL);
((TextView) holder.rlayout.getChildAt(1))
.setVisibility(View.INVISIBLE);
}
return convertView;
}
#SuppressWarnings("unchecked")
private void checkPromoCode(File promoPlistPath) {
if (promoPlistPath.exists()) {
try {
ObjectInputStream inStream = new ObjectInputStream(
new FileInputStream(promoPlistPath));
obj = (ArrayList<HashMap<String, Object>>) inStream
.readObject();
for (HashMap<String, Object> tmpObj : obj) {
promoTourname = (String) tmpObj.get("promoTour");
if (promoTourname.equals(TourDescription.currentTour.getObjtourName())) {
discountedTourDetails = tmpObj;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ViewHolder {
Button pinButton;
Button amountButton;
RelativeLayout rlayout;
TextView title;
TextView desc;
Button arrowButton;
EditText serialText;
}
}
Here
prodId = (String) discountedTourDetails.get("disProId");
I want to pass prodId to related activity.
Note: Base Adapter is called from the activity
adapter = new TourDescAdapter(currentTour.getListOfDescriptions(), this);
setListAdapter(adapter);
Any one can tell me how to do this?
Couldn't you just use String iGotTheString = adapter.prodId?