3

我正在尝试从 URL 下载并在我的 imageview 中显示一个图像,我将动态获得该图像。我已经尝试过这种方式

 URL url = new URL(parsedWeatherResponse.getWeatherIconUrl());
            Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            weather_image.setImageBitmap(bmp);

但它显示异常是

10-04 12:22:40.221: E/AndroidRuntime(15097): FATAL EXCEPTION: main
10-04 12:22:40.221: E/AndroidRuntime(15097): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.itintestapp/com.example.itintestapp.MainActivity}: android.os.NetworkOnMainThreadException
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.ActivityThread.access$600(ActivityThread.java:149)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.os.Looper.loop(Looper.java:153)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.ActivityThread.main(ActivityThread.java:4987)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at java.lang.reflect.Method.invokeNative(Native Method)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at java.lang.reflect.Method.invoke(Method.java:511)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at dalvik.system.NativeStart.main(Native Method)
10-04 12:22:40.221: E/AndroidRuntime(15097): Caused by: android.os.NetworkOnMainThreadException
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1125)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:292)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:185)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at com.example.itintestapp.MainActivity.setSectorData(MainActivity.java:64)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at com.example.itintestapp.MainActivity.onCreate(MainActivity.java:40)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.Activity.performCreate(Activity.java:5020)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-04 12:22:40.221: E/AndroidRuntime(15097):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
10-04 12:22:40.221: E/AndroidRuntime(15097):    ... 11 more

请帮助我如何做到这一点。我已经显示了来自 URL 的图像

我试过这种方式

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      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;
      }

      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
    }

打电话

 new DownloadImageTask((ImageView) findViewById(R.id.weather_image))
            .execute(parsedWeatherResponse.getWeatherIconUrl());

得到这个异常

10-04 12:29:14.298: E/AndroidRuntime(15813): FATAL EXCEPTION: main
10-04 12:29:14.298: E/AndroidRuntime(15813): java.lang.NullPointerException
10-04 12:29:14.298: E/AndroidRuntime(15813):    at com.example.itintestapp.DownloadImageTask.onPostExecute(DownloadImageTask.java:32)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at com.example.itintestapp.DownloadImageTask.onPostExecute(DownloadImageTask.java:1)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at android.os.AsyncTask.finish(AsyncTask.java:631)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at android.os.Looper.loop(Looper.java:153)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at android.app.ActivityThread.main(ActivityThread.java:4987)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at java.lang.reflect.Method.invokeNative(Native Method)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at java.lang.reflect.Method.invoke(Method.java:511)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
10-04 12:29:14.298: E/AndroidRuntime(15813):    at dalvik.system.NativeStart.main(Native Method)
4

4 回答 4

2

您正在 ui 线程上运行与网络相关的操作。所以,你得到NetworkOnMainThreadException.

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

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

您应该使用ThreadAsynctask

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

检查文档有一个例子。

例子:

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>

折断

在此处输入图像描述

于 2013-10-04T06:58:41.537 回答
2

你得到NetworkOnMainThreadException这表明你正在主线程上执行网络操作,而它应该在其他线程中执行。

按照这个问题了解更多信息:如何修复 android.os.NetworkOnMainThreadException?

于 2013-10-04T06:59:18.343 回答
1

当您在MainThreadie上运行与网络相关的工作时UIThread,导致UIThread无法将其布置View在 Screen 或Activity. 那是根据需要在orThreadPolicy上执行的所有耗时且可变的操作。AysncTaskThread

如下所示LongOperationAsyncTask可以通过调用execute()它来执行。

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) {
      }
}   
于 2013-10-04T07:01:04.890 回答
0

您可以直接从网络显示图像而无需下载。请检查以下功能。它会将来自网络的图像显示到您的图像视图中。

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;
    }
}

然后使用活动中的代码将图像设置为图像视图。

于 2014-04-09T12:00:49.287 回答