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

前端 未结 4 1876
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:13

    As you are running Network Related work on MainThread i.e. UIThread which cause UIThread not to laid out it's Viewon Screen or Activity. That's according to ThreadPolicy all the time consuming and variable operation are need to performed on AysncTask or Thread.

    As per below LongOperation is AsyncTask which can be executed by calling execute() on it.

    new LongOperation().execute();  
    

    private class LongOperation extends AsyncTask<String, Void, Bitmap> {
    
          @Override
          protected String doInBackground(Bitmap... params) 
          {
           try 
              {
              URL url = new URL(parsedWeatherResponse.getWeatherIconUrl());
              Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
              } 
           catch (InterruptedException e) {
              // TODO Auto-generated catch block
                e.printStackTrace();
               }
           return bmp;
          }      
    
          @Override
          protected void onPostExecute(Bitmap bmp) 
          {
           super.onPostExecute(result);
           weather_image.setImageBitmap(bmp);
           }
    
          @Override
          protected void onPreExecute() {
          }
    
          @Override
          protected void onProgressUpdate(Void... values) {
          }
    }   
    
    0 讨论(0)
  • 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<String, Void, Bitmap> {
        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

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:android1="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="171dp"
            android:src="@drawable/ic_launcher" />
    
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="78dp"
            android:text="Button" />
    
    </RelativeLayout>
    

    Snap

    enter image description here

    0 讨论(0)
  • 2021-01-20 05:18

    You're getting NetworkOnMainThreadException which indicates that you're performing network operation on main thread, while it should be performed in other thread.

    Follow this question for further information: How to fix android.os.NetworkOnMainThreadException?

    0 讨论(0)
  • 2021-01-20 05:18

    You can directly show image from web without downloading it. Please check the below function . It will show the images from the web into your image view.

    public static Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            return null;
        }
    }
    

    then set image to imageview using code in your activity.

    0 讨论(0)
提交回复
热议问题