Yenvanio Yenvanio - 2 months ago 6
Android Question

How to get specific images from a website and display them in an Android App?

Given the URL of a website I want to retrieve the logo and background image of the website and display it in an android app. For example from this link I would want the background image and the hack western logo.

EDIT: I forgot to mention I am trying to achieve this effect for a list of URL's of undetermined size until run time

TOP TOP
Answer

Use this AsyncTask for loading image from URL

 public class LoadImageTask extends AsyncTask<Void, Void, Void>{
    private Bitmap mMyBitmap;
    @Override
    protected Void doInBackground(Void... params) {
         try {
                URL url = new URL("https://hackwestern.com/images/logo_vert_spons.png");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                mMyBitmap = BitmapFactory.decodeStream(input);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
         mImageView.setImageBitmap(mMyBitmap);
    }

}

Then call it on OnCreate or somewhere you need:

new LoadImageTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Comments