我有一些代码我应该认为可以读取我的Galaxy S5上的地磁传感器,但每当它试图发射它时,立即崩溃只是说它崩溃了。我不知道代码可能会出现什么问题,但似乎没有任何错误。任何想法?
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) {
}
}
答案 0 :(得分:2)
调用setcontentView方法后,必须实例化变量。所以你必须做以下事情:
Mtext = (TextView)findViewById(R.id.<textview id from activity main>);