Android:相同的代码行在不同的方法中不起作用

Android: Identical lines of code not working in seperate methods

如果我碰巧在与调用变量的构造相同的方法中使用几行代码,它就可以工作,但如果我创建另一个方法来执行相同的操作, copy-pasted然后直接调用里面的其他方法,不行

    private void initElements(){

    TextView ageValue[] =
            {
                    (TextView)this.findViewById(R.id.age1Value),
                    (TextView)this.findViewById(R.id.age2Value),
                    (TextView)this.findViewById(R.id.age3Value)
            };

    TextView ageText[] =
            {
                    (TextView)this.findViewById(R.id.age1Text),
                    (TextView)this.findViewById(R.id.age2Text),
                    (TextView)this.findViewById(R.id.age3Text)
            };

            for(int i = 0; i<=2;i++){


        intValues[i] = a.getHours((i));
        stringValues[i] = String.valueOf(intValues[i]);
        ageValue[i].setText(stringValues[i]);

    }

    //updateValues();

}

private void updateValues(){


                for(int i = 0; i<=2;i++){


        intValues[i] = a.getHours((i));
        stringValues[i] = String.valueOf(intValues[i]);
        ageValue[i].setText(stringValues[i]);

    }



    }

如果我取消对 updateValues() 函数的注释,程序将不会 运行,即使之前在该函数中执行了相同的代码。此外,调试将在这条语句之后进行:

        ageValue[i].setText(stringValues[i]);

到这个error

我试过重建和清理程序并重新安装。我在虚拟设备和我的真实智能手机上试过了。同样的错误一遍又一遍。 (此外,当我将鼠标悬停在图片中的错误上时,它有时会说"Source code does not match the bytecode",但有时它也不会。”也到处都尝试了"this."关键字,但没有成功。

我只是对这怎么会发生感到困惑。也许该方法没有获得某种正确的内存引用,因为它不直接在声明旁边,但我的意思是 "error statement" 之前的两个语句工作得很好,尽管它们具有相同的性质。如果你能告诉我为什么这不起作用,那就太好了,谢谢!

    TextView ageValue[] = new TextView[3];
TextView ageText[] = new TextView[3];

int intValues[] = new int[3];
String stringValues[] = new String[3];

CalculateDates a = new CalculateDates();

这是使用变量的声明。 (那是在class的开头)

您需要为此使用全局 ageValue[] 和 ageText[] class。

private void initElements(){

    ageValue[0] =(TextView)this.findViewById(R.id.age1Value);
    ageValue[1] =(TextView)this.findViewById(R.id.age2Value);
    ageValue[2] =(TextView)this.findViewById(R.id.age3Value);


   ageText[0] = (TextView)this.findViewById(R.id.age1Text);
   ageText[1] = (TextView)this.findViewById(R.id.age2Text);
   ageText[2] = (TextView)this.findViewById(R.id.age3Text);



        for(int i = 0; i<=2;i++){


    intValues[i] = a.getHours((i));
    stringValues[i] = String.valueOf(intValues[i]);
    ageValue[i].setText(stringValues[i]);

}

也不要在方法内声明 TextView。

您在 initElements() 方法中创建了这些 textView 的不同实例,而全局 TextView 仍然为 null