How to set a Image to a Image View from a URL Android

前端 未结 4 1877
Happy的楠姐
Happy的楠姐 2021-01-20 04:20

I am trying to download and show a image in my imageview from URL that i will get dyncamically .I have tried this way

 URL url = new URL(parsedWeatherRespo         


        
4条回答
  •  盖世英雄少女心
    2021-01-20 05:18

    You are running the network related operation on the ui thread. So, you get NetworkOnMainThreadException.

    Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    

    http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

    You should use a Thread or Asynctask.

    http://developer.android.com/reference/android/os/AsyncTask.html.

    Check the docs there is an example.

    Example:

    public class MainActivity extends Activity {
        ImageView iv ;
        ProgressDialog pd; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pd = new ProgressDialog(this);
        pd.setMessage("Downloading Image");
        iv = (ImageView) findViewById(R.id.imageView1);
        Button b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener()
        {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 new DownloadImageTask(iv).execute("http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png");
            }
    
        });
    
    }
    class DownloadImageTask extends AsyncTask {
        ImageView bmImage;
    
        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }
    
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd.show();
        }
    
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
              InputStream in = new java.net.URL(urldisplay).openStream();
              mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }
    
        @Override 
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            pd.dismiss();
            bmImage.setImageBitmap(result);
        }
      }
    }
    

    activity_main.xml

    
    
        
    
        

    Snap

    enter image description here

提交回复
热议问题