2013-08-07 47 views
1

我有這個問題要問你:爲什麼數組每次重新初始化?

我寫了這個代碼:

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


} 

所以我不理解,因爲每個改變XYZ的值時,該數組初始化本身...

我有必要更多cicle存儲陣列中的價值

非常感謝

回答

1

,因爲你是initiali查懋他們裏面onSensorChanged()

所以當設備移動一點,onSensorChanged()被調用,所有

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

這些也被初始化onSensorChanged()其他的東西reinitialized

so Declare these inside class 

,並在那裏使用任何內部的類

+0

是的,但不是陣列 – MbbM

+0

哪個數組?或者你在談論'ArrayList oldvalue'? –

+0

是Tarsem我說Oldvalue – MbbM

相關問題