I have an error while using setOnClickListener

advertisements

This question already has an answer here:

  • NullPointerException accessing views in onCreate() 12 answers

I got the program to crash when using the simple code below as it is closed automatically after installing it

package com.zaki.thenewboston;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    int         counter;
    Button      add,sub;        //used to reference to xml view ids
    TextView    display;        //used to reference to xml view ids

    @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();
        } 

            //zaki: this is to wait the R.layout.activity_main to load first other wise the program may crash
            counter =0;
            add = (Button) findViewById(R.id.bAdd);
           // sub = (Button) findViewById(R.id.bSub);
            display = (TextView) findViewById(R.id.tvDisplay);
            add.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    counter ++;
                    display.setText("Your total is" + counter);

                }
            });

          /*
            sub.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    counter --;
                    display.setText("Your total is" + counter);
                }
            });*/

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    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_main, container, false);
            return rootView;
        }
    }

}

Here is the logcat: I think there is a null returned, but why? I don't know the reason. and I'm sure that the problem in onCreateView

09-21 12:58:37.277: D/AndroidRuntime(1449): Shutting down VM
09-21 12:58:37.277: W/dalvikvm(1449): threadid=1: thread exiting with uncaught exception (group=0xb2a81ba8)
09-21 12:58:37.277: E/AndroidRuntime(1449): FATAL EXCEPTION: main
09-21 12:58:37.277: E/AndroidRuntime(1449): Process: com.zaki.thenewboston, PID: 1449
09-21 12:58:37.277: E/AndroidRuntime(1449): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zaki.thenewboston/com.zaki.thenewboston.MainActivity}: java.lang.NullPointerException
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.os.Looper.loop(Looper.java:136)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.main(ActivityThread.java:5017)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at java.lang.reflect.Method.invokeNative(Native Method)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at java.lang.reflect.Method.invoke(Method.java:515)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at dalvik.system.NativeStart.main(Native Method)
09-21 12:58:37.277: E/AndroidRuntime(1449): Caused by: java.lang.NullPointerException
09-21 12:58:37.277: E/AndroidRuntime(1449):     at com.zaki.thenewboston.MainActivity.onCreate(MainActivity.java:38)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.Activity.performCreate(Activity.java:5231)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-21 12:58:37.277: E/AndroidRuntime(1449):     ... 11 more

the file Activity_main.xml is below

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zaki.thenewboston.MainActivity"
    tools:ignore="MergeRootFrame" />

and the file fragment_main.xml is below

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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="com.zaki.thenewboston.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/tvDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/your_total_is" />

    <Button
     android:layout_width="240dp"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="@string/add_one"
     android:textSize="20sp"
     android:id="@+id/bAdd"
     />

    <Button
     android:layout_width="240dp"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="@string/subtract_one"
     android:textSize="20sp"
     android:id="@+id/bSub"
     />

</LinearLayout>

note also that i changed the line

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

to be

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

and the problem still exists


i discovered that the problem isn't only in moving the code to the PlaceholderFragment as i got a new compilation error as i posted

but also the following codes

            add = (Button) findViewById (R.id.bAdd);
            sub = (Button) findViewById(R.id.bSub);
            display = (TextView) findViewById(R.id.tvDisplay);

should be converted to be as following

            add = (Button) rootView.findViewById (R.id.bAdd);
            sub = (Button) rootView.findViewById(R.id.bSub);
            display = (TextView) rootView.findViewById(R.id.tvDisplay);

i appreciate comments with the explanation to what i made