Search code examples
androidandroid-listviewlistadapterlistviewitemandroid-viewholder

Android ListView rows are repeating if i don't re-query the needed info from the database


It's my first time working with listviews so excuse me in advance for any beginner errors.

My code for the custom getView is as follows:

public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder mHolder;
    if (convertView == null) {
        /*Toast toast = Toast.makeText(context, "nullConvertView", Toast.LENGTH_SHORT);
        toast.show();*/
        mHolder = new ViewHolder();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.listitem, parent, false);


        mHolder.PetName = (TextView) convertView.findViewById(R.id.PetName);

        mHolder.PetImage = (RoundedImageView) convertView.findViewById(R.id.PetImage);



        updateItem(mHolder, this.getItem(position));

        convertView.setTag(mHolder);
    } else {
        mHolder = (ViewHolder) convertView.getTag();
    }

    return convertView;
}

The function updateItem connects to a dropbox datastore and retrieves the informations such as datastore title and image (each row in the listview is a dropbox datastore) and then sets them through mHolder.PetName.setText(queriedresultstring) ecc

If i keep the code this way i get repeated views when scrolling, while if i move the updateItem function outside of the if/else condition everything works fine, but everytime i scroll the listview it queries again the database for each row that reappears on screen.

Is there any way to keep the informations stored on the view without having to query the database each time the view returns on screen?

Thank you


Solution

  • Rather than query the database in your updateItem() method, use a Loader to query the data and build a local data store which is used to back your adapter (such as an ArrayList.) Alternatively, you could use a Loader which queries the backend the caches the data in a local database so your Loader would have to have the logic to use the local database rather than submitting a new query (if possible.) It's up to you to decide how to manage that.

    BTW, the reason you need to have your current updateItem() outside of the if/else condition check is because otherwise the recycled views don't get updated with the correct data binding.