java - Android:相同的代码行无法在单独的方法中工作

标签 java android exception reference

如果我碰巧在同一个方法中使用几行代码作为被调用变量的构造,它就可以工作,但是如果我创建另一个方法来执行相同的操作,复制粘贴,然后只调用其中的另一个方法,它就行不通。

    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

我尝试过重建和清理程序并重新安装它。我在虚拟设备和真实的智能手机上尝试过。同样的错误一遍又一遍。 (而且,当我将鼠标悬停在图片中的错误上时,它有时会说“源代码与字节码不匹配”,但有时也不会。”也到处尝试了“this.”关键字,但没有成功。

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

    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[]。

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

关于java - Android:相同的代码行无法在单独的方法中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46144239/

相关文章:

cocoa - "EXC_BREAKPOINT (SIGTRAP)"异常是否是调试断点导致的?

java - Java 中的简单多线程

android - 将连续语音识别添加到我的 Android 应用程序

java - LibGdx font.setColor(Color.WHITE) 不起作用

android - 粒子效果在android上显示严重波纹

java - 如何在 NativeScript 插件中链接本地 JAR 依赖项

java - 为什么我不能在 Java 8 lambda 表达式中抛出异常?

java - 存储数据时 Elasticsearch 异常

Java 正则表达式与括号匹配

Java ProcessBuilder 如何获取实时输出