Update textview when value in a different class is updated - java

I am trying to update a textview to a value (a timer) within my current xml im viewing, the java for the timer is part of a glrenderer class, everything works fine, except I can't update my textview, I have already extended Activity to the class like this:
class MyGLRenderer extends Activity implements GLSurfaceView.Renderer {
So that I am able to use this inside the timer loop:
TextView view = (TextView) findViewById(R.id.timetextview);
view.setText(String.valueOf(globals.gametime));
It crashes when it tries to create the viewtime object.
There is one way I can get it to partially, the Timer value is a global one so I can show it by creating a button in the main.java like so:
public void buttonExample (View v)
{
TextView view = (TextView) findViewById(R.id.timetextview);
view.setText(String.valueOf(globals.gametime));
}
But with this it wont update with the actual timer, I'm unsure why its crashing when I'm using the top 2 blocks of code, it compiles fine.

I doubt , you are updating the Textview in timer thread .
You can try this in your timer thread -
runOnUiThread(new Runnable() {
public void run() {
view.setText(String.valueOf(globals.gametime));
}
});

Using the code Gaurav provided to access the uithread in my timer worked perfectly, here is what I used
public Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable() {
public void run() {
TextView view = (TextView) findViewById(R.id.timetextview);
view.setText(String.valueOf(globals.GameTime));
}
});
}
}, 250, 250);

Related

Possible reasons of not showing up the view on SurfaceView

I have my custom view that extends SurfaceView and here I have a spinner among others on it. I set its visibility to visible and invisible in turns but after one cycle of showing and hiding, next time it does not show up anymore. To verify what's wrong I draw on canvas text:
spiner3.getVisibility()
spiner3.getX()
spiner3.getY()
but nothing of these seem to be wrong I mean X and Y are on the within the screen and getVisibility returns View.VISIBLE. So what can be the other reason of not showing up if it is not visibility property and coordinations?
I did a workaround. In Activity that uses this view I added such code:
Handler mTimerHandler;
Timer timer = new Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gra_layout);
vg = findViewById(R.id.content_frame);
refreshSpinner();
...
}
private void refreshSpinner() {
mTimerHandler = new Handler();
timer.schedule(new TimerTask() {
public void run() {
mTimerHandler.post(() -> {
vg.invalidate();
});
}
}, 0, 100);
}

Background is not dimming in fragment

I am using a fragment and there is a button as soon as I click on it the background will become dim and textView will be visible.The appearance of the dimming effect and text will take place at once.For some reason I don't get these result.
Here is my code:-
activate_wifi_button = (Button)wifi_and_hotspot.findViewById(R.id.Activate_wifi);
activate_wifi_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
WindowManager.LayoutParams layoutParams=getActivity().getWindow()
.getAttributes();
layoutParams.dimAmount = 0.7f;
getActivity().getWindow().setAttributes(layoutParams);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
text.setVisibility(View.VISIBLE);
text_animate_dots.setVisibility(View.VISIBLE);
timer.cancel();
}
};
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
}, 2000, 2000);
}
});
I have used handler and runnable because I want to animate the textview for 2 sec but the animate part can come latter at first I need to do the above task.
For the desired output, you can take semi-transparent layout and textView in FrameLayout. In onclick method, set its visibility VISIBLE; and for better user experience, set Fade animation to textview.

Java Timer equivalent in Android

