您好我對android非常陌生。我正在嘗試編寫一個可以收集傳感器數據的代碼。我嘗試了「http://developer.android.com/guide/topics/sensors/sensors_overview.html」中給出的示例。現在,我在手機(Samsung Galaxy S3)上安裝了apk文件,該應用程序運行但崩潰。這是我寫的代碼:如何顯示傳感器數據值
每當我把行「tv1.setText(Float.toString(lux));應用程序崩潰;」在onSensoeChanged()方法中。請告訴我在這裏做錯了什麼,以及如何更正代碼。
這是我第一篇文章在這個網站。對於張貼問題,任何不正確的格式道歉
感謝
'
package com.example.sensordata;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity implements SensorEventListener {
public SensorManager mSensorManager;
public Sensor mLight;
public TextView tv1;
//public TextView tv2;
@Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
tv1 = (TextView) findViewById(R.id.text1);
//tv2 = (TextView) findViewById(R.id.text2);
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
synchronized (this) {
float lux = event.values[0];
// Do something with this sensor value.
//tv1 = (TextView) findViewById(R.id.text1);
tv1.setText(Float.toString(lux));
}
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
}
`
嗨Shamm我試圖tv1.setText(Float.toString(勒克斯)) ;但該應用程序仍然崩潰。每當我嘗試引用文本視圖tv1.setText應用程序停止工作...這裏是xml代碼fragment_main.xml,我把textview ... – asa