Error while displaying web images in android java

Asked

Viewed 174 times

2

I’m trying to display images from the web in a ListView, but they appear out of order, on the wrong lines and change position with each update of Activity.

Activity:

public class ListarProdutosActivity extends Activity {
    DataBaseHandler db = new DataBaseHandler(this);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String[] from = new String[] {
            DataBaseHandler.KEY_PRODUTOS_DESCRICAO, DataBaseHandler.KEY_PRODUTOS_VALOR, DataBaseHandler.KEY_PRODUTOS_IMAGE
        };
        int[] to = {
            R.id.txtDescricao, R.id.txtValor, R.id.logo
        };
        Cursor cursor = db.listarProdutos();

        @SuppressWarnings("deprecation")
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_produtos, cursor, from, to);

        ListView dataList = (ListView) findViewById(R.id.list);
        dataList.setAdapter(adapter);

        adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            /** Binds the Cursor column defined by the specified index to the specified view */
            public boolean setViewValue(View view, final Cursor cursor, final int columnIndex) {
                final ImageView imgView = (ImageView) view.findViewById(R.id.logo);

                if (view.getId() == R.id.logo) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Log.v("aviso", "image");
                                Drawable image = getImagem(cursor.getString(columnIndex));

                                imgView.setImageDrawable(image);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    return true;
                }
                return false;
            }
        });
    }

    public Drawable getImagem(String image) throws Exception {
        URL url = new URL(image);

        InputStream is = (InputStream) getObjeto(url);
        Drawable d = Drawable.createFromStream(is, "src");

        return d;
    }

    private Object getObjeto(URL url) throws MalformedURLException, IOException {
        Object content = url.getContent();
        return content;
    }
}

Or if anyone knows a better way to do that, I appreciate the suggestions.

  • Opa, follow this example: http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_example/index.php? view=article_discription&aid=112&aaid=134 Here it creates a Holder that saves the view state at that position, and still ensures the fluidity of the list.

1 answer

4


There are libraries that load images synchronously or asynchronously, save the image in cache and/or disk to save the band and abstract that part of the encoding.

Take a look at this Project:

https://github.com/nostra13/Android-Universal-Image-Loader

EDIT

Improving the response a little:

The Android Universal Image Loader is a library that abstracts all the image download part, can be performed synchronously and asynchronously. In your code, it would look something like:

public class ListarProdutosActivity extends Activity {
    DataBaseHandler db = new DataBaseHandler(this);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Configuração default do Image Loader
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader.getInstance().init(config);

        String[] from = new String[] {
            DataBaseHandler.KEY_PRODUTOS_DESCRICAO, DataBaseHandler.KEY_PRODUTOS_VALOR, DataBaseHandler.KEY_PRODUTOS_IMAGE
        };
        int[] to = {
            R.id.txtDescricao, R.id.txtValor, R.id.logo
        };
        Cursor cursor = db.listarProdutos();

        @SuppressWarnings("deprecation")
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_produtos, cursor, from, to);

        ListView dataList = (ListView) findViewById(R.id.list);
        dataList.setAdapter(adapter);

        adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            /** Binds the Cursor column defined by the specified index to the specified view */
            public boolean setViewValue(View view, final Cursor cursor, final int columnIndex) {
                final ImageView imgView = (ImageView) view.findViewById(R.id.logo);

                if (view.getId() == R.id.logo) {
                   //Acredito que a URL seja obtida assim e a mesma deve ser enviada como string
                   URL url = new URL(cursor.getString(columnIndex));
                   //Aqui o ImageLoader fica responsável por obter a imagem na internet
                   ImageLoader.displayImage(url.toString() , imgView);
                    return true;
                }
                return false;
            }
        });
    }

    public Drawable getImagem(String image) throws Exception {
        URL url = new URL(image);

        InputStream is = (InputStream) getObjeto(url);
        Drawable d = Drawable.createFromStream(is, "src");

        return d;
    }

    private Object getObjeto(URL url) throws MalformedURLException, IOException {
        Object content = url.getContent();
        return content;
    }
}

I believe that this basic example works for your case, after you import the library to your project. If you access the Universal Imageloader link, you will see that there are several useful settings for your application! I hope it helps!

  • Sergio, I edited my answer, I hope it helps!

Browser other questions tagged

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