从android中的片段读取传感器的问题

时间:2017-04-19 07:02:39

标签: java android android-fragments fragment sensor

我在显示片段中的传感器并与之交互时遇到问题。我已经有了几个工作片段,但是当我加载传感器片段时,它会强制关闭。

sensors.java 是片段,看起来像这样

public class sensors extends Fragment implements SensorEventListener
{
private float lastX, lastY, lastZ;
private SensorManager sensorManager;
private Sensor accelerometer;

private float deltaXMax = 0;
private float deltaYMax = 0;
private float deltaZMax = 0;

private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;

private float vibrateThreshold = 0;

private TextView currentX, currentY, currentZ, maxX, maxY, maxZ;

public Vibrator v;

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, @Nullable Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    View rootView = inflater.inflate(R.layout.sensor, container, false);
    initializeViews();

    sensorManager = (SensorManager) 
getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
        // success! we have an accelerometer

        accelerometer = 
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, accelerometer, 
SensorManager.SENSOR_DELAY_NORMAL);
        vibrateThreshold = accelerometer.getMaximumRange() / 2;
    } else {
        // fai! we dont have an accelerometer!
    }

    //initialize vibration
    v = (Vibrator) 
this.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    return rootView;
}

public void initializeViews() {
    currentX = (TextView) getView().findViewById(R.id.currentX);
    currentY = (TextView) getView().findViewById(R.id.currentY);
    currentZ = (TextView) getView().findViewById(R.id.currentZ);

    maxX = (TextView) getView().findViewById(R.id.maxX);
    maxY = (TextView) getView().findViewById(R.id.maxY);
    maxZ = (TextView) getView().findViewById(R.id.maxZ);
}

//onResume() register the accelerometer for listening the events
public void onResume() {
    super.onResume();
    sensorManager.registerListener(this, accelerometer, 
SensorManager.SENSOR_DELAY_NORMAL);
}

//onPause() unregister the accelerometer for stop listening the events
public void onPause() {
    super.onPause();
    sensorManager.unregisterListener(this);
}

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

}

@Override
public void onSensorChanged(SensorEvent event) {

    // clean current values
    displayCleanValues();
    // display the current x,y,z accelerometer values
    displayCurrentValues();
    // display the max x,y,z accelerometer values
    displayMaxValues();

    // get the change of the x,y,z values of the accelerometer
    deltaX = Math.abs(lastX - event.values[0]);
    deltaY = Math.abs(lastY - event.values[1]);
    deltaZ = Math.abs(lastZ - event.values[2]);

    // if the change is below 2, it is just plain noise
    if (deltaX < 2)
        deltaX = 0;
    if (deltaY < 2)
        deltaY = 0;
    if (deltaZ < 2)
        deltaZ = 0;

    // set the last know values of x,y,z
    lastX = event.values[0];
    lastY = event.values[1];
    lastZ = event.values[2];

    vibrate();

}

// if the change in the accelerometer value is big enough, then vibrate!
// our threshold is MaxValue/2
public void vibrate() {
    if ((deltaX > vibrateThreshold) || (deltaY > vibrateThreshold) || 
(deltaZ > vibrateThreshold)) {
        v.vibrate(50);
    }
}

public void displayCleanValues() {
    currentX.setText("0.0");
    currentY.setText("0.0");
    currentZ.setText("0.0");
}

// display the current x,y,z accelerometer values
public void displayCurrentValues() {
    currentX.setText(Float.toString(deltaX));
    currentY.setText(Float.toString(deltaY));
    currentZ.setText(Float.toString(deltaZ));
}

// display the max x,y,z accelerometer values
public void displayMaxValues() {
    if (deltaX > deltaXMax) {
        deltaXMax = deltaX;
        maxX.setText(Float.toString(deltaXMax));
    }
    if (deltaY > deltaYMax) {
        deltaYMax = deltaY;
        maxY.setText(Float.toString(deltaYMax));
    }
    if (deltaZ > deltaZMax) {
        deltaZMax = deltaZ;
        maxZ.setText(Float.toString(deltaZMax));
    }
}




}

我的sensor.xml看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_gravity="center"
          android:background="#ffffff"
          android:gravity="center"
          android:orientation="vertical"
          android:paddingTop="20dp" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="10dp"
    android:text="Max Acceleration:"
    android:textSize="20dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:text="Max Acceleration: X-Axis"
    android:textSize="15dp" />

<TextView
    android:id="@+id/maxX"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="10dp"
    android:text="0.0"
    android:textSize="20dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:text="Max Acceleration: Y-Axis"
    android:textSize="15dp" />

<TextView
    android:id="@+id/maxY"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="10dp"
    android:text="0.0"
    android:textSize="20dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:text="Max Acceleration: Z-Axis"
    android:textSize="15dp" />

<TextView
    android:id="@+id/maxZ"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="10dp"
    android:text="0.0"
    android:textSize="20dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="30dp"
    android:text="Current Acceleration:"
    android:textSize="20dp" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:gravity="center|top"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.33"
        android:background="#ffffff"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="X-Axis"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/currentX"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="0.0"
            android:textSize="15dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.33"
        android:background="#ffffff"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="Y-Axis"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/currentY"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="0.0"
            android:textSize="15dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.33"
        android:background="#ffffff"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="Z-Axis"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/currentZ"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="0.0"
            android:textSize="15dp" />
    </LinearLayout>
</LinearLayout>

</RelativeLayout>

我的logcat读取问题

    04-19 01:59:56.723 6460-6460/abrunette.blackhawk.edu.pagenavi W/art: Before 
    Android 4.1, method int 
    android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, 
    boolean) would have incorrectly overridden the package-private method in 
    android.widget.ListView
    04-19 01:59:59.052 6460-6460/abrunette.blackhawk.edu.pagenavi 
    D/AndroidRuntime: Shutting down VM
    04-19 01:59:59.054 6460-6460/abrunette.blackhawk.edu.pagenavi 
    E/AndroidRuntime: FATAL EXCEPTION: main

    Process: abrunette.blackhawk.edu.pagenavi, PID: 6460

    Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, 
    com.android.systemui=overlay:system, 
    com.android.systemui.navbar=overlay:system}

    java.lang.NullPointerException: Attempt to invoke virtual method 
    'android.view.View android.view.View.findViewById(int)' on a null object 
    reference

    at abrunette.blackhawk.edu.pagenavi.sensors.initializeViews(sensors.java:61)

    at abrunette.blackhawk.edu.pagenavi.sensors.onCreateView(sensors.java:42)

    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)

    at 
  android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
                                                                                    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
                                                                                    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
                                                                                    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
                                                                                    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
                                                                                    at android.os.Handler.handleCallback(Handler.java:739)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                    at android.os.Looper.loop(Looper.java:148)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5461)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

您在设置根视图之前调用getView(),然后再从onCreateView()方法返回。

试试这个:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View rootView = inflater.inflate(R.layout.sensor, container, false);
    initializeViews(rootView);
    ....
}
public void initializeViews(rootView) {
    currentX = (TextView) rootView.findViewById(R.id.currentX);
    currentY = (TextView) rootView.findViewById(R.id.currentY);
    currentZ = (TextView) rootView.findViewById(R.id.currentZ);

    maxX = (TextView) rootView.findViewById(R.id.maxX);
    maxY = (TextView) rootView.findViewById(R.id.maxY);
    maxZ = (TextView) rootView.findViewById(R.id.maxZ);
}