简体   繁体   English

Java Array 列表在按钮内时不会更新

[英]Java Array list won't update when within button

I'm new to Java (and stackoverflow...), so this might be obvious but couldn't find similar when I searched for it (if I missed it please don't hesitate to just link me the solution!)我是 Java 新手(和 stackoverflow ......),所以这可能很明显,但在我搜索时找不到类似的(如果我错过了,请不要犹豫,将解决方案链接给我!)

I'm struggling with trying to make my Array list update within a button.我正在努力尝试在按钮内更新我的数组列表。 It keeps saying 'Cannot resolve symbol fileEntry' when I use it in onSensorChanged (I used to have it defined outside the button but it wouldn't update it when I clicked the starting button), and it also says 'Variable fileEntry is never used' within the button.当我在 onSensorChanged 中使用它时,它一直说“无法解析符号 fileEntry”(我曾经在按钮外定义它,但当我单击开始按钮时它不会更新它),并且它还说“从未使用过变量 fileEntry” ' 按钮内。 See code below :见下面的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    starting_button = (Button) findViewById(R.id.button_start);
    starting_button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            ArrayList fileEntry = new ArrayList();

And this is where I am trying to use it:这就是我尝试使用它的地方:

@Override
public void onSensorChanged(SensorEvent sensorEvent) {

    fileEntry.add(sensorEvent.values[0] + "," + sensorEvent.values[1] + "," + sensorEvent.values[2] + "\r");
}

What I would like it to do is to have a new fileEntry (ie clear it) every time I click on the starting button.我希望它做的是每次单击开始按钮时都有一个新的 fileEntry(即清除它)。

I know my code is far from being perfect, sorry in advance!我知道我的代码远非完美,提前抱歉!

You should declare your ArrayList as a property in your activity class like this in order to use it in your different methods :您应该像这样在活动类中将 ArrayList 声明为属性,以便在不同的方法中使用它:

class MainActivity extends AppCompatActivity() {
    private ArrayList fileEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fileEntry = new ArrayList();

        starting_button = (Button) findViewById(R.id.button_start);
        starting_button.setOnClickListener(new View.OnClickListener() {
    }

    @Override
    public void onClick(View v) {
        // Do something with your fileEntry
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        fileEntry.add(sensorEvent.values[0] + "," + sensorEvent.values[1] + "," + sensorEvent.values[2] + "\r");
    }    
}

The scope of your property will now be limited to your class, and not simply your onClick method.您的属性的范围现在将仅限于您的类,而不仅仅是您的 onClick 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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