代码适用于活动,但不适用于片段

时间:2014-12-13 14:50:50

标签: java android android-activity fragment

所以下面的代码适用于一个活动但是只要我用onCreateView将它添加到一个片段,应用程序崩溃

任何人都可以帮我修改片段或者向我解释出错的地方吗?

感谢

 public class Exercises extends Activity {

    // Display fields for Accelerometer
    private TextView textViewX;
    private TextView textViewY;
    private TextView textViewZ;

    // Display Fields for Sensitivity
    private TextView textSensitive;

    // Display for Steps
    private TextView textViewSteps;

    // Reset Button
    private Button buttonReset;

    // Sensor Manager
    private SensorManager sensorManager;
    private float acceleration;

    // Values to Calculate Number of Steps
    private float previousY;
    private float currentY;
    private int numSteps;

    // Seekbar Fields
    private SeekBar seekBar;
    private int threshold; // Point at which we want to trigger a 'step'


    @Override
    public void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);
       setContentView(R.layout.steps_layout);
        try {
            SetUpPedometer();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void SetUpPedometer(){

        // Attach objects to XML View
        textViewX=(TextView)findViewById(R.id.textViewX);
        textViewY=(TextView)findViewById(R.id.textViewY);
        textViewZ=(TextView)findViewById(R.id.textViewZ);

        //Attach Step and Sensitive View Objects to XML
        textViewSteps=(TextView)findViewById(R.id.textSteps);
        textSensitive=(TextView)findViewById(R.id.textSensitive);

        //Attach the resetButton to XML
        buttonReset = (Button)findViewById(R.id.buttonReset);

        //Attach the seekBar to XML
        seekBar = (SeekBar)findViewById(R.id.seekBar);

        //Set the Values on the seekBar, threshold, and threshold display
        seekBar.setProgress(10);
        seekBar.setOnSeekBarChangeListener(seekBarListener);
        threshold=10;
        textSensitive.setText(String.valueOf(threshold));

        // Initialize Values
        previousY = 0;
        currentY = 0;
        numSteps =0;

        buttonReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                numSteps = 0;
                textViewSteps.setText(String.valueOf(numSteps));
            }
        });

        // Initialize acceleration Values
        acceleration = 0.00f;

        // Enable the listener - We will write this later in the class
        enableAccelerometerListening();
    }

    private void enableAccelerometerListening(){
        //Initialise the Sensor Manager
        sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        sensorManager.registerListener(sensorEventListener,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }
    private SensorEventListener sensorEventListener=new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {

            // Gather the values from accelerometer
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            // Fetch the current y
            currentY = y;

            // Measure if a step is taken
            if ( Math.abs(currentY-previousY) > threshold) {
                numSteps++;
                textViewSteps.setText(String.valueOf(numSteps));
            } //end if

            // Display the Values
            textViewX.setText(String.valueOf(x));
            textViewY.setText(String.valueOf(y));
            textViewZ.setText(String.valueOf(z));

            // Store the previous Y
            previousY =y;
        }

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

    public void buttonReset() {
        numSteps = 0;
        textViewSteps.setText(String.valueOf(numSteps));
    }

    private SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            threshold = seekBar.getProgress();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };
}

片段     公共类步骤扩展片段{

// Display fields for Accelerometer
private TextView textViewX;
private TextView textViewY;
private TextView textViewZ;

// Display Fields for Sensitivity
private TextView textSensitive;

// Display for Steps
private TextView textViewSteps;

// Reset Button
private Button buttonReset;

// Sensor Manager
private SensorManager sensorManager;
private float acceleration;

// Values to Calculate Number of Steps
private float previousY;
private float currentY;
private int numSteps;

// Seekbar Fields
private SeekBar seekBar;
private int threshold; // Point at which we want to trigger a 'step'


@Override
public void onCreate(Bundle saveInstanceState){
    super.onCreate(saveInstanceState);        

}


public void SetUpPedometer(View S){

    // Attach objects to XML View
    textViewX=(TextView)S.findViewById(R.id.textViewX);
    textViewY=(TextView)S.findViewById(R.id.textViewY);
    textViewZ=(TextView)S.findViewById(R.id.textViewZ);

    //Attach Step and Sensitive View Objects to XML
    textViewSteps=(TextView)S.findViewById(R.id.textSteps);
    textSensitive=(TextView)S.findViewById(R.id.textSensitive);

    //Attach the resetButton to XML
    buttonReset = (Button)S.findViewById(R.id.buttonReset);

    //Attach the seekBar to XML
    seekBar = (SeekBar)S.findViewById(R.id.seekBar);

    //Set the Values on the seekBar, threshold, and threshold display
    seekBar.setProgress(10);
    seekBar.setOnSeekBarChangeListener(seekBarListener);
    threshold=10;
    textSensitive.setText(String.valueOf(threshold));

    // Initialize Values
    previousY = 0;
    currentY = 0;
    numSteps =0;

    buttonReset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            numSteps = 0;
            textViewSteps.setText(String.valueOf(numSteps));
        }
    });

    // Initialize acceleration Values
    acceleration = 0.00f;

    // Enable the listener - We will write this later in the class
    enableAccelerometerListening();
}

