Custom gridview after few positions shows incorrect data - android

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

Related

Listview add item one at a time

I have a listview and a button in my main activity and three layout ressource files (right.xml, mid.xml and left.xml [They're relative layout]).
I want to make an arrayList (with strings and drawable (images)) and each time I push the button in main.xml the first content of the arrayList will appear at the bottom of the screen (either left, mid or right --> depend of the order of the arrayList) and when I click again the next item (string or drawable) will appear beneath it, pushing it in an upward motion.
UPDATE
I made a Model and an Adapter
Here is the model
public class ModelC1 {
public String C1Name;
public String C1Text;
public int id;
public boolean isSend;
public ModelC1(String C1Name, String C1Text, int id, boolean isSend){
this.id = id;
this.C1Name = C1Name;
this.C1Text = C1Text;
this.isSend = isSend;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getC1Name() {
return C1Name;
}
public void setC1Name(String C1Name){
this.C1Name = C1Name;
}
public String getC1Text() {
return C1Text;
}
public void setC1Text (String C1Text){
this.C1Text = C1Text ;
}
public boolean isSend() {
return isSend;
}
public void setIsSend(boolean send){
isSend = send;
}
Here is the Adapter
public class AdapterC1 extends BaseAdapter {
private List<ModelC1> listChat;
private LayoutInflater inflater;
private Context context;
public AdapterC1(List<ModelC1> listChat, Context context){
this.listChat = listChat;
this.context = context;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listChat.size();
}
#Override
public Object getItem(int i) {
return listChat.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View vi = convertView;
if(convertView == null ){
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}else{
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}
if(listChat.get(i).isSend() !=0 || listChat.get(i).isSend() !=1 || listChat.get(i).isSend() !=2 ){
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
if(bubbleTextView != null)
bubbleTextView.setText(listChat.get(i).C1Text);
TextView nameTextView = (TextView) vi.findViewById(R.id.nameChat);
if(nameTextView != null)
nameTextView.setText(listChat.get(i).C1Name);
}else{
vi=inflater.inflate(R.layout.list_mid,null);
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
bubbleTextView.setText("THE END");
}
return vi;
}
And here is the activity
public class Chat1 extends AppCompatActivity {
private static final String TAG = "Chat1";
private AdapterC1 adapter;
private List<ModelC1> listChat = new ArrayList<>();
private int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
RecyclerView chatContent1 = findViewById(R.id.chatContent1);
}
private ModelC1 setUpMessage(){
Log.d(TAG, "setUpMessage: Exec");
return();
}
///OnClick of the button in the activity_chat1.xml
public void nextClicked1(View view) {
Log.d(TAG, "nextClicked: Is Clicked");
///After the limit of the arraylist is reached
final int limit = 40;
if(count == limit){
Log.d(TAG, "nextClicked: Limit Reached");
Intent i = new Intent(Chat1.this, MainActivity.class);
startActivity(i);
}else{
///Call the list
loadList(null);
}
}
///Load the list of arrays?
public void loadList(View view){
ModelC1 chat = setUpMessage();
listChat.add(chat);
///The ID of the recycleview in the activity_chat1.xml
final RecyclerView recyclerview = findViewById(R.id.chatContent1);
///The adapter
final AdapterC1 adapter = new AdapterC1(listChat, this);
///Make the recyclerview always scroll
///the adapter
///recyclerview.setAdapter(adapter);
}
My questions are now how do I make the ArrayList (containing strings and drawables) and how to link the ArrayList to make it appear one by one when I click on the button ?
As for the ArrayList, will soemthing like that works ?
private List<List<String>> textChat1 = new ArrayList<List<String>>();
ArrayList<String> textChat1 = new ArrayList<String>();
textChat1.add("This is message 1");
textChat1.add("This is message 2");
textChat1.add("This is message 2");
addresses.add(textChat1);
How can I add images and how to say which strings inflate which layout (left, mid or right) ?
You can do your job like this: in your Adapter's getView method ,
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
if (position == 1) {
convertView = getLayoutInflater().inflate(R.layout.left, container, false);
} else if (position == 2) {
convertView = getLayoutInflater().inflate(R.layout.mid, container, false);
} else {
convertView = getLayoutInflater().inflate(R.layout.right, container, false);
}
}
//your code here
return convertView;
}
This will do your job, but, I suggest you to use Recyclerview because it's more efficient and better in terms of looks as well as memory management.

Android ListView glitching back to top for a few seconds before it works properly

I am trying to make an application with a ListView that include a Country Flag and name. This is so that the user can click on them and be shown images of the country that they wouldve taken before. However for about 3 seconds when the listview loads if i try to scroll it will sort of glitch and send me back to top. This is the code..
public class CountriesListAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater inflater;
private List<CountryModel> countryModels;
private WeakReference<TextView> selectedCountryIdtxt;
private boolean useFilter;
private WeakReference<ProgressBar> progressBarWeakReference;
public int getSelectedCountryId() {
return selectedCountryId;
}
public void setSelectedCountryId(int selectedCountryId) {
this.selectedCountryId = selectedCountryId;
}
private int selectedCountryId;
public CountriesListAdapter(#NonNull WeakReference<Context> context, int resourceId, WeakReference<TextView> textView, #NonNull List<CountryModel> countryModelList, boolean useFilter, WeakReference<ProgressBar> progressBarWeakReference){
super(context.get(), resourceId, countryModelList);
selectedCountryIdtxt = textView;
resource = resourceId; //the id of the template file
inflater = LayoutInflater.from(context.get());
this.countryModels = countryModelList;
selectedCountryId = -1;
this.useFilter = useFilter;
this.progressBarWeakReference = progressBarWeakReference;
}
public int getCount() {
if (countryModels != null)
return countryModels.size();
return 0;
}
public CountryModel getItem(int position) {
if (countryModels != null)
return countryModels.get(position);
return null;
}
public long getItemId(int position) {
if (countryModels != null)
return countryModels.get(position).hashCode();
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// this method is automatically called for every object in our list
//basically it's called for every single row before it is generated
// this method is called per row
convertView = (ConstraintLayout) inflater.inflate(resource, null);
//the variable countryModel is fiiled with current object that is being processed
final CountryModel countryModel = countryModels.get(position);
TextView countryName = convertView.findViewById(R.id.countryNamelbl);
final ImageView countryFlag = convertView.findViewById(R.id.countryFlagimg);
final ImageView checked = convertView.findViewById(R.id.countryCheckedimg);
//this is done for every object in the list
assert countryModel != null;
countryName.setText(countryModel.getName());
Picasso.get().load(countryModel.getImage()).fit().into(countryFlag);
if(!useFilter) {
if (selectedCountryId == countryModel.getId()) {
checked.setVisibility(View.VISIBLE);
} else {
checked.setVisibility(View.INVISIBLE);
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!useFilter) {
if (checked.getVisibility() == View.VISIBLE) {
checked.setVisibility(View.INVISIBLE);
selectedCountryId = -1;
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
} else {
if (selectedCountryId == -1) {
checked.setVisibility(View.VISIBLE);
selectedCountryId = countryModel.getId();
} else {
selectedCountryId = countryModel.getId();
notifyDataSetChanged();
}
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
}
} else {
Intent i = new Intent(getContext(), PicturesActivity.class);
i.putExtra("countryId",countryModel.getId());
i.putExtra("countryName", countryModel.getName());
getContext().startActivity(i);
}
}
});
progressBarWeakReference.get().setVisibility(View.INVISIBLE);
return convertView;
}
public List<CountryModel> getCountryModels() {
return countryModels;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.countryModels = countryModels;
}
}
The problem was actually in another class, i was calling the adapter for every list item instead of just once... oops.
Thanks for the replies though!

Listview when scroll is getting the wrong position

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

Duplicate data in ListView?

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

Android Listview Overwrite data instead of append

In my Android application, I am using webservices with index values (for eg.
https://mysampleurl.com/sampledata?username=""&&password=""&&startindex="1"&&endindex="10")
and pass the extracted data to a BaseAdapter via an arraylist and display the result in a listview.
When the listview reaches the bottom, Using asynctask I will increment the index values (for eg.
https://mysampleurl.com/sampledata?username=""&&password=""&&startindex="11"&&endindex="20").
I will receive the data and store it in arraylist and it goes on.
But when I pass array list values to adapter, it overwrites the existing data instead of appending with previous values.
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
System.out.println("position:"+position);
}
I have checked this above code in some other examples, at first it gives values like 1,2,.....10. and at second time it gives 1,2,3,.....20. But in my application it always return the values upto 1,2,3......10.
Could some one tell me what mistake I have done?
public ContentListAdapter (Context context, ArrayList<CommonData> contentList)
{
ctxt = context;
this.ContentList = contentList;
contentListRowInflater = LayoutInflater.from(context);
mSelectedItemsIds=new SparseBooleanArray();
checkBoxState=new boolean[contentList.size()];
}
#Override
public int getCount() {
return (filteredContentList == null)?0:filteredContentList.size();
}
#Override
public Object getItem(int position) {
return filteredContentList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
Here only i pass the values and check the position
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ContentListActivity.adapterFlag = false;
DocumentListViewHolder viewHolder = null;
if (convertView == null || convertView.getTag() == null) {
convertView = contentListRowInflater.inflate(
R.layout.content_list_row, null);
viewHolder = new DocumentListViewHolder();
viewHolder.ivDocumentdoctypeIcon = (ImageView) convertView.findViewById(R.id.ivDocumentTypeIcon);
viewHolder.tvDocumentTitle = (TextView) convertView.findViewById(R.id.tvDocumentTitle);
viewHolder.tvsubitemcount = (TextView) convertView.findViewById(R.id.tvsubitemcount);
viewHolder.ivarrowlauncher = (ImageView)convertView.findViewById(R.id.arrowlauncher);
viewHolder.checkboxselection=(CheckBox)convertView.findViewById(R.id.checkboxdeletion);
checkBoxSelection=viewHolder.checkboxselection;
viewHolder.checkboxselection.setChecked(checkBoxState[position]);
viewHolder.ivarrowlauncher = (ImageView)convertView.findViewById(R.id.arrowlauncher);
mainlayoutrl = (RelativeLayout)convertView.findViewById(R.id.clrrlmain);
sublayoutll = (LinearLayout)convertView.findViewById(R.id.clrowll);
arrowlayoutll = (LinearLayout)convertView.findViewById(R.id.clarrowll);
final Context context = ContentListActivity.contentListActivity;
if(viewHolder.checkboxselection.isChecked()) {
mainlayoutrl.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
sublayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
arrowlayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
} else {
mainlayoutrl.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
sublayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
arrowlayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
}
sublayoutll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Config.networkConnectionCheck(context)) {
if(filteredContentList.get(position).type.equalsIgnoreCase("FOLDER")) {
ContentListActivity.ListarrowClick(position+1,context);
} else if (refreshFlag == false) {
ContentListActivity.oldviewContent(position+1,context);
} else
} else {
ContentListActivity.oldofflineViewContent(position+1,context);
}
}
});
arrowlayoutll.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
ContentListActivity.ListarrowClick(position+1,context);
}
});
viewHolder.ivfilesDownload=(ImageView)convertView.findViewById(R.id.document_list_row_download_imageview);
//newly added by venkat
viewHolder.ivfilesdownloaded=(ImageView)convertView.findViewById(R.id.document_list_row_downloaded_imageview);
viewHolder.tvDocumentDescription=(TextView)convertView.findViewById(R.id.tvdocumentdescription);
} else {
viewHolder = (DocumentListViewHolder) convertView.getTag();
}
viewHolder.tvDocumentTitle.setText(filteredContentList.get(position).name);
String desc = filteredContentList.get(position).versiondescription;
if (desc != null) {
viewHolder.tvDocumentDescription.setText(filteredContentList
.get(position).versiondescription);
}
String doctype = filteredContentList.get(position).type;
String subitemcount = filteredContentList.get(position).subitemcount;
if (doctype.equalsIgnoreCase(ctxt.getResources()
.getString(R.string.pdf))) {
viewHolder.ivDocumentdoctypeIcon
.setImageResource(R.drawable.pdfbigicon);
} else if (doctype.equalsIgnoreCase(ctxt.getResources().getString(
R.string.swf))) {
viewHolder.ivDocumentdoctypeIcon
.setImageResource(R.drawable.flashbigicon);
} if(doctype.equalsIgnoreCase(ctxt.getResources().getString(
R.string.folder)))
{
viewHolder.ivarrowlauncher.setVisibility(View.INVISIBLE);
}
if (filteredContentList.get(position).isupdateavailable
.equalsIgnoreCase(ctxt.getResources().getString(
R.string.update_false_status))) {
} else if (filteredContentList.get(position).isupdateavailable
.equalsIgnoreCase(ctxt.getResources().getString(
R.string.update_true_status))) {
WebAPI webapi = new WebAPI(ctxt);
if (LoginHandler.arraylistdata.size() == 1) {
user_id = LoginHandler.arraylistdata.get(0)
.getUserid();
org_id = LoginHandler.arraylistdata.get(0)
.getOrgId();
} else {
user_id = LoginHandler.arraylistdata.get(
OrgListActivity.selected_org_pos)
.getUserid();
org_id = LoginHandler.arraylistdata.get(
OrgListActivity.selected_org_pos)
.getOrgId();
}
LoginDatabaseHandler loginDBHandler = new LoginDatabaseHandler(
ctxt);
loginDBHandler.open();
int toglState = loginDBHandler.checkOffToggleState(
user_id, org_id, filteredContentList
.get(position).dockey.toString());
}
} else
versionUpdate(position, ctxt);
}
});
}
/*ends*/
return convertView;
}

Categories

Resources