简体   繁体   中英

Using an AsyncTask to update a user profile image in Android

I have a problem with the user profile picture update in my android application.

Introduction

In my MainActivity I can switch between two Fragments, the first one is the HomeFragment and the second is the UserProfileFragment . In the UserProfile, the user can decide to upload a new image, so i let the user pick the image from local storage, then i upload this picture into FirebaseStorage and get the download link. I use a class called LoadImageTask extending an AsyncTask that download the image from url and then upload the resulting bitmap into an ImageView that i have in my UserProfileFragment .

The problem:

When a user uploads a new profile picture, LoadImageTask does his job correctly. The problem is that, when the user tries to update his profile picture, the ImageView is still showing the old image and the user must go to HomeFragment and then go back to the UserProfileFragment to see the update. So, basically the update works but the Profile Picture change is not showed immediately.

What i tried to do

I tried many things like invalidating the imageView or trying to force the imageView in other ways but it didn't worked.

 public class LoadImageTask extends AsyncTask<String, Void, Bitmap> { private ImageView image; public LoadImageTask(ImageView image) { this. image = image; } @Override protected Bitmap doInBackground(String... urls) { String downloadUrl = urls[0]; Bitmap bitmap = null; try { java.net.URL url = new java.net.URL(downloadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); bitmap = BitmapFactory.decodeStream(input); } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { if(result.= null) { image;setImageBitmap(circleTransformation(result)); } } }

When you pick image from the local storage you can set image to imageView from the uri in your onActivityResult.

imageView.setImageURI(imgUri);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM