java - Unexpected Crash Android Sensors -
whenever try run crashes. not know problem be. missing or in wrong place?in logcat says system services not avaliable activities before oncreate.
import android.os.bundle; import android.app.activity; import android.hardware.sensor; import android.hardware.sensorevent; import android.hardware.sensoreventlistener; import android.hardware.sensormanager; import android.os.handler; import android.view.menu; import android.widget.*; import android.*; import java.math.*; import java.text.*; import java.util.*; public class mainactivity extends activity implements sensoreventlistener { private final sensormanager msensormanager; private final sensor mrotationvector; public float x,y,z; public mainactivity(){ msensormanager = (sensormanager)getsystemservice(sensor_service); mrotationvector = msensormanager.getdefaultsensor(sensor.type_rotation_vector); } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } protected void onresume() { super.onresume(); msensormanager.registerlistener(this, mrotationvector, sensormanager.sensor_delay_game); } protected void onpause() { super.onpause(); msensormanager.unregisterlistener(this); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); return true; } @override public void onaccuracychanged(sensor sensor, int accuracy) { // todo auto-generated method stub } @override public void onsensorchanged(sensorevent event) { x= event.values[0]; y= event.values[1]; z= event.values[2]; textview mtextview0 = (textview) findviewbyid(r.id.textview0); mtextview0.settext("x"+x); textview mtextview1 = (textview) findviewbyid(r.id.textview1); mtextview1.settext("y"+y); textview mtextview2 = (textview) findviewbyid(r.id.textview2); mtextview2.settext("z"+z); } }
system services not avaliable activities before oncreate
your logcat telling !
so change
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); msensormanager = (sensormanager)getsystemservice(sensor_service); mrotationvector = msensormanager.getdefaultsensor(sensor.type_rotation_vector); }
and remove constructor public mainactivity()
.
Comments
Post a Comment