I'm new in java and android. Trying to make some app and got NullPointerException. Please see my code below:
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class PoziomicaActivity extends Activity implements SensorEventListener {
TextView t1;
TextView t2;
TextView t3;
TextView t4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poziomica);
t1 = (TextView)findViewById(R.id.textView1);
t2 = (TextView)findViewById(R.id.textView2);
t3 = (TextView)findViewById(R.id.textView3);
t4 = (TextView)findViewById(R.id.textView4);
SensorManager sensor = (SensorManager) getSystemService(SENSOR_SERVICE);
sensor.registerListener(this,sensor.getDefaultSensor(Sensor.TYPE_ORIENTATION),0,null);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
t1.setText("event.values[0]="+event.values[0]+"\n" +
"event.values[1]="+event.values[1]+"\n"+
"event.values[2]="+event.values[2]+"\n");
String kierunek="";
if(event.values[0]==0){
kierunek="Północ (N)";
}else if(event.values[0]<90){
kierunek="Północny-wschód (NE)";
}else if(event.values[0]==90){
kierunek="Wschód (E)";
}else if(event.values[0]<180){
kierunek="Południowy-wschód (SE)";
}else if(event.values[0]==180){
kierunek="Południe (S)";
}else if(event.values[0]<270){
kierunek="Południowy-zachód (SW)";
}else if(event.values[0]==270){
kierunek="Zachód (W)";
}else if(event.values[0]<360){
kierunek="Północny-zachód (NW)";
}
t2.setText("idziesz na "+kierunek);
String pochylenie_gd="";
if(event.values[1]==0){
pochylenie_gd="poziomo";
}else if(event.values[1]>0){
pochylenie_gd="góra niżej";
}else{
pochylenie_gd="dół niżej";
}
t3.setText("Płaszczyzna góra-dół: "+pochylenie_gd);
String pochylenie_lp="";
if(event.values[2]==0){
pochylenie_lp="poziomo";
}else if(event.values[2]>0){
pochylenie_lp="lewa niżej";
}else{
pochylenie_lp="prawa niżej";
}
t4.setText("Płaszczyzna lewa-prawa: "+pochylenie_lp);
if((event.values[1]==0)&&(event.values[2]==0)){
Toast.makeText(getApplicationContext(), "Idealny poziom!", Toast.LENGTH_LONG).show();
}
}
}
Every time I got error:
java.lang.NullPointer.Exception at com.example.pomocnik.PoziomicaActivity.onSensorChenged (PoziomicaActivity.java:51).
Can someone tell me where is a problem?