【问题标题】:crash load image from website [duplicate]来自网站的崩溃加载图像[重复]
【发布时间】:2012-11-07 23:23:24
【问题描述】:

可能重复:
Download a file with Android, and showing the progress in a ProgressDialog

我正在尝试从网站加载图像,我看到了这个问题:Android load from URL to Bitmap 但我的应用程序在这一行崩溃了: conn.connect();

public class HTTPTest extends Activity {

ImageView imView;
String imageUrl = "http://api.androidhive.info/images/sample.jpg";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    Button bt3 = (Button) findViewById(R.id.get_imagebt);
    bt3.setOnClickListener(getImgListener);
    imView = (ImageView) findViewById(R.id.imview);
}

View.OnClickListener getImgListener = new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        downloadFile(imageUrl);
    }
};

Bitmap bmImg;

void downloadFile(String fileUrl) {
    URL myFileUrl = null;
    try {
        myFileUrl = new URL(fileUrl);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl
                .openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        bmImg = BitmapFactory.decodeStream(is);
        imView.setImageBitmap(bmImg);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView  
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HTTPImage load test"
/>
    <Button 
android:id="@+id/get_imagebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get an image"
android:layout_gravity="center"
/>  
<ImageView 
android:id="@+id/imview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>

我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.androidtest.HTTPTest"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<!-- Permission to write to external storage -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

提前感谢您的帮助!

日耳曼。

【问题讨论】:

  • 我只能猜测异常是NetworkOnMainThread...
  • 哦,是的。我该如何解决?我的目录:11-19 15:12:52.655:E/AndroidRuntime(21823):致命异常:主要 11-19 15:12:52.655:E/AndroidRuntime(21823):android.os.NetworkOnMainThreadException 11-19 15:12 :52.655: E/AndroidRuntime(21823): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178) ..
  • 以后每当应用程序崩溃时,请始终将您的 LogCat 添加到您的问题中,这是帮助我们解决错误的路线图。
  • 好的,谢谢您的回答,我正在查看您的链接/网址
  • 我为您的新错误发布了解决方案。

标签: android


【解决方案1】:

您应该在另一个线程上运行所有网络请求(即不在 UI 线程上)。事实上,Android 让你这样做。否则,您的 UI 将在您等待响应时锁定。将您的 downloadFile() 方法更改为如下所示。 AsyncTask 将在另一个线程上运行您的代码。对于需要一段时间才能执行的任务,这是一个很好的做法。

void downloadFile(String fileUrl) {

    AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {

        @Override
        protected String doInBackground(String... params) {
            URL myFileUrl = null;
            try {
                myFileUrl = new URL(params[0]);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) myFileUrl
                        .openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();

                bmImg = BitmapFactory.decodeStream(is);
                imView.setImageBitmap(bmImg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }
    };
    task.execute(fileUrl);

}

【讨论】:

  • 您只能运行一次 AsyncTask 的实例。 “该任务只能执行一次(如果尝试第二次执行将引发异常。)”developer.android.com/reference/android/os/AsyncTask.html
  • 我试过这个但我有这个错误:11-19 15:43:52.620: E/AndroidRuntime(23369): FATAL EXCEPTION: AsyncTask #1 11-19 15:43:52.620: E/ AndroidRuntime(23369): java.lang.RuntimeException: 执行 doInBackground() 11-19 15:43:52.620 时发生错误:E/AndroidRuntime(23369): at android.os.AsyncTask$3.done(AsyncTask.java:278 ) 11-19 15:43:52.620: E/AndroidRuntime(23369): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)...
  • 你能发布完整的堆栈跟踪吗?
  • 抱歉,我已断开与互联网的连接。错误出现在这一行:imView.setImageBitmap(bmImg);山姆给了我解决方案。感谢您的帮助金博!
【解决方案2】:

但是我的应用程序在这一行崩溃了:conn.connect();

从 Android 3+ 开始,您无法对主线程执行可能较慢的网络操作。

在 AsyncTask 中下载图像,以免降低用户体验。只需将您的 downloadFile() 方法移动到 AsyncTask 的 doInBackground() 方法中即可。

如果您需要详细信息,请联系very extensive answer here


加法
使用 Jimbo 的doInBackground(),您可能会因为尝试从不同的线程访问 UI 而遇到错误,这是您无法做到的。您可以在 AsyncTask 中覆盖 onPostExecute() 以使用您的视图,因为它可以访问 UI 线程:

@Override
protected void onPostExecute(String unused) {
    imView.setImageBitmap(bmImg);
}

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多