I recently began working with Java and am exploring Android development. I was trying to port over one of the Java programs I made, but I am having some difficulty with getting the java Timer to function the same way in Android. I read through a number of posts and they, for the most part, indicated that it would be better to use the Handler class in android as opposed to Timer.
This was my timer in Java:
playTimer = new Timer(1000/model.getFPS(), new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// do something
...
if( finished everything ) playTimer.stop();
}
});
And once a certain button was clicked, I would simply run "playTimer.start()" to start it.
As you can see, I had it set up so that the user could set the FPS they wanted (by simply setting the first parameter of the Timer class to 1000/model.getFPS()).
Now I've tried to do something similar in Android using handlers, but I am having some difficulty. It appears that the Handler ticks are not firing at the proper intervals. It seems that they are quite slow compared to what I need it to be. This is what I did in android so far:
public void startTimer() {
playHandler = new Handler();
startTime = System.currentTimeMillis();
playHandler.removeCallbacks(updateTimeTask);
playHandler.postDelayed(updateTimeTask, 0);
}
private Runnable updateTimeTask = new Runnable() {
public void run() {
// do something
...
if( finished everything ) playHander.cancel();
else {
playHandler.postDelayed(updateTimeTask, 1000/model.getFPS());
}
}
};
Excuse the semi-pseudocode. Can anyone shed any light? Thanks guys.
You can use a timer as below. The timer runs every second incrementing the counter. Displs the counter value in textview.
Timer runs on a different thread. SO you should set the text on the UI Thread.
The counter runs from 0 to 99. After 99 the timer is cancelled. Also cancel the timer when not required like in onPause().
public class MainActivity extends Activity {
TextView _tv,tv2;
Timer _t;
int _count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_tv = (TextView) findViewById( R.id.textView1 );
_t = new Timer();
_tv.setText(R.string.app_name);
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
_count++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText(""+_count);
if(_count==99)
{
_t.cancel();
}
}
});
}
}, 1000, 1000 ); //change this value of 1000 to whatever you need.
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
_t.cancel();
}
}
If you decide not to use Timer (for whatever reason) you can just write a separate Thread that sleeps for x milliseconds and then wakes up and calls whatever Runnable you want it to call. That's going to be pretty precise. I have it working at the 10 millisecond level and it works quite nicely.
Just remember that it HAS to call a Runnable because a separate Thread can't have direct effect on anything on the main display thread.
public boolean keepPlayingAnimation = true
Handler h = new Handler()
Runnable updateDisplay = new Runnable(){
public void run(){
//do something in my display;
}
}
new Thread(){
public void run(){
while(keepPlayingAnimation){
try{
sleep(10);
}catch(Exception e){
}
h.post(updateDisplay);
}
}
}.start();
Just don't forget to set keepPlayingAnimation to false when you're done with this cause otherwise it will sit there running in the background for ever (or just about).
Take a look at Android Timer
It already has everything you need i guess. From ticking every 1 second to finish handly and so on.
Here is an example how to setup an TimerTask: setup
Not sure if you need such but i just remembered that i made this.

Setting an Android Button visible after a certain period of time?

I have a button that I don't want to be clickable until a certain amount of time has run (say, 5 seconds?) I tried creating a thread like this
continueButtonThread = new Thread()
{
#Override
public void run()
{
try {
synchronized(this){
wait(5000);
}
}
catch(InterruptedException ex){
}
continueButton.setVisibility(0);
}
};
continueButtonThread.start();
But I can't modify the setVisibility property of the button within a different thread. This is the error from the LogCat:
10-02 14:35:05.908: ERROR/AndroidRuntime(14400): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Any other way to get around this?
The problem is that you can touch views of your activity only in UI thread. you can do it by using runOnUiThread function. I would like to suggest you to use
handler.postDelayed(runnable, 5000)`
You must update your view from UI-thread. What you are doing is you are updating from non-ui-thread.
Use
contextrunOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
}});
or use handler and signalize hand.sendMessage(msg) when you think is right time to update the view visibility
Handler hand = new Handler()
{
#Override
public void handleMessage(Message msg) {
/// here change the visibility
super.handleMessage(msg);
}
};
You can use the postDelayed method from the View class (A Button is a child of View)
here is simple answer i found
Button button = (Button)findViewBYId(R.id.button);
button .setVisibility(View.INVISIBLE);
button .postDelayed(new Runnable() {
public void run() {
button .setVisibility(View.VISIBLE);
}
}, 7000);

How to properly implement android.os.Handler class instead of Timer in Android application?

So I wanted to implement Timer in my Anroid program and I found out the better way to do that is using Handler class.
First I decided to write the simplest program using Handler - the text is set after 1 second. I'm totall beginner in Android, so I went through some tutorials on web especially that one http://developer.android.com/resources/articles/timed-ui-updates.html , but still my application shows error ("application mTimer stopped").
So could anyone point out where exactly am I making mistake? I would be gratefull, here's the code:
public class mTimer extends Activity {
TextView tv;
Button button1,button2;
Handler mHandler;
private Runnable myTask = new Runnable() {
public void run() {
tv.setText("text");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mHandler.postDelayed(myTask, 100);
}
});
}
}
You should initialize your Handler in your onCreate method with at least a code like mHandler = new Handler();.
Note, that the myTask task will be run on the UI thread, since your handler is declared there
API Docs for Handler.postDelayed:
The runnable will be run on the thread
to which this handler is attached.

Categories

Resources