0

I'm having a problem with Null Pointer Exception which is threw by setOnClickListener.

I'm trying to make an application processing an image, and I want to load and image from gallery.

I've been reading lots of posts here but I still don't understand what's happening.

Why Am I getting NullPointerException?

Here is my code:

 import android.net.Uri;
 import android.support.v7.app.ActionBarActivity;
 import android.support.v4.app.Fragment;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.graphics.*;
 import android.graphics.drawable.*;
 import android.content.Intent;
 import android.app.Activity;
 public class MainActivity extends ActionBarActivity {
Bitmap oryginal;
ImageView image;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

    image = (ImageView) findViewById(R.id.imageView);
    image.setOnClickListener(new View.OnClickListener() { here is the Null Pointer Exception
        @Override
        public void onClick(View view) {

            Intent gallery = new Intent();
            gallery.setType("image/*");
            gallery.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(gallery,"Select Image"),1);

        }
    });


}

public void onActivityResult(int requestCode , int resultCode, Intent data)
{

    if(resultCode  == RESULT_OK)
    {
        if(requestCode ==1)
        {
            image.setImageURI(data.getData());
        }
    }
}

Here is my fragment_main.xml where I have my ImageView (in the first paragraph)

    <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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.app.MainActivity$PlaceholderFragment"
android:background="#ffe93d"
android:focusable="false">

<ImageView
    android:layout_width="300dp"
    android:layout_height="400dp"
    android:id="@+id/imageView"
    android:src="@drawable/tucano"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/oryginal"
    android:id="@+id/oryginal"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="Oryginal" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/kotim"
    android:layout_below="@+id/imageView"
    android:layout_toLeftOf="@+id/oryginal"
    android:visibility="invisible"
    android:src="@drawable/kot" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/lennaim"
    android:layout_above="@+id/oryginal"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:visibility="invisible"
    android:src="@drawable/lenna" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/lennaim"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:visibility="invisible"
    android:src="@drawable/obrazek"
    android:id="@+id/stworim"
    android:focusableInTouchMode="false" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/help"
    android:id="@+id/help"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="Help" />

Details:

Details:

   04-07 16:01:14.162    1451-1451/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}:               java.lang.NullPointerException
               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
               at android.app.ActivityThread.access$600(ActivityThread.java:141)
               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
               at android.os.Handler.dispatchMessage(Handler.java:99)
               at android.os.Looper.loop(Looper.java:137)
               at android.app.ActivityThread.main(ActivityThread.java:5041)
               at java.lang.reflect.Method.invokeNative(Native Method)
               at java.lang.reflect.Method.invoke(Method.java:511)
               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
               at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.NullPointerException
               at com.example.app.MainActivity.onCreate(MainActivity.java:36)
               at android.app.Activity.performCreate(Activity.java:5104)
               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
               at android.app.ActivityThread.access$600(ActivityThread.java:141)
               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
               at android.os.Handler.dispatchMessage(Handler.java:99)
               at android.os.Looper.loop(Looper.java:137)
               at android.app.ActivityThread.main(ActivityThread.java:5041)
               at java.lang.reflect.Method.invokeNative(Native Method)
               at java.lang.reflect.Method.invoke(Method.java:511)
               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
               at dalvik.system.NativeStart.main(Native Method)
user3131037
  • 425
  • 1
  • 6
  • 20
  • 1
    My bet is that `image = (ImageView) findViewById(R.id.imageView);` is returning `null`. Are you completely sure you have a `ImageView` called `R.id.imageView` in your `activity_main` layout file? – nKn Apr 07 '14 at 16:15
  • Show activity_main.xml – Onik Apr 07 '14 at 16:16
  • @nKn yes, he/she has: `android:id="@+id/imageView"` - 1st imageview - But it's into the wrong layout.. – Blo Apr 07 '14 at 16:22
  • 1
    Put the code from fragment_main.xml into activity_main.xml – Onik Apr 07 '14 at 16:22
  • I've done it, and It still didn't solve the problem. Now I'm wondering.. When the code was in fragment_main.xml and it didn't contain the part concerning loading image from gallery application works well. Why? Shouldn't the code be always in activity_main then? – user3131037 Apr 07 '14 at 16:31
  • @user3131037 You probably got rid of NPE in question and now you have another issue. Look at your logcat again. – Onik Apr 07 '14 at 16:37
  • See this question, he has the same problem than yours: http://stackoverflow.com/q/22917626/2668136 It might help you, especially the comments below the issue and the answer. – Blo Apr 07 '14 at 16:46

2 Answers2

0

The problem is that you're setting your content as this:

setContentView(R.layout.activity_main);

But as per your code, the required ImageView is in this file: Here is my fragment_main.xml where I have my ImageView (in the first paragraph), therefore my assumption of:

image = (ImageView) findViewById(R.id.imageView); is returning null

is true and you're getting the NullPointerException error. You can just find Views that correspond to the layout declared in your setContentView() statement, otherwise it will return null.

nKn
  • 13,691
  • 9
  • 45
  • 62
  • Ok, So I have one more question, because I don't know what should I do now. I have all my code in fragment_main.xml, and when my application doesn't contain the part with loading image it works well. Now when I put my code from fragment_main to activity_main(or when I change this setContentView(R.layout.activity_main) to setContentView(R.layout.fragment_main)) the application doesn't work. I have no idea what to do with it. – user3131037 Apr 07 '14 at 16:43
  • Yes, that's because of how `Fragment`s work, only the current is active so if you try doing this on a `Fragment` that is currently active everything will go smoothly, but if the `Fragment` is `detach()`ed or `delete()`d, you'll get an error. You might want to wrap the `Fragment`s inside a `ViewPager` so the global code goes here and applies to all the design you have. Have a look here: http://developer.android.com/reference/android/support/v4/view/ViewPager.html – nKn Apr 07 '14 at 16:48
0

Your ImageView is in Fragment Layout while you are trying to initialize variable using Activity's method FindViewByID.
To do that properly get your fragment's View reference and then call View.FindViewByID().
Also I would advise to change your Image's View ID just in case.

user3455363
  • 408
  • 1
  • 5
  • 13