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".
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.
TextView text1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
text1 = (TextView) findViewById(R.id.txtNextAlarm);
}
Do the initialization in the onCreate method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With