Convert a bitmap image from a URL and set it to an ImageView

1

I would like to know how to set a URL in an ImageView variable, I do not know if I was clear?

  private final DisplayImageOptions options;

public NoticiasAdapter(Activity activity, List objects) {
    super(activity, R.layout.noticia_list_item , objects);
    this.activity = activity;
    this.stocks = objects;

    options = new DisplayImageOptions.Builder()
    .cacheInMemory(true)
    .cacheOnDisk(true)
    .build();
}


public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    StockQuoteView sqView = null;

    if(rowView == null)
    {

        LayoutInflater inflater = activity.getLayoutInflater();
        rowView = inflater.inflate(R.layout.noticia_list_item, null);


        sqView = new StockQuoteView();
         //sqView.quote = (TextView) rowView.findViewById(R.id.ticker_symbol);
        sqView.ticker = (TextView) rowView.findViewById(R.id.ticker_price);
        sqView.img  = (ImageView) rowView.findViewById(R.id.img);     

        rowView.setTag(sqView);
    } else {
        sqView = (StockQuoteView) rowView.getTag();
    }



    Noticias currentStock = (Noticias) stocks.get(position);
    String imagem3 = currentStock.getImagem();

    sqView.ticker.setText(currentStock.getTitulo());
    ImageLoader.getInstance().displayImage(imagem3, sqView.img, options);
  return rowView;
}

protected static class StockQuoteView {
    protected TextView ticker;
    protected TextView quote;
    protected ImageView img;
}
    
asked by anonymous 13.01.2015 / 20:07

2 answers

1

You can use Universal Image Loader, which does all the heavy lifting for you quickly and effectively.

To implement it in your project is simple:

1) Download .jar in this link and import into the "libs" folder of your project

2) In your Application (if you do not have one, see how to create here ) within the onCreate method, initialize the ImageLoader settings:

...

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
        .threadPriority(Thread.NORM_PRIORITY - 2)
        .threadPoolSize(3)
        .diskCacheExtraOptions(480, 320, null)
        .tasksProcessingOrder(QueueProcessingType.LIFO)
        .build();

ImageLoader.getInstance().init(config);

...

3) To implement within ListView , for example, set your Adapter as follows:

private final DisplayImageOptions options;

public SeuAdapter (List<SeusObjetos> list){
    ...

    options = new DisplayImageOptions.Builder()
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .build();
}

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

    ...
    String suaUrl = "algumaUrl";
    ImageLoader.getInstance().displayImage(suaUrl, suaImageView, options);
    ...

    return convertView;

}

Of course, you will make the implementations that meet your needs in DisplayImageOptions . Explore library documentation to understand and implement what works best for you.

    
14.01.2015 / 21:37
2

This is a simple and straightforward way to perform the requested procedure.

1 - Create a folder where your images will be, put this code in the main activity:

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
             File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"/MeuApp/imagens/");
                directory.mkdirs();

        } 

2 - Create a private method called getBitmapFromURL, to "get" the image from a url:

private Bitmap getBitmapFromURL(String url) {
    try {
        URL src = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) src.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

3 - Create a method that will receive the converted Bitmap to save to your device:

private void salvando(Bitmap abmp){

    String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/MeuApp/imagens/";
            File dir = new File(file_path);
            if(!dir.exists())
            dir.mkdirs();
            File file = new File(dir, "nomedaImagembaixada");
            FileOutputStream fOut;
            try {
            fOut = new FileOutputStream(file);
            ;
            abmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();

            } catch (Exception e) {
            e.printStackTrace();
            }


}

4 - This code will download, as it will pass a return to the salvando() method:

salvando(getBitmapFromURL(www.meusite.com.br/imagens/minhaimagens.png));

5 - NOW IF YOU HAVE A URI!

Uri imagemURI = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/MeuApp/imagens/" + "nomedaImagembaixada" );

6 - Finally what you wanted in ImageView:

imgview.setImageUri(imagemURI);
OBS: Caso queira mais de uma imagem: Substitua a 'nomedaImagembaixada' por uma variável do tipo STRING e a 'www.meusite.com.br/imagens/minhaimagens.png', TAMBÉM. Assim, cada valor dado, a ambas as variáveis, servirão para gerar novas imagens. 
    
13.01.2015 / 20:21