使用ImageLoad(Android)下载图像后下载URL

时间:2015-07-27 08:15:50

标签: android json android-viewpager

我在Android上遇到了问题

我保存了一些图片的数据库网址。我想下载图片以查看viewpager。当我有URL时,我将使用ImageLoader下载图像。

当我想从服务器下载图像的URL时,会出现问题。我正在使用Asyntask但不知何故aplicaión失败了。

如何下​​载URL以便以后使用ImageLoader下载图像?

我留下了我正在使用的部分代码。

package com.cinemappstop;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.cinemappstop.libraries.UserFunctions;
import com.cinemappstop.utils.Utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;


public class ActivityGallery extends SherlockFragmentActivity {



    // Create instance of list and ListAdapter
    ListView list;
    ProgressDialog pDialog;
    LinearLayout lytRetry;

    private ViewPager pager;
    private DisplayImageOptions options;

    // Array to url of my images
    String[] actorImages;
    // Create an instance of ActionBar
    ActionBar actionbar;

    private int intLengthData;
    String mIdActor ;
    // Declare object of JSONObject class
    JSONObject json;

    Context context;

    public String[] mImage;
    ImagePagerAdapter sla; 
    // Declare object of userFunctions and Utils class
    UserFunctions userFunction;
    Utils utils;

    private ImageLoader imageLoader;
    DetailOnPageChangeListener listener;
    /* String[] imageUrls = {
            "http://4.bp.blogspot.com/-dCQSa1pig0M/TgbxHWWS2zI/AAAAAAAAABk/Rtnv6PyXYqI/s748/5.jpg",
            "http://static.yousaytoo.com/post_images/de/38/50/1198542/remote_image_1326117775.jpg",
            "http://im1.indiancolleges.com/uploaded_images/article/CBSE-12-resultsIC_348X264.jpg",
            "http://thumbnail.craftkeys.com/t/336x280/f05af81c9d3c71046c07e138756c8ab885d3d74e.jpg",
            "http://4.bp.blogspot.com/--2tylWQhA6Y/TY920P3ivyI/AAAAAAAAACo/pI9kArldvm0/s1600/Wearable_Technology%2528GtuGuru%2529.jpg",

            "http://1.bp.blogspot.com/-gPY9kcs7w9w/T9W3W62TaSI/AAAAAAAAAM8/nEXldUDIJhc/s1600/gtu-mca-android-tutorial-logo-four.jpg",

            "http://gtu-mca.weebly.com/uploads/9/1/5/6/9156517/8037790_orig.png",
            "http://gtu-mca.weebly.com/uploads/9/1/5/6/9156517/_6068527.png",
            "http://gtu-mca.weebly.com/uploads/9/1/5/6/9156517/3898239.png",
            "http://4.bp.blogspot.com/-tXQSSpN5z8o/TfdJViDk9XI/AAAAAAAAAAY/LbY0hbrezKU/s1600/mcahelp.bmp",
            "http://i.ytimg.com/vi/yeWf4zvxRTo/0.jpg",
            "http://english.globalgujaratnews.com/uploads/news/09_2012/1348840805_ADMISSION_STUDENTS.jpg" };
    */


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);

        context = this;

        // Get id actor to download images
        Intent i = getIntent();  
        mIdActor = i.getStringExtra("idActor");
        new downLoadUrl().execute();

        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_launcher).cacheOnDisc()
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();

        pager = (ViewPager) findViewById(R.id.view_pager);
        pager.setAdapter(new ImagePagerAdapter(actorImages));
        listener = new DetailOnPageChangeListener();
        pager.setOnPageChangeListener(listener);


    }

    public void btnClick(View view) {
        Toast.makeText(ActivityGallery.this,
                "Current Page :: " + listener.getCurrentPage(),
                Toast.LENGTH_LONG).show();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>" + listener.getCurrentPage());
    }

    public class DetailOnPageChangeListener extends
            ViewPager.SimpleOnPageChangeListener {

        private int currentPage;

        @Override
        public void onPageSelected(int position) {

            currentPage = position;
        }

        public int getCurrentPage() {
            return currentPage;
        }
    }


    @Override
    protected void onStop() {
        imageLoader.stop();
        super.onStop();
    }


    private class ImagePagerAdapter extends PagerAdapter {

        private String[] images;
        private LayoutInflater inflater;

        ImagePagerAdapter(String[] images) {
            this.images = images;
            inflater = getLayoutInflater();
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public void finishUpdate(View container) {
        }

        @Override
        public int getCount() {
            return images.length;
        }

        @Override
        public Object instantiateItem(View view, int position) {
            final View imageLayout = inflater.inflate(
                    R.layout.item_pager_image, null);
            final ImageView imageView = (ImageView) imageLayout
                    .findViewById(R.id.image);


            imageLoader.displayImage(images[position], imageView, options,
                    new ImageLoadingListener() {
                        @Override
                        public void onLoadingFailed(FailReason failReason) {
                            String message = null;
                            switch (failReason) {
                            case IO_ERROR:
                                message = "Input/Output error";
                                break;
                            case OUT_OF_MEMORY:
                                message = "Out Of Memory error";
                                break;
                            case UNKNOWN:
                                message = "Unknown error";
                                break;
                            }
                            Toast.makeText(ActivityGallery.this, message,
                                    Toast.LENGTH_SHORT).show();


                            imageView
                                    .setImageResource(android.R.drawable.ic_delete);
                        }

                        @Override
                        public void onLoadingComplete(Bitmap loadedImage) {
                            Animation anim = AnimationUtils.loadAnimation(
                                    ActivityGallery.this, R.anim.fade_in);
                            imageView.setAnimation(anim);
                            anim.start();
                        }

                        @Override
                        public void onLoadingCancelled() {
                            // Do nothing
                        }

                        @Override
                        public void onLoadingStarted() {
                            // TODO Auto-generated method stub

                        }
                    });

            ((ViewPager) view).addView(imageLayout, 0);
            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View container) {
        }
    }


    // Load first 10 videos
    private class downLoadUrl extends AsyncTask<Void, Void, Void> {


        @Override
        protected void onPreExecute() {
             // Showing progress dialog before sending http request
            pDialog = new ProgressDialog(
                    context);
            pDialog.setMessage("Buscando...");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();

        }

        protected Void doInBackground(Void... unused) {
            // Call method getDataFromServer
                getDataUrlFromServer();
                return (null);
            }

            protected void onPostExecute(Void unused) {

                // Closing progress dialog
                pDialog.dismiss();

            }

        }


    // Method get data from server
    public void getDataUrlFromServer(){

        try {

            Log.d("Value idActor", mIdActor);
            json = userFunction.searchImageActor(mIdActor);


            if(json != null){

                JSONArray dataLocationArray = 
                        json.getJSONArray(userFunction.array_list_actor_images);

                intLengthData = dataLocationArray.length();

                actorImages = new String[intLengthData];            

                // Store data to variable array
                for (int i = 0; i < intLengthData; i++) {
                    JSONObject locationObject = dataLocationArray.getJSONObject(i);


                    actorImages[i] = userFunction.URLImagesActor + locationObject.getString(userFunction.key_images_actor);

                }
             }


         } catch (JSONException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             Log.d("NULO", "Null");
         }      
    }

}

logCat。有时它失败并且没有显示消息

