Android Studio - java.lang.NullPointerException:尝试调用虚方法'void android.widget.Button.setOnClickListener

时间:2016-11-06 01:50:24

标签: java android nullpointerexception

我在我的android studio应用程序中创建了一个新活动,我有一个按钮,可以在单击时执行操作。我不确定是什么导致了错误,因为当我实际运行活动时会发生这种情况。如果我删除onClick代码,则活动将运行。谢谢你的帮助。我收到了这个错误:

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)

这是我的Main2Activity.java代码:

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

}

这是我的XML代码

<?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>

1 个答案:

答案 0 :(得分:4)

OnCreate方法中,您应始终首先放置

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

这是因为在您使用setContentView设置视图之前,视图不会膨胀。这意味着任何findViewById之前的调用都会返回null

此外,您还必须在super.onResume(...)最开始处设置onResume()来电,正如Android文档所述。这也适用于其他生命周期方法。这也应解决您的setText问题。