How to keep listview item loaded

Asked

Viewed 393 times

1

I have this listview

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:context="${relativePackage}.${activityClass}"
xmlns:ads = "http://schemas.android.com/apk/res-auto"
android:background="#ffffff"
>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="0dp"
    android:layout_above="@+id/ad">

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:id="@+id/praias"
        android:layout_centerHorizontal="true"
         />
</LinearLayout>

<com.google.android.gms.ads.AdView
    android:id="@+id/ad"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adSize="SMART_BANNER"
    ads:adUnitId="@string/banner_unit_id"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">
</com.google.android.gms.ads.AdView>

layoutlist.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Bertioga"
    android:textSize="25dp"
    android:textColor="#000000"
    android:gravity="center"
    android:background="@drawable/backrepeat"
    android:id="@+id/nomePraia"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<ImageView
    android:layout_marginTop="10dp"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/fotoPraia"
    android:layout_below="@+id/nomePraia"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/bt" />

<TextView
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Coemçar a descrição ...."
    android:id="@+id/descricao"
    android:maxLength="400"
    android:textColor="#000000"
    android:layout_alignTop="@+id/btFavorito"
    android:layout_toEndOf="@+id/btFavorito"
    android:gravity="left"
    android:layout_toStartOf="@+id/bt"
    android:layout_toRightOf="@+id/btFavorito"
    android:layout_toLeftOf="@+id/bt" />

<RelativeLayout
    android:layout_marginTop="10dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="3dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btVerMais"
        android:id="@+id/btVerMais"
        android:background="#fff"
        android:textColor="@color/wallet_link_text_light"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btFavorito"

        android:background="@drawable/ic_action_favorite"
        android:layout_alignTop="@+id/bt"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt"
        android:background="@drawable/ic_popup_menu"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Adapter.java

    public View getView(final int position, View v, ViewGroup parent) {
    view = mInflater.inflate(R.layout.layoutlist, null);
    final ListenerItem categoria = itens.get(position);
    ImageView foto = (ImageView) view.findViewById(R.id.fotoPraia);
    int drawableId = context.getResources().getIdentifier(categoria.nome_foto, "drawable", packageName);
    LoadBitmapImage bitmapTask = new LoadBitmapImage(foto,width,context);
    bitmapTask.execute(drawableId);
    TextView nomePraia = (TextView) view.findViewById(R.id.nomePraia);

    final ImageButton btFavorito = (ImageButton) view.findViewById(R.id.btFavorito);
    TextView descricao = (TextView) view.findViewById(R.id.descricao);
    final Button bt = (Button) view.findViewById(R.id.bt);
    Button btVerMais = (Button) view.findViewById(R.id.btVerMais);
    String desc="";
    if(categoria.descricao.length()<397){
        btVerMais.setVisibility(View.INVISIBLE);
        desc=categoria.descricao;
    }else{
        for(int i=0;i<397;i++){
            desc=desc+categoria.descricao.charAt(i);
        }
        desc=desc+"...";
    }
    nomePraia.setText(categoria.nome);
    String nome_foto = categoria.nome_foto;


    descricao.setText(desc);

    if (categoria.favorito) {
        btFavorito.setImageResource(R.drawable.ic_action_favorite_v);
    } else {
        btFavorito.setImageResource(R.drawable.ic_action_favorite);
    }
    btVerMais.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ListenerItem listenerItem = new ListenerItem();

            listenerItem = itens.get(position);
            open(listenerItem);
        }
    });
    btFavorito.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ListenerItem listenerItem = new ListenerItem();

            listenerItem = itens.get(position);

            if (listenerItem.favorito) {
                listenerItem.favorito = false;
                btFavorito.setImageResource(R.drawable.ic_action_favorite);
                chamaToast(false);
            } else {
                listenerItem.favorito = true;
                btFavorito.setImageResource(R.drawable.ic_action_favorite_v);
                chamaToast(true);
            }

            try {
                daoItem.createOrUpdate(listenerItem);

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });
    activity.registerForContextMenu(bt);

    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bt.setId(position);
            activity.openContextMenu(bt);

        }
    });

    return view;
}

In this one of mine ListView carries an item there when going down the ScrollView of ListViewwill loading the other items one at a time I wanted to keep these items loaded , after loading once no need to reload

New Adapter

 public View getView(final int position, View convertView, ViewGroup parent) {

    View view;
    final ViewHolder holder;
    if(convertView == null) {
        view = mInflater.inflate(R.layout.layoutlist, parent, false);
        holder = new ViewHolder();


        holder.foto = (ImageView) view.findViewById(R.id.fotoPraia);
        holder.btFavorito = (ImageButton) view.findViewById(R.id.btFavorito);
        holder.nomePraia = (TextView) view.findViewById(R.id.nomePraia);
        holder.descricao = (TextView) view.findViewById(R.id.descricao);
        holder.bt = (ImageButton) view.findViewById(R.id.bt);
        holder.btVerMais = (Button) view.findViewById(R.id.btVerMais);
        view.setTag(holder);
    }else {
        view = convertView;
        holder = (ViewHolder)view.getTag();
    }

    final ListenerItem categoria = itens.get(position);
    int drawableId = context.getResources().getIdentifier(categoria.nome_foto, "drawable", packageName);

    LoadBitmapImage bitmapTask = new LoadBitmapImage(holder.foto,width,context);
    bitmapTask.execute(drawableId);

    String desc="";
    if(categoria.descricao.length()<397){
        holder.btVerMais.setVisibility(View.INVISIBLE);
        desc=categoria.descricao;
    }else{
        for(int i=0;i<397;i++){
            desc=desc+categoria.descricao.charAt(i);
        }
        desc=desc+"...";
    }
    holder.nomePraia.setText(categoria.nome);
    holder.descricao.setText(desc);

    if (categoria.favorito) {
        holder.btFavorito.setImageResource(R.drawable.ic_action_favorite_v);
    } else {
        holder.btFavorito.setImageResource(R.drawable.ic_action_favorite);
    }
    holder.btVerMais.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ListenerItem listenerItem = new ListenerItem();

            listenerItem = itens.get(position);
            open(listenerItem);
        }
    });
    holder.btFavorito.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ListenerItem listenerItem = new ListenerItem();

            listenerItem = itens.get(position);

            if (listenerItem.favorito) {
                listenerItem.favorito = false;
                holder.btFavorito.setImageResource(R.drawable.ic_action_favorite);

            } else {
                listenerItem.favorito = true;
                holder.btFavorito.setImageResource(R.drawable.ic_action_favorite_v);

            }

            try {
                daoItem.createOrUpdate(listenerItem);

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    });
    activity.registerForContextMenu(holder.bt);

    holder.bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.bt.setId(position);
            activity.openContextMenu(holder.bt);

        }
    });

    return view;
}

Viewholder class

private class ViewHolder {
public ImageView foto;
public TextView nomePraia;
public ImageButton btFavorito;
public TextView descricao;
public ImageButton bt;
public Button btVerMais;

}

Mode I upload the images Class I’m using to carry Loadbitmapimage

public class LoadBitmapImage extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private final int width;
private Context context;

public LoadBitmapImage(ImageView imageView,int width,Context context) {
    this.width = width;
    this.context = context;
    // Use a WeakReference para ter certeza que sua ImageView sera reciclada
    imageViewReference = new WeakReference<ImageView>(imageView);
}

// Carregando a imagem em background
@Override
protected Bitmap doInBackground(Integer... drawableId) {
    // Aqui voce utiliza seus proprios metodos para carregar e configurar sua Bitmap
    Bitmap bm = BitmapFactory.decodeResource(context.getResources(), drawableId[0]);
    bm = bm.createScaledBitmap(bm, width, width, true);
    return bm;
}

// Quando completo, coloque o Bitmap em sua ImageView
@Override
protected void onPostExecute(Bitmap bitmap) {
    if (imageViewReference != null && bitmap != null) {
        final ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(bitmap);
        }
    }
}

}

  • You’re talking about the pictures?

  • or the images or everything , just so you don’t have to reload

  • Where the images come from?

  • the images are already in the same drawable

1 answer

1


There is a better way to implement the method getView, using the concept of Viewholders, where your Views are in another class (Holder). For example:

@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
    View v = convertView;
    ViewHolder holder;

    if (convertView == null) {
        holder = new ViewHolder();
        v = ((Activity) mContext).getLayoutInflater().inflate(R.layout.layout, null);
        holder.imageView1 = v.findViewById(R.id.seuImageView);
        holder.textView1 = v.findViewById(R.id.seuTextView);

        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }

    Object item = getItem(position);

    return v;
}

private class ViewHolder {
    ImageView imageView1;
    TextView textView1;
}

Listview recycles the items in the list not to keep creating again, basically it keeps in memory only those on the screen and the next item to be shown. By doing your getView like this, using a Holder to manipulate your Views you prevent Listview from reusing your already created Views by modifying your data.

  • I put the Holder in my Adapter more is generating another problem beyond what I was already , has time that is showing the repeated item , and has time that loads the item the wrong way , I will put the new Adapter la

  • "Magic" happens on the if line (convertView == null) {

  • what’s wrong with mine?

  • In the first line of your getView your "View view" needs to receive the convertView: View view = convertView

  • if will switch to if ( view ==null) or continues the if (convertView == null)

  • Whatever happens at this stage 2 are equal

  • rafael , if I upload my image inside this getview hangs the application until the image is loaded , then I put a class to load in the background but there is the previous image until the image of the current item is loaded, you know some way to load this image more efficiently?

  • In my experience with uploading images the best framework I used was Google’s Volley, it has an Imageview (Networkimageview) that does all the work for you. There is also Square Picasso which is very good, just as easy. Every image upload should be done in a separate task and these 2 do it very well, including with the option to display any image while yours is loaded.

  • minutes, I will seek to know more of this thank you

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.