Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How to Set Text in TextView from A Public Static Method?

I have this in onCreate :

final TextView text1 = (TextView) findViewById(R.id.txtNextAlarm);

And I'm trying to set a text in a method that is in the same class :

public static void NextTxt(){
        text1.setText("");
}

But it doesn't recognize the "text1".

like image 598
user1880779 Avatar asked Dec 27 '22 08:12

user1880779


2 Answers

The problem is that static methods aren't associated with any particular object, but with the class as a whole. As such, they can only see static fields in your class. Your text1 variable isn't even that, if what you say is true. Instead, it's a local variable that only exists for the length of the onCreate() method. If you know you'll only ever have one instance of your activity (and that's probably not an unreasonable assumption), what you could do is use

private static TextView text1;

at the top of your class (or, basically, anywhere outside of a method). The final modifier doesn't buy you anything. Your choice of whether to make it public or private, but I tend toward private by default (unless there's a reason for something else).

The alternative is to ask yourself why NextTxt() is static; if you make it a normal instance method, then you'd still need to declare text1 in the class, but it wouldn't need to be static. But then you'd need an instance to call it on.

like image 131
Adam Lopresto Avatar answered Dec 28 '22 22:12

Adam Lopresto


TextView text1;

@Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      text1 = (TextView) findViewById(R.id.txtNextAlarm);
}

Do the initialization in the onCreate method.

like image 33
Ahmad Avatar answered Dec 28 '22 23:12

Ahmad