简体   繁体   中英

NullPointerException on setText() in a fragment

When I run the following code it crash and throws an NPE error.

I try to access an object, in this case a textview in a fragment activity. How should I go about it ?

Below is the code I have pasted from the fragment activity.

Another issue is how to use the findViewById in the fragment activity.

public class Report extends Fragment implements SensorEventListener {

    private static final double NOISE = 2.0 ;
    //define

    private SensorManager sensorManager;
    private Sensor accelerometer;
    private boolean mInitialized;
    private static final String TAG = "Report";
    private TextView Counter;
    double X,Y,Z;
    double lastX, lastY, lastZ;
    double deltaX, deltaY, deltaZ;
    int stepsCount;
    private int threshold; // point at which we want to trigger a step.


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.report, container, false);

       Counter = getActivity().findViewById(R.id.counter);


       threshold = 10;

        //initialize the variables
        mInitialized = false;

        //get the sensor manager

        sensorManager = (SensorManager)getActivity().getSystemService(getActivity().SENSOR_SERVICE);

        //get accelerometer sensor.
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        startSensor();

        return view;
    }

    private void startSensor() {
        //register a listener
        sensorManager.registerListener(Report.this, accelerometer ,SensorManager.SENSOR_DELAY_NORMAL);

    }


    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        // Log.d (TAG, "onSensorChanged: X:" + sensorEvent.values[0] + "Y:" + sensorEvent.values[1] + "Z:" + sensorEvent.values[2]);

        // alpha is calculated as t / (t + dT)
        // with t, the low-pass filter's time-constant
        // and dT, the event delivery rate

        final double alpha = 0.8; // constant for our filter below

        double[] gravity = {0, 0, 0};

        // Isolate the force of gravity with the low-pass filter.
        gravity[0] = alpha * gravity[0] + (1 - alpha) * sensorEvent.values[0];
        gravity[1] = alpha * gravity[1] + (1 - alpha) * sensorEvent.values[1];
        gravity[2] = alpha * gravity[2] + (1 - alpha) * sensorEvent.values[2];

        // Log.d(TAG,"GRAVITY: X:" +  gravity[0] + "Y:" +  gravity[1] + "Z:" + gravity[2] );

        // Remove the gravity contribution with the high-pass filter.
        X = sensorEvent.values[0] - gravity[0];
        Y = sensorEvent.values[1] - gravity[1];
        Z = sensorEvent.values[2] - gravity[2];

        //Log.d(TAG,"X:" + X + "Y:" + Y + "Z:" + Z);

        lastX = 0;
        lastY = 0;
        lastZ = 0;

        if (!mInitialized) {
            //sensor is used for the first time, initialize the last read values
          lastX = X;
          lastY = Y;
          lastZ = Z;
          mInitialized = true;
        } else {
          // sensor is already initialized, and we have previously read values.
          // take difference of past and current values and decide which
          // axis acceleration was detected by comparing values

          deltaX = Math.abs(lastX - X);
          deltaY = Math.abs(lastY - Y);
          deltaZ = Math.abs(lastZ - Z);

          // Log.d(TAG,"X:"+ deltaX + "Y:" + deltaY + "Z:" + deltaZ);

          if (deltaX < NOISE)
            deltaX = (float) 0.0;
          if (deltaY < NOISE)
            deltaY = (float) 0.0;
          if (deltaZ < NOISE)
            deltaZ = (float) 0.0;
          lastX = X;
          lastY = Y;
          lastZ = Z;

          if (deltaX > deltaY) {
            // Horizontal shake
            // do something here if you like

          } else if (deltaY > deltaX) {
            // Vertical shake
            // do something here if you like

          } else if (deltaZ>threshold){


            stepsCount++;
            Log.d(TAG,"STEPS:" + stepsCount);


          }

          Counter.setText(String.valueOf(stepsCount));//this is the line that throws the error
       }

    }

    @Override
    public void onResume(){
        super.onResume();
        stepsCount=0;
        // put your code here...
    }

    @Override
    public void onPause(){
        super.onPause();
        sensorManager.unregisterListener(this);
        // put your code here...

    }

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

    }
}

This line in onCreateView() :

Counter = getActivity().findViewById(R.id.counter);

needs to be:

Counter = view.findViewById(R.id.counter);

As you're obtaining your TextView from the layout you inflated the line before, not the Activity. As a side note, you shouldn't be naming variables with a capital letter at the front. Only classes should begin with capital letters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM