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

标签 android

我正在尝试编写一段代码,从 url 下载图片,并将其放入 ImageView。

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

Main Activity 使用 AsyncTask 内部私有(private)类来调用 UrlDoanload。在 onPostExecute 方法中,它通过使用 Bitmap、BitmapFactory 对象将字节数组放入 ImageView 中。

问题是 Bitmap 对象变为空。

这是代码:

主要 Activity :

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

        }
    }
}

网址下载:

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)

谢谢!

最佳答案

the Bitmap object becomes null

尝试使用图像的 URL。您的代码正在使用指向 HTML 页面的 URL。

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

关于android - 从互联网下载图像,并放入 ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27089295/

相关文章:

java - Android 中的 BitmapFactory null 问题

java - 如何在较新版本的 Android 3.1 及更高版本中实现 Firebase Recycler Adapter?

android - 如何检测用户早上开始使用手机的时间

java - Android ftp 下载无法正确下载文件

java 11,运行 sdkmanage 导致 java.lang.module.FindException : Module java. se.ee not found

php - AES加密 Android/AES解密 PHP

android - 更改抽屉导航中的布局

android - 如何将 Bitmap 转换为 Drawable?

查看SDK源码时Android Studio报错

android:即时反射(reflect) UI 语言更改,无需重新加载/重新启动应用程序