Add image from URL

How to add a image into menu from url


I will show how to add a image from url like a Drawable object 


You will need this references.

In this case we will use this method 

import android.graphics.drawable.Drawable;
import android.graphics.drawable.BitmapDrawable;
import java.net.URL;
import java.net.HttpURLConnection;
import android.graphics.BitmapFactory.Options;
import android.graphics.Bitmap;
import java.io.ByteArrayOutputStream;


You could be need add this policy into main activity.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

You can use this method into your class

    public static Drawable getImageByteUrl(Context context,String url)
    {
        Drawable image = null;
        try
        {
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.connect();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2; 
            Bitmap imagen = BitmapFactory.decodeStream(conn.getInputStream(), new Rect(0, 0, 0, 0), options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            imagen.compress(Bitmap.CompressFormat.JPEG, 90,stream);
            image = new BitmapDrawable(context.getResources(),imagen);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return image;
    }

References:

Thanks to these guys.

https://stackoverflow.com/questions/22395417/error-strictmodeandroidblockguardpolicy-onnetwork
https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception
https://stackoverflow.com/questions/1921514/how-to-run-a-runnable-thread-in-android-at-defined-intervals


Comments

Popular posts from this blog

Retriving Android API version by code