lostAstronaut
lostAstronaut

Reputation: 1361

Async download image and set to imageview

Alright, I'm fairly new to android development and am working on an app. I've looked all over stackoverflow but can't seem to find an example which works. I need to download a photo from a url asynchronously and then set it in an imageview. I decided to create a class separate from my fragments to download the images.

Code:

public class UpdateUser {

    private static final String TAG = "UpdateUser";


    public void refresh(JSONObject user){

        //Download profile pic
        try {
            downloadProfpic(user.getString("userpic_url"));
        }  catch (JSONException e) {
            Log.e(TAG, "", e);
        }
    }

    public void downloadProfpic(String userpicURL) {

        try{

            URL murl = new URL(userpicURL);
            Bitmap bm = BitmapFactory.decodeStream(murl.openConnection().getInputStream());

            Context context = Application.getContext();
            final FileOutputStream fos = context.openFileOutput("Prof_pic.png", Context.MODE_PRIVATE);

            bm.compress(CompressFormat.JPEG, 90, fos);

            //Set the imageview
            //pageFrag.setProfPic("Prof_pic.png");

        } catch (IOException e) {
            e.printStackTrace();
            return;
        }    

    }
}

As you can see its not asynchronous and also doesn't set the imageview. Also I'm fairly sure I'm not doing it correctly. Should I be downloading to internal storage? Or download to a file? Could someone please help me.

Thank you, Tom

Upvotes: 1

Views: 287

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007658

Use Picasso.

Or, use Ion.

Or, use SmartImageView.

Or, use any other existing Android library for downloading and processing images.

Upvotes: 3

Related Questions