Reputation: 3075
I have a problem with that code
setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");
It works if it's inside an activity, but if it isn't, obviously, it gives errors:
The method findViewById(int) is undefined for the type new TimerTask(){}
The method setContentView(int) is undefined for the type new TimerTask(){}
The code is inside a timer in separate class (not activity). The full code is as follows.
//main timer task for ingame time processing
static Timer gameTimer = new Timer();
static TimerTask gameTimerTask = new TimerTask() {
@Override
public void run() {
setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");
}
};
I tried changing it like that
ScreenGame.this.setContentView(R.layout.game);
TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
text.setText("Hello Android");
But it still doesn't work :(
PS - Yes, I searched other similar questions, but all of them although appear to be the same, in fact completely different.
Upvotes: 2
Views: 4660
Reputation: 11931
ScreenGame.this.setContentView(R.layout.game);
TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
text.setText("Hello Android");
is exactly the same as
setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");
wrong code
You should make a parent class, that fires off all the other Activities. In that parent class, you can have a reference to each child activity, and you can ask each child for it's textfield:
// In the parent:
child.getTextView().setText("Hello galaxy!");
// with the child method:
TextView getTextView () {
return (TextView) findViewById(R.id.qwe_string);
}
EDIT: More info:
The code I gave was not good, I hadn't understood your problem well... I hope I do now, do I'll try to correct myself.
Make a seperate class, for example MyTimer
, which will extends the TimerTask
class:
class MyTimer extends TimerTask {
// your class
}
Make a constructor, that excepts an TextView as an argument, and saves a reference to it.
TextView theTextView;
MyTimer (TextView tv) {
this.theTextView = tv;
}
Now implement run()
:
@Override
public void run() {
setContentView(R.layout.game);
thetextView.setText("Hello Galaxy!");
}
Call make this class using the following code:
static TimerTask gameTimerTask = new MyTimer((TextView) findViewById(R.id.qwe_string));
I hope this is all correct, I have to do this from memory as I don't have any testing environment. At least it should help you in the right direction.
Upvotes: 2
Reputation: 11256
You will need:
ScreenGame.this.runOnUiThread( new Runnable(){
public void run(){
TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
text.setText("Hello Android"); }
});
And you should call the following line in onCreate()
of ScreenGame
:
setContentView(R.layout.game);
Upvotes: 0