从网站崩溃加载图像

时间:2012-11-19 23:04:04

标签: android

  

可能重复:
  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>

先谢谢你的帮助!

Germain的。

2 个答案:

答案 0 :(得分:3)

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

}

答案 1 :(得分: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);
}