类的定义按钮上的Android Studio NullPointerException

时间:2017-10-01 10:14:29

标签: java android nullpointerexception

我使用的是Android工作室,我只知道基本的java。 我知道我需要在类上声明Widgets以在另一个函数中使用它,但它仍然会给出null引用错误。

package com.uruskan.shock.kultureventbase;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity implements 
View.OnClickListener {
TextView tv;
Button bYemek, bSleep, bAttack;
int sayac = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.event_date);
    Button bYemek = (Button) findViewById(R.id.button); //yemek ye
    Button bSleep = (Button) findViewById(R.id.button2); //uyu
    Button bAttack = (Button) findViewById(R.id.attack); // saldır
    bYemek.setOnClickListener(this);
    bSleep.setOnClickListener(this);
    bAttack.setOnClickListener(this);
    Karakter k = new Karakter();
    k.hareketSayisi = 10;
    k.kilo = 10;
    k.saldiriGücü = 100;

}

@Override
public void onClick(View v) {
    if (v.getId() == bAttack.getId()) {
        //Attack Code
        tv.setText("Attack ");
    } else if (v.getId() == bSleep.getId()) {
        //sleep code
        tv.setText("Sleeping Rrrrrr !");
    } else if (v.getId() == bYemek.getId()) {
        //eat code
        tv.setText("Narcissus get her, for a dinner..");
    }
}
}

2 个答案:

答案 0 :(得分:0)

更新您的代码:

bYemek = (Button) findViewById(R.id.button); //yemek ye
bSleep = (Button) findViewById(R.id.button2); //uyu
bAttack = (Button) findViewById(R.id.attack); // saldır

答案 1 :(得分:0)

您正在初始化Button变量,这些变量在onClick函数被引用时超出范围,这就是您获取NullPointerException的原因。

因此,当您将按钮声明为公共变量时,需要像这样分配变量。

bYemek = (Button) findViewById(R.id.button); //yemek ye
bSleep = (Button) findViewById(R.id.button2); //uyu
bAttack = (Button) findViewById(R.id.attack); // saldır

onClick函数中,您可以简单地执行此操作。

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.button:
            tv.setText("Narcissus get her, for a dinner..");
            return;
        case R.id.button2:
            tv.setText("Sleeping Rrrrrr !");
            return;
        case R.id.attack:
            tv.setText("Attack ");
            return;
    }
}