Trevader24135 Trevader24135 - 5 months ago 47
Java Question

android studio how to read magnetic sensor

I have some code I should think would work to readout the geomagnetic sensor on my Galaxy S5, but whenever it attempts to launch it immediately crashes simply stating that it crashed. I don't know what the problem might be with the code, but there doesn't seem to be any errors. any ideas?


import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mSensor;
TextView Mtext;

protected void onCreate(Bundle savedInstanceState) {

mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mSensor, mSensorManager.SENSOR_DELAY_NORMAL);

public void onSensorChanged(SensorEvent event) {

public void onAccuracyChanged(Sensor sensor, int accuracy) {



You have to instantiate the variable after the setcontentView method was called. So you have to do the following:

Mtext = (TextView)findViewById(<textview id from activity main>);