我试图在我的android工作室模拟器中运行代码,但在运行之后,模拟器一直显示"(应用程序名称)已停止。再次打开应用程序"。
这是一个从Android服装中获取加速度计和陀螺仪传感器数据的应用程序。
我已经检查了logcat,并在此过程中发现了这个错误。
03-06 04:18:57.364 3189-3189/com.drejkim.androidwearmotionsensors E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.drejkim.androidwearmotionsensors, PID: 3189
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.hardware.Sensor.getStringType()' on a null object reference
at com.drejkim.androidwearmotionsensors.SensorFragment.onCreateView(SensorFragment.java:63)
at android.app.Fragment.performCreateView(Fragment.java:2353)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:563)
at android.support.wearable.view.FragmentGridPagerAdapter.finishUpdate(FragmentGridPagerAdapter.java:196)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1161)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1008)
at android.support.wearable.view.GridViewPager.onMeasure(GridViewPager.java:1322)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.wearable.view.WatchViewStub.onMeasure(WatchViewStub.java:136)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:690)
at android.view.View.measure(View.java:19857)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1675)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6338)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
at android.view.Choreographer.doCallbacks(Choreographer.java:686)
at android.view.Choreographer.doFrame(Choreographer.java:621)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
这里有三个我的java代码:
SensorFragments.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SensorFragment extends Fragment implements SensorEventListener {
private static final float SHAKE_THRESHOLD = 1.1f;
private static final int SHAKE_WAIT_TIME_MS = 250;
private static final float ROTATION_THRESHOLD = 2.0f;
private static final int ROTATION_WAIT_TIME_MS = 100;
private View mView;
private TextView mTextTitle;
private TextView mTextValues;
private SensorManager mSensorManager;
private Sensor mSensor;
private int mSensorType;
private long mShakeTime = 0;
private long mRotationTime = 0;
public static SensorFragment newInstance(int sensorType) {
SensorFragment f = new SensorFragment();
// Supply sensorType as an argument
Bundle args = new Bundle();
args.putInt("sensorType", sensorType);
f.setArguments(args);
return f;
}
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if(args != null) {
mSensorType = args.getInt("sensorType");
}
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(mSensorType);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.sensor, container, false);
mTextTitle = (TextView) mView.findViewById(R.id.text_title);
mTextTitle.setText(mSensor.getStringType());
mTextValues = (TextView) mView.findViewById(R.id.text_values);
return mView;
}
@Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
// If sensor is unreliable, then just return
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
{
return;
}
mTextValues.setText(
"x = " + Float.toString(event.values[0]) + "\n" +
"y = " + Float.toString(event.values[1]) + "\n" +
"z = " + Float.toString(event.values[2]) + "\n"
);
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
detectShake(event);
}
else if(event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
detectRotation(event);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// References:
// - http://jasonmcreynolds.com/?p=388
// - http://code.tutsplus.com/tutorials/using-the-accelerometer-on-android--mobile-22125
private void detectShake(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mShakeTime) > SHAKE_WAIT_TIME_MS) {
mShakeTime = now;
float gX = event.values[0] / SensorManager.GRAVITY_EARTH;
float gY = event.values[1] / SensorManager.GRAVITY_EARTH;
float gZ = event.values[2] / SensorManager.GRAVITY_EARTH;
// gForce will be close to 1 when there is no movement
float gForce = FloatMath.sqrt(gX*gX + gY*gY + gZ*gZ);
// Change background color if gForce exceeds threshold;
// otherwise, reset the color
if(gForce > SHAKE_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
private void detectRotation(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mRotationTime) > ROTATION_WAIT_TIME_MS) {
mRotationTime = now;
// Change background color if rate of rotation around any
// axis and in any direction exceeds threshold;
// otherwise, reset the color
if(Math.abs(event.values[0]) > ROTATION_THRESHOLD ||
Math.abs(event.values[1]) > ROTATION_THRESHOLD ||
Math.abs(event.values[2]) > ROTATION_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
}
MainActivity.Java:
package com.drejkim.androidwearmotionsensors;
import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.DotsPageIndicator;
import android.support.wearable.view.GridViewPager;
import android.support.wearable.view.WatchViewStub;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override public void onLayoutInflated(WatchViewStub stub) {
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new SensorFragmentPagerAdapter(getFragmentManager()));
DotsPageIndicator indicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
indicator.setPager(pager);
}
});
}
}
SensorFragmentPagerAdapter.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.app.FragmentManager;
import android.hardware.Sensor;
import android.support.wearable.view.FragmentGridPagerAdapter;
public class SensorFragmentPagerAdapter extends FragmentGridPagerAdapter {
private int[] sensorTypes = {
Sensor.TYPE_ACCELEROMETER,
Sensor.TYPE_GYROSCOPE
};
public SensorFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getFragment(int row, int column) {
return SensorFragment.newInstance(sensorTypes[column]);
}
@Override
public int getRowCount() {
return 1; // fix to 1 row
}
@Override
public int getColumnCount(int row) {
return sensorTypes.length;
}
}
的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.drejkim.androidwearmotionsensors" >
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.DeviceDefault" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
有人可以帮帮我吗?我从某些来源获得了此代码,而且我不知道如何修复它,因为logcat显示了一个用红色突出显示的长致命异常脚本。谢谢,如果有人可以提供帮助,我会非常感激。
答案 0 :(得分:0)
从LogCat中的错误消息中,您可以在尝试执行时读取mSensor
为空
mTextTitle.setText(mSensor.getStringType());
这意味着您的传感器管理器无法找到与所请求类型相匹配的默认传感器
mSensor = mSensorManager.getDefaultSensor(mSensorType);
如documentation中所述。