2017-04-19 85 views
0

我遇到了顯示片段中的傳感器並與其進行交互的問題。我已經有幾個工作片段,但是當我加載傳感器片段時,它強制關閉。從Android中的片段讀取傳感器的問題

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

'getView()'將返回null直到'onCreateView()'完成。如果你想在'onCreateView()'中初​​始化你的View,你需要在你已經在那裏膨脹的'View'調用'findViewById()'。你可以爲你的'initializeViews()'方法添加一個'View'參數,並將'rootView'傳遞給它。 –

+1

感謝兄弟。有趣的是,我讀過那篇文章,認爲它必須嘗試一百萬件事情,並且更多地破壞它,最終失去了醬油。如果其他人有這個問題,我只是將所有東西都移動到inflater,並將rootView返回到OnViewCreated。再次感謝@MikeM。 – Adam

回答

0

你在根視圖爲s之前調用getView() et,在從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); 
} 
+0

謝謝@Titus。我移動了一切,但inflater並從OnCreateView返回到OnViewCreated。 – Adam