Trevader24135 Trevader24135 - 2 months ago 23
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?

package com.gmail.~~~~~~~~.magnetictest;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mSensor;
TextView Mtext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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

@Override
public void onSensorChanged(SensorEvent event) {
Mtext.setText(String.valueOf(event.values[0]));
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

Answer

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

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