【问题标题】:Downloading many images with AsyncTask and post them to ImageView使用 AsyncTask 下载许多图像并将它们发布到 ImageView
【发布时间】:2013-10-27 11:16:57
【问题描述】:

我坐着尝试用 Android 做一些练习。我今天的重点是制作一个简单的应用程序,它将下载数据(来自 URL 的图像)并在布局中的 ImageView 控件中显示它们。我在网上看到了一些例子,并完成了我的应用程序。一切似乎都很好,但是当我按下按钮时,我开始了它的工作,但随后显示错误失败:NULL POINTER 9error reading file)。这是我的代码:

package com.example.htmlcontent;

import java.io.BufferedInputStream;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;


    public class MainActivity extends Activity {
        private ImageView mImageView;
        private ImageView mImageView2;
        public Button button;
        public static ArrayList<Drawable> drawable;

        public static String[] URLs = {"http://zitterman.com/wp-content/uploads/2013/07/19194927_1371972212.jpg","http://i.imgur.com/CQzlM.jpg"};

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            mImageView = (ImageView) findViewById(R.id.test_image);
            mImageView2 = (ImageView) findViewById(R.id.test_image2);
            button = (Button) findViewById(R.id.download1);

            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    new DownloadImage().execute();
                }
            });
        }


        /**
         * Simple functin to set a Drawable to the image View
         * @param drawable
         */
        @SuppressWarnings("deprecation")
        private void setImage()
        {
            if(drawable.get(0) == null)
            {
                System.out.println("DRAWABLE JEST NULL");
            }
            mImageView.setBackgroundDrawable(drawable.get(0));
            mImageView2.setBackgroundDrawable(drawable.get(1));
        }

        public class DownloadImage extends AsyncTask<Void, Void, Void> {



            /**
             * Called after the image has been downloaded
             * -> this calls a function on the main thread again
             */
            protected void onPostExecute(Drawable image)
            {
                setImage();
            }
            protected void onPreExecute()
            {
                Log.i("333333", "Uruchamiam WATEK SCIAGANIA ASYNCTASKIEM PLIKU Z NETA");
            }

            @Override
            protected Void doInBackground(Void... params) {

                downloadImage();
                return null;
            }
            /**
             * Actually download the Image from the _url
             * @param _url
             * @return
             */
            @SuppressWarnings("deprecation")
            private void downloadImage()
            {
                //Prepare to download image

                URL url;        

                InputStream in;
                BufferedInputStream buf;

                //BufferedInputStream buf;
                for(int i = 0; i<URLs.length; i++)
                {
                    try {
                    url = new URL(URLs[i]);
                    in = url.openStream();

                    // Read the inputstream 
                    buf = new BufferedInputStream(in);

                    // Convert the BufferedInputStream to a Bitmap
                    Bitmap bMap = BitmapFactory.decodeStream(buf);
                    if (in != null) {
                        in.close();
                    }
                    if (buf != null) {
                        buf.close();
                    }

                     drawable.add(new BitmapDrawable(bMap));

                } catch (Exception e) {
                    Log.e("Error reading file", e.toString());
                }

                }

            }


        }
    }

还有我的 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"
    >

    <Button
        android:id="@+id/download1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

<TextView
    android:layout_width="102dp"
    android:layout_height="wrap_content"
    android:text="hello" />

    <ImageView
        android:id="@+id/test_image"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@drawable/ic_launcher" />
    <ImageView
        android:id="@+id/test_image2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/ic_launcher" />

</LinearLayout>

正如你在代码 ArrayList 中看到的那样,它是 Drawable 列表。代码没有错误。只有那个 NULL POINTERs。

【问题讨论】:

标签: java android android-asynctask


【解决方案1】:

我认为这是因为您忘记初始化可绘制对象。改为:

public static ArrayList<Drawable> drawable = new ArrayList<Drawable>();

接下来,因为您的 AsyncTask 是 &lt;Void, Void, Void&gt;。您的帖子执行应如下所示:

    @Override
    protected void onPostExecute(Void aVoid) {
        setImage();
    }

泛型类型&lt;A,B,C&gt;对应不同方法的参数和返回类型。你应该在这里阅读更多信息:https://stackoverflow.com/a/6053673/827110

(为了完整起见)您还需要在AndroidManifest.xml 添加互联网权限(就在&lt;application.. 之前):

<uses-permission android:name="android.permission.INTERNET" />

【讨论】:

  • 是的,我忘记了;)
【解决方案2】:

