2017-04-19 2 views
0

J'ai un problème d'affichage et d'interaction avec les capteurs d'un fragment. J'ai déjà quelques fragments de travail, mais quand je charge le fragment de capteur, la force se ferme.Problèmes de lecture du capteur à partir d'un fragment dans android

sensors.java est le fragment et ressemble à ce

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)); 
    } 
} 




} 

Mon sensor.xml ressemble à ceci

<?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> 

mon logcat lit la question

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()' renvoie null jusqu'à ce que se termine 'onCreateView ('). Si vous voulez initialiser votre 'View's dans' onCreateView() ', vous devez appeler' findViewById() 'sur' View' que vous avez gonflé. Vous pouvez ajouter un paramètre 'View' à votre méthode' initializeViews() 'et lui passer votre' rootView'. –

+1

Merci mon frère. Chose amusante, c'est que j'ai lu ce fil de pensée qui devait être essayé un million de choses et l'a cassé encore plus et s'est retrouvé perdu dans la sauce. Si quelqu'un d'autre a ce problème, j'ai tout simplement déplacé tout à l'inflateur et retourner rootView dans un OnViewCreated. Merci encore @MikeM. – Adam

Répondre

0

Vous appelez getView() avant que la vue racine soit s et, avant de revenir de la méthode onCreateView().

Essayez ceci:

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

Merci @Titus. J'ai déplacé tout sauf le gonfleur et je suis revenu de OnCreateView vers un OnViewCreated. – Adam