android - 从互联网下载图像,并放入ImageView

时间:2014-11-23 13:08:29

标签: android

我正在尝试编写一个从网址下载图片的代码,并将其放在ImageView中。

下载它的类是UrlDoanload,它以字节数组的形式返回原始图像。

主要活动使用AsyncTask内部私有类来调用UrlDoanload。在onPostExecute方法中,它使用Bitmap,BitmapFactory对象将字节数组放在ImageView中。

问题是,Bitmap对象变为null。

这是代码:

mainActivity:

package com.example.downloadingimageandpuingrid;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

    public String url;
    public Byte [] imageBytes;
    public ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery_item);
        imageView = (ImageView) findViewById(R.layout.gallery_item);
        url = "http://www.royalcanin.in/var/royalcanin/storage/images/breeds/cat-breeds/norwegian-forest-cat/19311843-15-eng-GB/norwegian-forest-cat_cat_breed_cat_picture.jpg";
        new FetchItemsTask().execute();
    }


    private class FetchItemsTask extends AsyncTask<Void,Void, byte[] > {
        @Override
        protected byte[] doInBackground(Void... params) {
            return new UrlDownload().getUrlBytes(url);
        }

        @Override
        protected void onPostExecute(byte[] imageBytes) {
            final Bitmap bitmap = BitmapFactory
                    .decodeByteArray(imageBytes, 0, imageBytes.length);
            imageView.setImageBitmap(bitmap);

        }
    }
}

urlDownload:

package com.example.downloadingimageandpuingrid;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class UrlDownload {
    byte[] getUrlBytes(String urlSpec) 
    {
        try{
        return download(urlSpec);
        } catch(Exception e){
            //e.printStackTrace();
            Log.e("UrlDownload", "error downloading");
            byte[] empety = {};
            return empety;
        }

    }

    public byte[] download (String urlSpec) throws IOException
    {
        URL url = new URL(urlSpec);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = connection.getInputStream();
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) 
            {
                return null;
            }
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, bytesRead);
            }
            out.close();
            return out.toByteArray();
        } 
        finally {
        connection.disconnect();
        }
    }
}

gallary_item布局:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gallery_item_imageView"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_gravity="center"
    android:scaleType="centerCrop" >

</ImageView>

这是logCat:

11-23 15:10:44.348: D/libEGL(3964): loaded /system/lib/egl/libEGL_genymotion.so
11-23 15:10:44.352: D/(3964): HostConnection::get() New Host Connection established 0xb9259888, tid 3964
11-23 15:10:44.364: D/libEGL(3964): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-23 15:10:44.364: D/libEGL(3964): loaded /system/lib/egl/libGLESv2_genymotion.so
11-23 15:10:44.436: W/EGL_genymotion(3964): eglSurfaceAttrib not implemented
11-23 15:10:44.436: E/OpenGLRenderer(3964): Getting MAX_TEXTURE_SIZE from GradienCache
11-23 15:10:44.452: E/OpenGLRenderer(3964): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-23 15:10:44.452: D/OpenGLRenderer(3964): Enabling debug mode 0
11-23 15:10:44.684: D/skia(3964): --- SkImageDecoder::Factory returned null
11-23 15:10:44.684: D/AndroidRuntime(3964): Shutting down VM
11-23 15:10:44.684: W/dalvikvm(3964): threadid=1: thread exiting with uncaught exception (group=0xa4b84648)
11-23 15:10:44.684: E/AndroidRuntime(3964): FATAL EXCEPTION: main
11-23 15:10:44.684: E/AndroidRuntime(3964): java.lang.NullPointerException
11-23 15:10:44.684: E/AndroidRuntime(3964):     at com.example.downloadingimageandpuingrid.MainActivity$FetchItemsTask.onPostExecute(MainActivity.java:36)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at com.example.downloadingimageandpuingrid.MainActivity$FetchItemsTask.onPostExecute(MainActivity.java:1)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at android.os.AsyncTask.finish(AsyncTask.java:631)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at android.os.Looper.loop(Looper.java:137)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at java.lang.reflect.Method.invokeNative(Native Method)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at java.lang.reflect.Method.invoke(Method.java:525)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-23 15:10:44.684: E/AndroidRuntime(3964):     at dalvik.system.NativeStart.main(Native Method)

谢谢!

2 个答案:

答案 0 :(得分:2)

  

Bitmap对象变为空

尝试使用图片的网址。您的代码使用的是HTML页面的URL。

另外,请考虑使用任意数量的现有库,例如PicassoIon

答案 1 :(得分:1)

有效!

我改变了布局。在一个只有ImageView的布局中,我将ImageView放在linerarLayout中。

这是我的新布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

这是新的onCreate方法代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.gallery_item);
            imageView = (ImageView) findViewById(R.id.imageView1);

            url = "http://www.royalcanin.in/var/royalcanin/storage/images/breeds/cat-breeds/norwegian-forest-cat/19311843-15-eng-GB/norwegian-forest-cat_cat_breed_cat_picture.jpg";
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) .build();
            ImageLoader.getInstance().init(config);
            //ImageLoader.getInstance().displayImage(url, imageView);
        new FetchItemsTask().execute();
    }