把你的异步任务改成

 public class DownloadImage extends AsyncTask<Void, Void,  ArrayList<Drawable>> {



        /**
         * Called after the image has been downloaded
         * -> this calls a function on the main thread again
         */
        protected void onPostExecute( ArrayList<Drawable> drawable)
        {
            setImage(drawable);
        }
        protected void onPreExecute()
        {
            Log.i("333333", "Uruchamiam WATEK SCIAGANIA ASYNCTASKIEM PLIKU Z NETA");
        }

        @Override
        protected  ArrayList<Drawable> doInBackground(Void... params) {

            downloadImage();
            return drawable;
        }




 private void setImage(ArrayList<Drawable> drawable)
    {
        if(drawable.get(0) == null)
        {
            System.out.println("DRAWABLE JEST NULL");
        }
        mImageView.setBackgroundDrawable(drawable.get(0));
        mImageView2.setBackgroundDrawable(drawable.get(1));
    }

【讨论】:

  • 好的,谢谢你!但是你能告诉我为什么会这样吗?我知道我将数组静态发送到 AsyncTask,所以第一个参数是 Void。没有更新,所以它是无效的。为什么第三个参数不应该是 Void?而在doInBackground ...如果我有静态数组并且它是从另一个函数(downloadImage)完成的,为什么会有返回?如果 Array 是静态的,为什么 setImage 函数应该有这个参数?
【解决方案3】:

好的,我已经按照你说的更正了。是的,我忘了在开始时初始化这个数组列表,但你比我快;)所以

public class MainActivity extends Activity {
        private ImageView mImageView;
        private ImageView mImageView2;
        public Button button;
        public static ArrayList<Drawable> drawable = new ArrayList<Drawable>();

        public static String[] URLs = {"http://zitterman.com/wp-content/uploads/2013/07/19194927_1371972212.jpg","http://i.imgur.com/CQzlM.jpg"};

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            mImageView = (ImageView) findViewById(R.id.test_image);
            mImageView2 = (ImageView) findViewById(R.id.test_image2);
            button = (Button) findViewById(R.id.download1);

            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    new DownloadImage().execute();
                }
            });
        }


        /**
         * Simple functin to set a Drawable to the image View
         * @param drawable
         */
        @SuppressWarnings("deprecation")
        private void setImage( ArrayList<Drawable> drawable)
        {
            if(drawable.get(0) == null)
            {
                System.out.println("DRAWABLE JEST NULL");
            }
            mImageView.setBackgroundDrawable(drawable.get(0));
            mImageView2.setBackgroundDrawable(drawable.get(1));
        }

        public class DownloadImage extends AsyncTask<Void, Void, ArrayList<Drawable>> {

            /**
             * Called after the image has been downloaded
             * -> this calls a function on the main thread again
             */
            protected void onPostExecute( ArrayList<Drawable> drawable)
            {
                setImage(drawable);
            }
            protected void onPreExecute()
            {
                Log.i("333333", "Uruchamiam WATEK SCIAGANIA ASYNCTASKIEM PLIKU Z NETA");
            }

            @Override
            protected ArrayList<Drawable> doInBackground(Void... params) {

                downloadImage();
                return null;
            }
            /**
             * Actually download the Image from the _url
             * @param _url
             * @return
             */
            @SuppressWarnings("deprecation")
            private void downloadImage()
            {
                //Prepare to download image

                URL url;        

                InputStream in;
                BufferedInputStream buf;

                //BufferedInputStream buf;
                for(int i = 0; i<URLs.length; i++)
                {
                    try {
                    url = new URL(URLs[i]);
                    in = url.openStream();

                    // Read the inputstream 
                    buf = new BufferedInputStream(in);

                    // Convert the BufferedInputStream to a Bitmap
                    Bitmap bMap = BitmapFactory.decodeStream(buf);
                    if (in != null) {
                        in.close();
                    }
                    if (buf != null) {
                        buf.close();
                    }

                     drawable.add(new BitmapDrawable(bMap));

                } catch (Exception e) {
                    Log.e("Error reading file", e.toString());
                }

                }

            }


        }
    }

现在它在尝试下载图像时崩溃。我不明白为什么我应该把 ArrayList 作为第三个参数....?为什么如果我声明存储图像的静态数组? OnPostExecute 它应该只调用能够完成其余工作的函数。

【讨论】:

  • 您应该编辑原始问题或发布新问题。发布答案具有误导性,可能会让您投下反对票!
  • 我已经更新了我的答案。现在一切都应该正常了。我希望你已经为你的 android.manifest 添加了互联网权限。
  • 在 doInBackground 方法中,您返回 null,将其更改为返回 drawable ,因为无论您在 doInbackground 中返回什么内容,它都会进入 postexecute,是的,您可以在不提供异步任务参数的情况下使用它,因为您数组是静态的,但如果你给出参数,不要忘记返回 doinbackground 的结果,即 drawable 。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
相关资源
最近更新 更多