How to set image from Url using AsyncTask?

后端 未结 7 1246
青春惊慌失措
青春惊慌失措 2021-02-06 14:18

I\'m a newbie programmer an I\'m making an android program that displays an image on ImageView from a given url. My problem is how do you use this on the AsyncTask?

Thes

7条回答
  •  醉酒成梦
    2021-02-06 14:44

    Just create a new class "DownloadImageTask" like following one and put it at the same folder where you have your Activity.

    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.util.Log;
    import android.widget.ImageView;
    import android.os.AsyncTask;
    import java.io.*;
    
    
    public class DownloadImageTask extends AsyncTask {
        ImageView bmImage;
    
        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }
    
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap myImage = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                myImage = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return myImage;
        }
    
        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
    

    After this add line to crate that class in your Activity.

    import android.graphics.Bitmap;
    import android.os.AsyncTask;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.util.Log;
    import android.widget.ImageView;
    
    
    public class HomeScreen extends ActionBarActivity {
    
        private final String TAG = "test1";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d(TAG, "onCreate");
            setContentView(R.layout.activity_home_screen);
            InitHomeScreen();
        }
    
        protected void InitHomeScreen()
        {
            String imageUrl = "http://s20.postimg.org/4t9w2pdct/logo_android_png.png";
            Log.d(TAG, "Get an Image");
            // Get an Image
            try{
                AsyncTask execute = new DownloadImageTask((ImageView) findViewById(R.id.imageView))
                        .execute(imageUrl);
                  // R.id.imageView  -> Here imageView is id of your ImageView
            }
            catch(Exception ex)
            {
            }
        }
    
       // Other code...
    

    Don't forget to allow access to INTERNET to your Android app.

    Check your manifest file.

    
    
    
        
        
    
        
            
                
                    
    
                    
                
            
        
    
    
    

提交回复
热议问题