Meindert Stijfhals
Meindert Stijfhals

Reputation: 355

Android - Java - Buttonclicker nullpointerexception

I want to make a buttonclicker. When I press the btnKopen I want the textView 'BonnenMand' to display the amount of times how many the button has been clicked.

This is the code I use for this:

Button btnKopen;
TextView bonnenMand;
int bonnenMandCounter = 0;    

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

    Button btnKopen = (Button) findViewById(R.id.buttonKopen);
    final TextView bonnenMand = (TextView) findViewById(R.id.textViewItemCount);  

    btnKopen.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            bonnenMandCounter++;
            bonnenMand.setText(bonnenMandCounter);
        }
    });
}

I get a NullPointerException and the application crashes before it opens.

01-04 14:02:48.649 13685-13685/? I/art: Late-enabling -Xcheck:jni
01-04 14:02:48.704 13685-13685/? W/System: ClassLoader referenced unknown path: /data/app/be.ehb.dt.bestellingen-1/lib/arm
01-04 14:02:48.774 13685-13685/? D/AndroidRuntime: Shutting down VM
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime: FATAL EXCEPTION: main
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime: Process: be.ehb.dt.bestellingen, PID: 13685
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{be.ehb.dt.bestellingen/be.ehb.dt.bestellingen.Winkel}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at be.ehb.dt.bestellingen.Winkel.onCreate(Winkel.java:79)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:6251)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.-wrap11(ActivityThread.java) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
01-04 14:02:48.774 13685-13685/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
01-04 14:02:51.469 13685-13685/? I/Process: Sending signal. PID: 13685 SIG: 9

EDIT: The button does not exist in my main_activity.xml, The button gets added using the following arrayAdapter..

public class MenuAdapter extends ArrayAdapter<MenuWinkel> {

        public MenuAdapter(Context context, ArrayList<MenuWinkel> menus) {
            super(context, 0, menus);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            MenuWinkel menu = getItem(position);

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.winkelrow, parent, false);
            }

            TextView menuName = (TextView) convertView.findViewById(R.id.textViewMenu);
            TextView menuPrice = (TextView) convertView.findViewById(R.id.textViewPrijs);

            menuName.setText(menu.getNaam());
            if(menu.getPrijs() > 0.0) {
                StringTokenizer tokens = new StringTokenizer(menu.getPrijs()+"", ".");
                String first = tokens.nextToken();// this will contain "Fruit"
                String second = tokens.nextToken();

                    if (second.equals("0")) {
                        menuPrice.setText(first);
                    } else {
                        menuPrice.setText(first + "," + second);
                    }

            }

            return convertView;
        }
    }

This makes me able to place items like this:

 ArrayList<MenuWinkel> arrayOfMenus = new ArrayList<MenuWinkel>();
        MenuAdapter menuAdapter = new MenuAdapter(this,arrayOfMenus);

 MenuWinkel menu1 = new MenuWinkel("10% korting op drank bij menu",50.0);
        menuAdapter.add(menu1);
        MenuWinkel menu2 = new MenuWinkel("30% korting op drank bij menu",70.0);
        menuAdapter.add(menu2);
        MenuWinkel menu3 = new MenuWinkel("70% korting op drank bij menu",120.0);

This arrayadapter adds items with the following XML:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="106.5dp"
        android:id="@+id/imageBackground"
        android:src="@drawable/banner_wit"
        android:layout_marginTop="4.5dp"
        android:contentDescription="@string/banner_white"
        android:scaleType="fitXY"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="85dp"
        android:id="@+id/imageViewMenu"
        android:src="@drawable/drinks"
        android:contentDescription="Drinks"
        android:layout_weight="0.28"
        android:layout_marginTop="13dp"
        android:layout_marginLeft="-2dp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textViewMenu"
            android:layout_gravity="center"
            android:textColor="#1D1D1B"
            android:layout_weight="0.65"
            android:paddingLeft="10dp"
            android:layout_marginTop="0dp"
            android:layout_marginBottom="10dp"/>

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:id="@+id/imageCaps"
            android:src="@drawable/caps"
            android:layout_weight="0.01"
            android:layout_marginTop="30dp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/textViewPrijs"
            android:layout_gravity="center_vertical"
            android:textColor="#fff"
            android:layout_weight="0.10"
            android:layout_marginLeft="-35dp"
            android:layout_marginTop="8dp" />

    </LinearLayout>

    <Button
        android:layout_width="100dp"
        android:layout_height="30dp"
        android:text="Kopen"
        android:id="@+id/buttonKopen"
        android:textColor="#fff"
        android:background="@drawable/borderradiuskopen"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="40dp"
        android:layout_gravity="center_horizontal|bottom"
        />
</FrameLayout>

In this XML you can find the buttonID for buttonKopen.

Upvotes: 0

Views: 130

Answers (3)

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

You are getting

AndroidRuntime: Caused by: java.lang.NullPointerException

I assume problem is setText method .

At first, You can use

bonnenMand.setText(String.valueOf(bonnenMandCounter));

Second

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'

When you try to use Any nullable object then NPE is getting.Any object that not initialize or not give correct refrences .Also View have not give correct refrences from xml.

My advice , Make sure proper Button Click .I mean check id .

Upvotes: 1

2Dee
2Dee

Reputation: 8627

Your error is

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

It is caused by these lines :

Button btnKopen = (Button) findViewById(R.id.buttonKopen);
btnKopen.setOnClickListener(...);

It is due to the fact that there is no button with id R.id.buttonKopen included in activity_main.xml

To add a click listener to your button, do it in the getView method of your MenuAdapter.

Upvotes: 2

Deepak John
Deepak John

Reputation: 967

replace final TextView bonnenMand = (TextView) findViewById(R.id.textViewItemCount); with

bonnenMand = (TextView) findViewById(R.id.textViewItemCount); 

and replace bonnenMand.setText(bonnenMandCounter); with

bonnenMand.setText(String.valueOf(bonnenMandCounter));

Upvotes: 0

Related Questions