private void enableAccelerometerListening(){
    //Initialise the Sensor Manager
    sensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
    sensorManager.registerListener(sensorEventListener,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);
}
private SensorEventListener sensorEventListener=new SensorEventListener() {
    @Override
    public void onSensorChanged(SensorEvent event) {

        // Gather the values from accelerometer
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        // Fetch the current y
        currentY = y;

        // Measure if a step is taken
        if ( Math.abs(currentY-previousY) > threshold) {
            numSteps++;
            textViewSteps.setText(String.valueOf(numSteps));
        } //end if

        // Display the Values
        textViewX.setText(String.valueOf(x));
        textViewY.setText(String.valueOf(y));
        textViewZ.setText(String.valueOf(z));

        // Store the previous Y
        previousY =y;
    }

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

public void buttonReset() {
    numSteps = 0;
    textViewSteps.setText(String.valueOf(numSteps));
}

private SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        threshold = seekBar.getProgress();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
     View S = inflater.inflate(R.layout.steps_layout, container, false);
    try {
        SetUpPedometer(S);
    } catch (Exception e) {
        e.printStackTrace();
    }
     return S;
}
}

12-13 15:17:15.062 984-984 / com.stephenh.daytrack.daytrackstephenh E / AndroidRuntime:FATAL EXCEPTION:main     处理:com.stephenh.daytrack.daytrackstephenh,PID:984     显示java.lang.NullPointerException             at com.stephenh.daytrack.daytrackstephenh.SwipeViewsAdapter.Steps.SetUpPedometer(Steps.java:101)             at com.stephenh.daytrack.daytrackstephenh.SwipeViewsAdapter.Steps.onCreateView(Steps.java:188)             在android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)             在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)             在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)             在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)             在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)             在android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)             在android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)             在android.support.v4.view.ViewPager.populate(ViewPager.java:1073)             在android.support.v4.view.ViewPager.populate(ViewPager.java:919)             在android.support.v4.view.ViewPager $ 3.run(ViewPager.java:249)             在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:761)             在android.view.Choreographer.doCallbacks(Choreographer.java:574)             在android.view.Choreographer.doFrame(Choreographer.java:543)             在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:747)             在android.os.Handler.handleCallback(Handler.java:743)             在android.os.Handler.dispatchMessage(Handler.java:99)             在android.os.Looper.loop(Looper.java:136)             在android.app.ActivityThread.main(ActivityThread.java:5212)             at java.lang.reflect.Method.invokeNative(Native Method)             在java.lang.reflect.Method.invoke(Method.java:515)             在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)             在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)             在dalvik.system.NativeStart.main(本地方法)

1 个答案:

答案 0 :(得分:2)

在活动生命周期活动中使用onCreate而片段使用

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View rootView = inflater.inflate(R.layout.steps_layout,
            container, false);
    SetUpPedometer(rootView);
    return rootView;
}


public void SetUpPedometer(View view){

    // Attach objects to XML View
    textViewX=(TextView)view.findViewById(R.id.textViewX);
    textViewY=(TextView)view.findViewById(R.id.textViewY);
    textViewZ=(TextView)view.findViewById(R.id.textViewZ);

    //Attach Step and Sensitive View Objects to XML
    textViewSteps=(TextView)view.findViewById(R.id.textSteps);
    textSensitive=(TextView)view.findViewById(R.id.textSensitive);

    //Attach the resetButton to XML
    buttonReset = (Button)view.findViewById(R.id.buttonReset);

    //Attach the seekBar to XML
    seekBar = (SeekBar)view.findViewById(R.id.seekBar);

    //Set the Values on the seekBar, threshold, and threshold display
    seekBar.setProgress(10);
    seekBar.setOnSeekBarChangeListener(seekBarListener);
    threshold=10;
    textSensitive.setText(String.valueOf(threshold));

    // Initialize Values
    previousY = 0;
    currentY = 0;
    numSteps =0;

    buttonReset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            numSteps = 0;
            textViewSteps.setText(String.valueOf(numSteps));
        }
    });

    // Initialize acceleration Values
    acceleration = 0.00f;

    // Enable the listener - We will write this later in the class
    enableAccelerometerListening();
}

并尝试记录这些值,以确保它们在将它们设置为textview之前不会为null

// Gather the values from accelerometer
    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];