0

I know this question has been asked many times but none of the other answers helped me. My code works perfectly when I comment out setOnClickListener.

So, this is my main activity...

public class StartingPoint extends ActionBarActivity {

int ctr = 0;
Button add, sub;
TextView display;

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

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

    //find views
    display = (TextView) findViewById(R.id.tvTotal);
    add = (Button)this. findViewById(R.id.bAdd);
    sub = (Button)this. findViewById(R.id.bSub);

    //click listeners
    OnClickListener lis = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            ctr++;
            display.setText("The total is " + ctr);
        }
    };
    add.setOnClickListener(lis);

    /**sub.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            ctr--;
            display.setText("The total is " + ctr);
        }
    });*/

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {...}

@Override
public boolean onOptionsItemSelected(MenuItem item) {...}

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_starting_point,
                container, false);
        return rootView;
    }
}

}

The add.setOnClickListener(lis); makes the app crash.

This is the fragment_starting_point.xml...

<LinearLayout 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:orientation="vertical" >

<TextView
    android:id="@+id/tvTotal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="The total is 0"
    android:layout_gravity="top"
    android:gravity="center"
    android:textSize="30sp"
    android:textColor="@color/red"
/>

<Button
    android:id="@+id/bAdd"
    android:layout_width="150sp"
    android:layout_height="wrap_content"
    android:text="Add 1"
    android:textSize="20sp"
    android:layout_gravity="center"
    android:gravity="center"
    />

<Button
    android:id="@+id/bSub"
    android:layout_width="150sp"
    android:layout_height="wrap_content"
    android:text="Subtract 1"
    android:textSize="20sp"
    android:layout_gravity="center"
    android:gravity="center"
/>

This is what logCat says...

05-19 23:23:09.700: D/CLIPBOARD(16417): Hide Clipboard dialog at Starting input:         finished by someone else... !
05-19 23:23:34.085: I/dalvikvm(16518): Could not find method     android.widget.LinearLayout$LayoutParams.<init>, referenced from method     android.support.v7.internal.view.menu.ActionMenuView$LayoutParams.<init>
05-19 23:23:34.085: W/dalvikvm(16518): VFY: unable to resolve direct method 8208:    Landroid/widget/LinearLayout$LayoutParams;.<init> (Landroid/widget/LinearLayout$LayoutParams;)V
05-19 23:23:34.085: D/dalvikvm(16518): VFY: replacing opcode 0x70 at 0x0000
05-19 23:23:34.115: D/CLIPBOARD(16518): Hide Clipboard dialog at Starting input: finished by someone else... !
05-19 23:23:37.760: D/CLIPBOARD(16518): Hide Clipboard dialog at Starting input: finished by someone else... !
05-19 23:28:52.000: D/AndroidRuntime(16834): Shutting down VM
05-19 23:28:52.000: W/dalvikvm(16834): threadid=1: thread exiting with uncaught exception (group=0x40192760)
05-19 23:28:52.000: E/AndroidRuntime(16834): FATAL EXCEPTION: main
05-19 23:28:52.000: E/AndroidRuntime(16834): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example2.mysecondapp/com.example2.mysecondapp.StartingPoint}: java.lang.NullPointerException
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.app.ActivityThread.access$500(ActivityThread.java:122)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.os.Looper.loop(Looper.java:132)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.app.ActivityThread.main(ActivityThread.java:4123)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at java.lang.reflect.Method.invokeNative(Native Method)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at java.lang.reflect.Method.invoke(Method.java:491)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at dalvik.system.NativeStart.main(Native Method)
05-19 23:28:52.000: E/AndroidRuntime(16834): Caused by: java.lang.NullPointerException
05-19 23:28:52.000: E/AndroidRuntime(16834):    at com.example2.mysecondapp.StartingPoint.onCreate(StartingPoint.java:47)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
05-19 23:28:52.000: E/AndroidRuntime(16834):    at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
05-19 23:28:52.000: E/AndroidRuntime(16834):    ... 11 more
05-19 23:28:59.720: I/Process(16834): Sending signal. PID: 16834 SIG: 9

I did not know exactly what would be required so I just posted everything I thought was relevant, I'm still new to this. I'd really appreciate any help.

Mandira
  • 3
  • 3
  • What is on `StartingPoint.java` at line 47? – Emmanuel May 19 '14 at 18:27
  • NullPointerException StartingPoint.java:47 – Marco Acierno May 19 '14 at 18:29
  • copy the whole contents in `fragment_starting_point.xml` to `activity_main.xml` – Lal May 19 '14 at 18:33
  • or change `setContentView(R.layout.activity_starting_point);` to `setContentView(R.layout.fragment_starting_point);` – Lal May 19 '14 at 18:34
  • Check my answer or for a temporary solution try the earlier comment which i said... – Lal May 19 '14 at 18:36
  • @Lal omg don't change the content view. This is obviously a mistake because @Mandira does not understand how layouts work with `Fragments` and `Activities`. I think your suggestion will just cause more confusion and doesn't really solve the problem. – Xaver Kapeller May 19 '14 at 18:40
  • I've said the right way as my answer...@XavierKapeller..This was just for a quick solution.. – Lal May 19 '14 at 18:41

2 Answers2

1

The layout of your Fragment contains a Button with the id R.id.bAdd, the layout of your Activity does not. That's the source of your error, this line:

add = (Button)this.findViewById(R.id.bAdd);

Cannot find the Button in the layout of the Activity and therefore it returns null. After that when you try to set the OnClickListener you get a NullPointerException.

What you have to do is move all of the interaction with the Buttons etc into the Fragment it doesn't belong in the Activity as it is not part of the layout of the Activity. Override the onCreateView() method in your Fragment and inflate your layout there and then look for the Views like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_starting_point, container, false);

    this.add = (Button) view.findViewById(R.id.bAdd);

    return view;
}

You can then add your OnClickListener in onViewCreated():

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    this.add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ...    
        }
    });
}
Xaver Kapeller
  • 49,491
  • 11
  • 98
  • 86
0

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

Lal
  • 14,726
  • 4
  • 45
  • 70