NullPointerException on Button.findViewById() [英] NullPointerException on Button.findViewById()

查看:74
本文介绍了NullPointerException on Button.findViewById()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了在Android Studio中创建对话框的教程.我的代码在Java文件中未显示任何错误,但显示不幸的是,应用程序已停止工作".我不知道为什么.

I followed a tutorial to create a dialog in Android Studio. My code shows no error in the Java file, but says "Unfortunately app has stopped working". I don't know why.

我的Java文件:

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private static Button b1;

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

    public void onButoonListener(){
        b1=(Button) b1.findViewById(R.id.button);
        b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder ad = new          AlertDialog.Builder(MainActivity.this);
                    ad.setMessage("Do you want to   close").setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).setNegativeButton("no", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                    AlertDialog ad1= ad.create();
                    ad1.setTitle("Alert!!");
                    ad1.show();
                }
            });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

我的Xml好友:

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="188dp" />

</RelativeLayout>

我的Logcat:

 06-13 21:32:20.500  11336-11336/hilz.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: hilz.myapplication, PID: 11336
        java.lang.RuntimeException: Unable to start activity ComponentInfo{hilz.myapplication/hilz.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:135)
                at android.app.ActivityThread.main(ActivityThread.java:5257)
                at java.lang.reflect.Method.invoke(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:372)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
                at hilz.myapplication.MainActivity.onButoonListener(MainActivity.java:23)
                at hilz.myapplication.MainActivity.onCreate(MainActivity.java:20)
                at android.app.Activity.performCreate(Activity.java:5990)
                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:135)
                at android.app.ActivityThread.main(ActivityThread.java:5257)
                at java.lang.reflect.Method.invoke(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:372)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

推荐答案

您以错误的方式调用了findViewById()方法.应该在Activity本身而不是在Button引用上调用它.替换

You are invoking the findViewById() method in the wrong way. It should be invoked on the Activity itself, not on the Button reference. Replace

b1=(Button) b1.findViewById(R.id.button);

使用

b1=(Button) findViewById(R.id.button);

b1引用此时为null,这是NullPointerException的原因.

The b1 reference is null at that point, and is the reason for the NullPointerException.

这篇关于NullPointerException on Button.findViewById()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