Radon5K
Radon5K

Reputation: 47

Android Studio - java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener

I created a new activity in my android studio app and I have a button that performs an action when click. I am not sure what's causing the error as this happens when I actually run the activity. If I remove the onClick code, the activity runs. Thanks for any help. I'm getting this error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.masesk.kalkulator, PID: 4102
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.masesk.kalkulator/com.masesk.kalkulator.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                      at com.masesk.kalkulator.Main2Activity.onCreate(Main2Activity.java:29)
                      at android.app.Activity.performCreate(Activity.java:6237)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                      at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:5417) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

This is my Main2Activity.java code:

package com.masesk.kalkulator;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

public class Main2Activity extends AppCompatActivity {
    private ToggleButton textToBinary;
    private Button trace;
    private EditText text;
    private EditText binary;
    private String textInput;
    private String binaryInput;
    StringBuilder binaryText = new StringBuilder();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.textToBinary = (ToggleButton)findViewById(R.id.textToBinary);
        this.trace = (Button)findViewById(R.id.trace);
        this.text = (EditText)findViewById(R.id.text);
        this.binary = (EditText)findViewById(R.id.binary);

        trace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(textToBinary.isActivated() == false){
                    textInput = text.getText().toString();
                    byte[] bytes = textInput.getBytes();
                    StringBuilder binary = new StringBuilder();
                    for (byte b : bytes)
                    {
                        int val = b;
                        for (int i = 0; i < 8; i++)
                        {
                            binaryText.append((val & 128) == 0 ? 0 : 1);
                            val <<= 1;
                        }
                        binaryText.append(' ');
                    }
                }
            }
        });
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }
    @Override
    public void onResume(){
        this.binary = (EditText)findViewById(R.id.binary);
        binary.setText(binaryText.toString(), TextView.BufferType.EDITABLE);
    }

}

and here is my XML code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main2"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.masesk.kalkulator.Main2Activity"
    tools:showIn="@layout/activity_main2">

    <ToggleButton
        android:text="ToggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/textToBinary"
        android:layout_alignParentEnd="true"
        android:textOff="Binary To Text"
        android:textOn="Text to Binary" />

    <TextView
        android:text="Text:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textToBinary"
        android:layout_alignParentStart="true"
        android:id="@+id/textView2"
        android:layout_alignParentEnd="true" />

    <EditText
        android:background="@drawable/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true"
        android:id="@+id/text"
        android:layout_alignParentEnd="true" />

    <TextView
        android:text="Binary Code:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text"
        android:layout_alignParentStart="true"
        android:id="@+id/textView3" />

    <EditText
        android:background="@drawable/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/textView3"
        android:layout_alignParentStart="true"
        android:id="@+id/binary"
        android:layout_alignParentEnd="true" />

    <Button
        android:text="convert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/binary"
        android:layout_alignParentStart="true"
        android:layout_marginTop="14dp"
        android:id="@+id/trace"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

Upvotes: 0

Views: 4882

Answers (1)

thatguy
thatguy

Reputation: 22089

In the OnCreate method, you should always first put

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

This is because the view is not inflated until you have set it with setContentView. This means any findViewById call before will return null.

Additionally, you must also set the super.onResume(...) call at the very beginning of onResume(), as the Android documentation states. This also goes for the other lifecycle methods as well. This should also solve your setText problem.

Upvotes: 4

Related Questions