07-27 09:55:51.806: I/MemoryCache(10592): cache size=4916800 length=3
07-27 09:55:52.576: D/dalvikvm(10592): GC_FOR_ALLOC freed 10842K, 47% free 16309K/30672K, paused 31ms, total 31ms
07-27 09:55:52.696: I/MemoryCache(10592): cache size=7060800 length=4
07-27 09:55:52.946: I/MemoryCache(10592): cache size=8980800 length=5
07-27 09:55:53.366: D/dalvikvm(10592): GC_FOR_ALLOC freed 180K, 34% free 20251K/30672K, paused 24ms, total 24ms
07-27 09:55:53.386: I/MemoryCache(10592): cache size=10900800 length=6
07-27 09:55:54.316: I/MemoryCache(10592): cache size=13044800 length=7
07-27 09:55:55.616: D/Valor id_actor(10592): 11
07-27 09:55:55.616: D/Valor id_actor(10592): 11
07-27 09:55:55.816: D/Click(10592): id_actor
07-27 09:55:55.886: D/Value idActor(10592): 11
07-27 09:55:55.886: W/dalvikvm(10592): threadid=11: thread exiting with uncaught exception (group=0x415f68b0)
07-27 09:55:55.886: E/AndroidRuntime(10592): FATAL EXCEPTION: AsyncTask #1
07-27 09:55:55.886: E/AndroidRuntime(10592): java.lang.RuntimeException: An error occured while executing doInBackground()
07-27 09:55:55.886: E/AndroidRuntime(10592):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at java.lang.Thread.run(Thread.java:841)
07-27 09:55:55.886: E/AndroidRuntime(10592): Caused by: java.lang.NullPointerException
07-27 09:55:55.886: E/AndroidRuntime(10592):    at com.cinemappstop.ActivityGallery.getDataUrlFromServer(ActivityGallery.java:285)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at com.cinemappstop.ActivityGallery$downLoadUrl.doInBackground(ActivityGallery.java:265)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at com.cinemappstop.ActivityGallery$downLoadUrl.doInBackground(ActivityGallery.java:1)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-27 09:55:55.886: E/AndroidRuntime(10592):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-27 09:55:55.886: E/AndroidRuntime(10592):    ... 4 more
07-27 09:55:55.896: D/AndroidRuntime(10592): Shutting down VM
07-27 09:55:55.896: W/dalvikvm(10592): threadid=1: thread exiting with uncaught exception (group=0x415f68b0)
07-27 09:55:55.896: I/Process(10592): Sending signal. PID: 10592 SIG: 9

解决方案

package com.cinemappstop;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.cinemappstop.libraries.UserFunctions;
import com.cinemappstop.utils.Utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;


public class ActivityGallery extends SherlockFragmentActivity {



    // Create instance of list and ListAdapter
    ListView list;
    ProgressDialog pDialog;
    LinearLayout lytRetry;

    private ViewPager pager;
    private DisplayImageOptions options;

    // Array to url of my images
    String[] actorImages;
    // Create an instance of ActionBar
    ActionBar actionbar;
    String name;
    private int intLengthData;
    String mIdActor ;
    // Declare object of JSONObject class
    JSONObject json;

    Context context;

    public String[] mImage;
    ImagePagerAdapter sla; 
    // Declare object of userFunctions and Utils class
    UserFunctions userFunction;
    Utils utils;

    private ImageLoader imageLoader;
    DetailOnPageChangeListener listener;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);

        context = this;

        // Get id actor to download images
        Intent i = getIntent();  
        mIdActor = i.getStringExtra("idActor");
        name = i.getStringExtra("name");

        // Declare object of userFunctions class
        userFunction = new UserFunctions();

        new downLoadUrl().execute();




    }

    public void btnClick(View view) {
        Toast.makeText(ActivityGallery.this,
                "Current Page :: " + listener.getCurrentPage(),
                Toast.LENGTH_LONG).show();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>" + listener.getCurrentPage());
    }

    public class DetailOnPageChangeListener extends
            ViewPager.SimpleOnPageChangeListener {

        private int currentPage;

        @Override
        public void onPageSelected(int position) {

            currentPage = position;
        }

        public int getCurrentPage() {
            return currentPage;
        }
    }


    @Override
    protected void onStop() {
        imageLoader.stop();
        super.onStop();
    }


    private class ImagePagerAdapter extends PagerAdapter {

        private String[] images;
        private LayoutInflater inflater;

        ImagePagerAdapter(String[] images) {
            this.images = images;
            inflater = getLayoutInflater();
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public void finishUpdate(View container) {
        }

        @Override
        public int getCount() {
            return images.length;
        }

        @Override
        public Object instantiateItem(View view, int position) {
            final View imageLayout = inflater.inflate(
                    R.layout.item_pager_image, null);
            final ImageView imageView = (ImageView) imageLayout
                    .findViewById(R.id.image);


            imageLoader.displayImage(images[position], imageView, options,
                    new ImageLoadingListener() {
                        @Override
                        public void onLoadingFailed(FailReason failReason) {
                            String message = null;
                            switch (failReason) {
                            case IO_ERROR:
                                message = "Input/Output error";
                                break;
                            case OUT_OF_MEMORY:
                                message = "Out Of Memory error";
                                break;
                            case UNKNOWN:
                                message = "Unknown error";
                                break;
                            }
                            Toast.makeText(ActivityGallery.this, message,
                                    Toast.LENGTH_SHORT).show();


                            imageView
                                    .setImageResource(android.R.drawable.ic_delete);
                        }

                        @Override
                        public void onLoadingComplete(Bitmap loadedImage) {
                            Animation anim = AnimationUtils.loadAnimation(
                                    ActivityGallery.this, R.anim.fade_in);
                            imageView.setAnimation(anim);
                            anim.start();
                        }

                        @Override
                        public void onLoadingCancelled() {
                            // Do nothing
                        }

                        @Override
                        public void onLoadingStarted() {
                            // TODO Auto-generated method stub

                        }
                    });

            ((ViewPager) view).addView(imageLayout, 0);
            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View container) {
        }
    }


    // Load first 10 videos
    private class downLoadUrl extends AsyncTask<Void, Void, Void> {


        @Override
        protected void onPreExecute() {
             // Showing progress dialog before sending http request
            pDialog = new ProgressDialog(
                    context);
            pDialog.setMessage("Buscando...");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();

        }

        protected Void doInBackground(Void... unused) {
            // Call method getDataFromServer
                getDataUrlFromServer();
                return (null);
            }

            protected void onPostExecute(Void unused) {

                // Closing progress dialog
                pDialog.dismiss();

                imageLoader = ImageLoader.getInstance();
                imageLoader.init(ImageLoaderConfiguration.createDefault(context));
                options = new DisplayImageOptions.Builder()
                        .showImageForEmptyUri(R.drawable.ic_launcher).cacheOnDisc()
                        .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();

                pager = (ViewPager) findViewById(R.id.view_pager);
                pager.setAdapter(new ImagePagerAdapter(actorImages));
                listener = new DetailOnPageChangeListener();
                pager.setOnPageChangeListener(listener);

            }

        }


    // Method get data from server
    public void getDataUrlFromServer(){

        try {

            Log.d("Value idActor", mIdActor);
            json = userFunction.searchImageActor(mIdActor);


            if(json != null){

                JSONArray dataLocationArray = 
                        json.getJSONArray(userFunction.array_list_actor_images);

                intLengthData = dataLocationArray.length();
                Log.d("Valor json", String.valueOf(intLengthData));
                actorImages = new String[intLengthData];            

                // Store data to variable array
                for (int i = 0; i < intLengthData; i++) {
                    JSONObject locationObject = dataLocationArray.getJSONObject(i);


                    actorImages[i] = userFunction.URLImagesActor + locationObject.getString(userFunction.key_images_actor);

                }
             }


         } catch (JSONException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             Log.d("NULO", "Null");
         }      
    }

}

1 个答案:

答案 0 :(得分:0)

您似乎忘了初始化UserFunctions userFunction,因此在userFunction.searchImageActor(mIdActor)内调用getDataUrlFromServer()时会收到NullPointerException