简体   繁体   中英

Android: Crashing when trying to download images with an AsyncTask and JSON

In my doInBackground method i am trying to create a HTTPGet and creating a JSONResponseHandler than passing both of them into mClient.execute(). The application crashed in the doInBackgroundMethod. Any help would be great. And I am fairly new to Android, which may explain some of my coding practices here. Here is my code:

public class Downloader extends AsyncTask <String, Void, List<Bitmap>>{

private static final String URL = "http://......";

private MainActivity mParentActivity;
private Context mApplicationContext;

AndroidHttpClient mClient = AndroidHttpClient.newInstance("");

// Constructor
    public Downloader(MainActivity parentActivity) {
        super();

        mParentActivity = parentActivity;
        mApplicationContext = parentActivity.getApplicationContext();

    }


@Override
protected List<Bitmap> doInBackground(String... params) {

    log("Entered doInBackground()");
    HttpGet request = new HttpGet(URL);
    JSONResponseHandler responseHandler = new JSONResponseHandler();

    try {
        return mClient.execute(request, responseHandler);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;


}

@Override
protected void onPostExecute(List<Bitmap> result)
{
    mParentActivity.setImages(result);

}

private void log(String msg)
{
    Log.i(TAG, msg);
}

private class JSONResponseHandler implements ResponseHandler<List<Bitmap>> {

    private static final String IMAGE = "cover";
    private static final String LIST = "data";

    @Override
    public List<Bitmap> handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {
        List<Bitmap> result = new ArrayList<Bitmap>();
        String JSONResponse = new BasicResponseHandler()
                .handleResponse(response);
        try {

            // Get top-level JSON Object - a Map
            JSONObject responseObject = (JSONObject) new JSONTokener(
                    JSONResponse).nextValue();

            // Extract value of "Data" key -- a List
            JSONArray images = responseObject
                    .getJSONArray(LIST);

            InputStream is = null;

            // Iterate over data list
            for (int idx = 0; idx < images.length(); idx++) {

                // Get single piece of data - a Map
                JSONObject image = (JSONObject) images.get(idx);

                // open the url
                URL coverURL = (java.net.URL) image.get(IMAGE);
                HttpURLConnection conn = (HttpURLConnection) coverURL.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
                int r = conn.getResponseCode();
                Log.d(TAG, "The response is: " + r);
                is = conn.getInputStream();

                // creates an image from the inputStream
                Bitmap imageMap = BitmapFactory.decodeStream(is);


            result.add(imageMap);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }
}
}  

My LogCat is as follows:

02-27 21:37:32.540: E/AndroidRuntime(1536): FATAL EXCEPTION: AsyncTask #1
02-27 21:37:32.540: E/AndroidRuntime(1536): Process: com.example.test, PID: 1536
02-27 21:37:32.540: E/AndroidRuntime(1536): java.lang.RuntimeException: An error occured   while executing doInBackground()
02-27 21:37:32.540: E/AndroidRuntime(1536):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at java.lang.Thread.run(Thread.java:841)
02-27 21:37:32.540: E/AndroidRuntime(1536): Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.net.URL
02-27 21:37:32.540: E/AndroidRuntime(1536):     at com.example.test.DownloadStories$JSONResponseHandler.handleResponse(DownloadStories.java:109)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at com.example.test.DownloadStories$JSONResponseHandler.handleResponse(DownloadStories.java:1)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
02-27 21:37:32.540: E/AndroidRuntime(1536):     at android.net.http.AndroidHttpClient.execute(AndroidHttpClient.java:273)

add below line into your downloader constructor,

mClient = AndroidHttpClient.newInstance("", mApplicationContext);

I think you have to pass your context to get Instance.

I believe your code is crashing as it is running out of memory during this line

 Bitmap imageMap = BitmapFactory.decodeStream(is);


        result.add(imageMap);

But what I'm not able to understand is why are you not saving the picture to a particular location during that step and releasing the memory

      void downloadFile(String fileUrl, String fileName) {
    URL myFileUrl = null;
    try {
        myFileUrl = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        if (bmImg != null) {
            bmImg.recycle();
        }

        bmImg = BitmapFactory.decodeStream(is);
        FileOutputStream out = new FileOutputStream(path + "/" + fileName + ".jpg");
        bmImg.compress(Bitmap.CompressFormat.JPEG, 50, out);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        // Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

Hence by this step you don't need to create List<Bitmap> which I'm assuming the reason behind the crash of the application

as in Log:

Permission denied (missing INTERNET permission?

Add INTERNET permission in AndroidManifest as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM