8

I'm am fairly new to android development and ran into an issue where I am trying to create an image array that shows in a gallery and when I click on a picture, it shows the the pic at the bottom. When I run the app, it crashes. Any help i can get will be very very helpful. And thanks in advance.

My questions are

  1. How do I get rid of the NullPointerException?
  2. I'm I decoding the pictures correctly? Can someone show me a better way?

Thanks

My layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".PicturesActivity" >

    <Gallery
        android:id="@+id/gallery1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/trophykiss" />

</RelativeLayout>

MY CLASS:

public class PicturesActivity extends Activity {   

    Bitmap[] myImages = new Bitmap[] {
         BitmapFactory.decodeResource(getResources(), R.drawable.champions),
         BitmapFactory.decodeResource(getResources(), R.drawable.trophykiss),
         BitmapFactory.decodeResource(getResources(), R.drawable.championstwo),
         BitmapFactory.decodeResource(getResources(), R.drawable.trophies),
         BitmapFactory.decodeResource(getResources(), R.drawable.culture),
         BitmapFactory.decodeResource(getResources(), R.drawable.maintrophy),
         BitmapFactory.decodeResource(getResources(), R.drawable.dive),
         BitmapFactory.decodeResource(getResources(), R.drawable.naijamain),
         BitmapFactory.decodeResource(getResources(), R.drawable.ethiopia),
         BitmapFactory.decodeResource(getResources(), R.drawable.peru),
         BitmapFactory.decodeResource(getResources(), R.drawable.funtime),
         BitmapFactory.decodeResource(getResources(), R.drawable.skils),
         BitmapFactory.decodeResource(getResources(), R.drawable.gabon),
         BitmapFactory.decodeResource(getResources(), R.drawable.gambia),
         BitmapFactory.decodeResource(getResources(), R.drawable.guinea)
    };


    private ImageView imageView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pictures);

        Gallery g = (Gallery) findViewById(R.id.gallery1);
        g.setAdapter(new ImageAdapter(this));
        imageView = (ImageView) findViewById(R.id.image1);



                g.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "pic: " + position,
                        Toast.LENGTH_SHORT).show();
                imageView.setImageBitmap(myImages[position]);

            }



        });
    }

    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray a = obtainStyledAttributes(R.styleable.MyGallery);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.MyGallery_android_galleryItemBackground, 0);
            a.recycle();
        }

        public int getCount() {
            return myImages.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);


            i.setImageBitmap(myImages[position]);
            i.setLayoutParams(new Gallery.LayoutParams(200, 200));
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setBackgroundResource(mGalleryItemBackground);

            return i;
        }
    }
}

ERROR MESSAGE:

java.lang.NullPointerException: Attempt to invoke virtual method 
'android.content.res.Resources android.content.Context.getResources()
codeMagic
  • 44,549
  • 13
  • 77
  • 93
Toye
  • 483
  • 1
  • 4
  • 7
  • 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) – StackFlowed Apr 16 '15 at 14:30

1 Answers1

5

1) You can't access your Context object before onCreate() has been called in your current activity. For the way you currently have it to work, just move the initialization of your array into your onCreate() method.

2) Since you're decoding so many images at once, this should happen on a background thread. Look at the AsyncTask documentation for how to pull the image loading out into a separate thread.

Submersed
  • 8,810
  • 2
  • 30
  • 38
  • Ok thanks for the quick response @Submersed. I will give this a shot and let you know what happens but what you said make sense. Thanks again – Toye Apr 16 '15 at 14:28
  • now im getting out of memory error when i move the array into the onCreate block. Im assuming the asynctask process should fix that? – Toye Apr 16 '15 at 14:42
  • How large are the images you're loading, and do you have them correctly defined in each of the qualified drawable folders? The AsyncTask won't fix an OutOfMemory exception. Remember if you only specify drawables in the drawable folder without a qualifier, they're treated as mdpi, so they'll be scaled up on higher density devices. – Submersed Apr 16 '15 at 14:48
  • They are quite big. Im not sure exactly how big they are but i did put all those images in all the drawable folders. – Toye Apr 16 '15 at 14:52
  • You're likely running out of memory by loading them all in at once. If you're interested in seeing where this occurs, you could loop through an array of your resource ids, attempt to load each in a try catch block -- however, It might be worth while to use an image loading library like Picasso to handle the image loading for you since it manages a bitmap cache for you, but this is really a separate question at this point. – Submersed Apr 16 '15 at 14:55
  • Perfect. I will read up on Async Task and Picasso then. I really appreciate your time. Thanks again – Toye Apr 16 '15 at 14:57
  • No problem, lastly if you use Picasso they handle the AsyncTask part for you. Also, if this solved the issue please accept the answer to close the question. – Submersed Apr 16 '15 at 14:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75421/discussion-between-user118742-and-submersed). – Toye Apr 16 '15 at 17:46