1

I am trying to write a code that downloads a picture from a url, and put it in ImageView.

The Class that downloads it, is UrlDoanload that returns the raw image in a byte array.

the Main Activity uses a AsyncTask inner private class to call UrlDoanload. in the onPostExecute method it puts the byte array in a ImageView, by using Bitmap, BitmapFactory objects.

the problem is, that the Bitmap object becomes null.

this is the code:

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 layout:

<?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>

this is the 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)

thanks!

Zag Gol
  • 1,038
  • 1
  • 18
  • 43
  • 2
    Why do so much of hectic code, i use this library to handle images: https://github.com/nostra13/Android-Universal-Image-Loader And it just uses one line to download and display an image in th e ImageView: imageLoader.displayImage(imageUri, imageView); – Sarthak Mittal Nov 23 '14 at 13:17
  • I tried using Image-loder, and still dosent work. this is the code (with a diffrent url): 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"; ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) .build(); ImageLoader.getInstance().init(config); ImageLoader.getInstance().displayImage(url, imageView); – Zag Gol Nov 23 '14 at 13:38
  • 1
    mine worked in dozens of projects i made, maybe you are missing something, moreover if image is of big size then it takes some time to show up – Sarthak Mittal Nov 23 '14 at 13:45
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Simon Nov 23 '14 at 14:18

2 Answers2

2

the Bitmap object becomes null

Try using a URL to an image. Your code is using a URL to a HTML page.

Also, please consider using any number of existing libraries for this, such as Picasso or Ion.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I changed the url to a image url. this is the new 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 it still dosent work. – Zag Gol Nov 23 '14 at 13:31
1

It works!

i changed the layout. insted of a layout that is only a ImageView, i put the ImageView in a linerarLayout.

this is my new layout:

<?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>

and this is the new onCreate method code:

@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();
    }
Zag Gol
  • 1,038
  • 1
  • 18
  • 43