Nicky Romero Nicky Romero - 3 years ago 190
Android Question

Android Studio NullPointerException on a Defined Button on Class

Im completely beginner to android studio and i only know basic java.
I know i need to declare the Widgets on Class to use it in another function but it still gives nullreference error.And some more details what i can add more ? I hate posting things on there..

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

M M M M
Answer Source

Update you code:

bYemek = (Button) findViewById(R.id.button); //yemek ye
bSleep = (Button) findViewById(R.id.button2); //uyu
bAttack = (Button) findViewById(R.id.attack); // saldır
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download