当前位置: 首页 > 知识库问答 >
问题:

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

笪欣嘉
2023-03-14

因此,下面的代码适用于一个活动,但当我使用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) {

        }
    };
}

Fragment公共类步骤扩展Fragment{

// 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.daytrack.daytrackstephenh E/AndroidRuntime:致命异常:主进程:com.stephenh.daytrack.daytrack.daytrackstephenh.nullpointerexception(位于com.stephenh.daytrack.daytrackstaytrack.swipeviewsadapter.steps.setuppedometer(steps.java:101)(位于com.stephenh.daytrack.daytrack.swipeviewsadapter.steps.onCreateView(oid.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(

共有1个答案

缪修德
2023-03-14

在活动生命周期中,活动使用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];
 类似资料:
  • 我的GMAILIMAP代码在PHP从我的localhost工作得很好,但它不能从域工作。 我已完成以下项目: 1) 允许不太安全的应用登录2)在GMAIL帐户中启用IMAP 3)未启用双因素身份验证。4) 我也验证了帐户访问权限5)我还允许:http://www.google.com/accounts/DisplayUnlockCaptcha 可能是我在实时服务器上没有SSL的问题吗? 但我不断得

  • 我正在编写一个 C# 应用程序来解码此字符串: "--W 3原文3 R hcn Rfd Gl tZ SI 6 I jAi L CJ w cm 9 k dW N 0 X 2 lk I jo iO D Q wM DMz MD气LC J 1 cm wi O iI if Sx 7 InN 0 Y XJ 0 X 3 Rp b WU iO iI 3 OS In by b 2 R 1 Y 3 Rfa WQ iO

  • 问题内容: 嗨,我只是简单地尝试在www.example.com上获取h1标签,该标签显示为“ Example Domain”。该代码适用于http://www.example.com,但不适用于https://www.exmaple.com。我该如何解决这个问题?谢谢 问题答案: PhantomJSDriver不支持(所有)DesiredCapabilities。 你会需要: 记录在这里:htt

  • 所以我使用这种方法写入文件,它在windows上运行完全正常,但在mac上运行时,它会创建文件,但它们是空的。 我知道数据是正确的,因为它打印正确。感谢您的任何帮助,这真的让我绊倒了。

  • 列名称的类型为int[] 上述查询适用于postgresql,但不适用于hsqldb,甚至适用于sql 尝试的hsqldb版本:2.2.9和2.3.0 在hsqldb中工作的sql是从table_name中选择x,unnest(column_name)y(x)x和y不是该表的列。

  • 我试图解决这个问题:https://leetcode.com/problems/palindrome-number/使用代码: 并在C中得到了这个错误: 但同样的代码在Java中运行得很好。为什么会这样?我该如何修复它?