Android Studio - 显示传感器结果时出错?

时间:2015-05-26 13:02:41

标签: android sensor

仍然是新的...当尝试运行我的应用程序时,我只是得到一个“错误”,它关闭。如果我禁用“线”以显示传感器值,它运行没有问题。请帮助我!!

public class MainActivity extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;


    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;


    //wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    TextView baroText;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        //wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
        uiVars();
        SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);

        sensorManager.registerListener(new MyListener(), sensor,
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    public void uiVars(){
        baroText = (TextView) findViewById(R.id.zSensorInfo2);
        //timeText = (TextView) findViewById(R.id.timeTxt);
        //refresh = (Button) findViewById(R.id.baroRefreshBtn);
    }

    class MyListener implements SensorEventListener {
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            //long timestamp = event.timestamp;
            float value = event.values[0];
            // do something with the values
            String valueString = String.valueOf(value);
            //baroText.setText(valueString);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果没有logcat结果或任何其他细节,很难弄清楚您的错误是什么。如需更好的帮助,请在下次发布调试信息。

基于我在短暂查看代码时可以看到的内容,您可能在使用此行时遇到了问题?

String valueString = String.valueOf(value);
//baroText.setText(valueString);

尝试将其更改为:

String valueString = Float.toString(value);
baroText.setText(valueString);

另一个问题是您的传感器值可能根本没有返回值。那么也许先检查一下值是否为null?如果是这种情况,valueString尝试将null float值转换为一个错误输出的字符串