从网站崩溃加载图像



可能的重复项:
使用 Android 下载文件,并在进度对话框中显示进度

正在尝试从网站加载图像,我看到这个问题:Android从URL加载到位图,但我的应用程序在此行崩溃: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();
    }
}

主要.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>

提前感谢您的帮助!

日 耳 曼。

您应该在另一个线程上运行所有网络请求(即不在 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);
}

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

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

在 AsyncTask 中下载图像,这样它就不会减慢用户体验。 只需将downloadFile()方法移动到 AsyncTask 的doInBackground()方法中即可。

如果您需要详细的细节,这里有一个非常广泛的答案。


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

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

最新更新