为什么阵列每次重新初始化?

时间:2013-08-07 19:04:40

标签: java android

我有这个问题:

我写了这段代码:

public class MainActivity extends Activity implements SensorEventListener {
    private SensorManager mSensorManager;
    private Sensor mSensor;
    ArrayList<String> oldvalue  = new ArrayList<String>();
    int count;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener((SensorEventListener) this, mSensor,         SensorManager.SENSOR_DELAY_NORMAL);
        count = 0;
        //oldvalue = null;

    }

    @Override
    protected void onPause() {
        super.onPause();
        //mSensorManager.unregisterListener(this);
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public void onSensorChanged(SensorEvent event) {
        String x,y,z;
        Float xnum,ynum,znum;
        TextView xtextview,ytextview,ztextview = new TextView(this);

        if (oldvalue == null || oldvalue.size()<1) {
        String statoarray = "null or 0";
        Toast.makeText(this, statoarray, Toast.LENGTH_SHORT)
          .show();
        }
        else {
            String statoarray = String.valueOf(oldvalue.size());
            Toast.makeText(this, statoarray, Toast.LENGTH_SHORT)
              .show();
        }


        if (oldvalue.size()<2) 
        {
            xtextview=(TextView)findViewById(R.id.x); 
            ytextview=(TextView)findViewById(R.id.y);
            ztextview=(TextView)findViewById(R.id.z);

            xnum = event.values[0];
            ynum = event.values[1];
            znum = event.values[2];

            oldvalue.add(String.valueOf(xnum));
        oldvalue.add(String.valueOf(ynum));
        oldvalue.add(String.valueOf(znum));


        x = Float.toString(Math.round(xnum));
        y = Float.toString(Math.round(ynum));;
        z = Float.toString(Math.round(znum));;

        xtextview.setText(x);
        ytextview.setText(y);
        ztextview.setText(z);   
        }

        //Toast.makeText(this, "pieno", Toast.LENGTH_SHORT)
        //.show();
    }


}

所以我不明白,因为每次更改x y z的值时,数组都会重新初始化...

我有必要在数组中存储更多的cicle值

非常感谢

1 个答案:

答案 0 :(得分:1)

因为您正在onSensorChanged()

中初始化它们

所以当设备移动很少时,会调用onSensorChanged()并且所有

 String x,y,z;
        Float xnum,ynum,znum;
        TextView xtextview,ytextview,ztextview = new TextView(this);

这些以及初始化onSensorChanged()的其他内容都是reinitialized

so Declare these inside class

并使用该类中的任何位置