How to refresh text in a TextView programatically? - java

I have following timer:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
--mTimer;
mTimeLeft.setText(String.valueOf(mTimer));
}
}, 0, 1000);
Text in the TextView will change when I touch the screen.
How can I refresh the TextView programatically?

I think this article will help you. http://android-developers.blogspot.com/2007/11/stitch-in-time.html
Basically you want to use the Handler class provided in the SDK. You shouldn't need to call invalidate like someone else suggested because setText does that for you.
Hope this helps!

The UI should be updated from the main thread. Take a look at this example that is closer to what you want.

TextView yourTextView =(TextView)findViewById(R.id.your_text_view_ID);
yourTextView.setText("your text");

If it doesn't change, try calling invalidate. Also, make sure you are calling from the UI thread, if not then use post method to send a runnable that will be executed in the UI thread (There you can change the text.)

Related

Perform an Action on showing AlertDialoge, then dismiss

I would like to start an AlertDialogue showing a loading message and a ProgressBar icon, then on showing the dialogue I would run the heavy processing with the ProgressBar spinning, and finally cancel the dialogue when the processing is over.
I have tried putting the logic on setOnShowListener of the alert dialogue which was not carried out. Then, I have tried starting the dialogue then using a delayed handler like the following:
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
// heavy procssing logic
// alert.dismiss();
}
}, 1000);
Though, the ProgressBar icon stopped spinning, so I assumed that my heavy processing blocked the UI. How do I achieve what I need. Thanks.
Edit: I have replaced the handler with new Thread() and everything worked properly. Would this approach cause any problems like memory leaks?
Create a new AsyncTask to do your work, this will cause any code placed in the “doInBackground()” method to be ran in a background thread, you have pre-execute and post-execute to run code on the main thread, my recommendation is create an alertDialog in the pre-execute methods and close it on the post-execute, using “publishProgress()” method In the doInBackground method to update your dialog as you need.
Otherwise instead of an alertDialog (or as well as) you can use a progressBar, simply have it in the view preciously, instantiate it as you normally would.
<ProgressBar
android:id=“+id/progressBar”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:centreInParent=true
android:indeterminate=true
android:visibility=gone />
ProgressBar progressBar = view.findViewById(R.id.progressBar)
Now when you want to show the progress bar use
progressBar.setVisibility(visible)
Or to hide
progressBar.setVisibility(gone)

CountDownTimer getting restarted after closing and reopening the app

I am trying to show a CountDownTimer to user which start decreasing immediately a user press the 'START' button, but if I'm closing the activity and reopening it, the CountDownTimer is getting reset and getting start again.
I used this link to learn how to set a CountDownTimer.
Here's how I coded it:
new CountDownTimer(ms, 1000) {
public void onTick(long millisUntilFinished) {
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % TimeUnit.MINUTES.toSeconds(1));
holder.availableFor.setText(hms);
}
public void onFinish() {
holder.linearLayout.setVisibility(View.GONE);
holder.firebaseDatabase.child(itemID).setValue(null);
holder.geoFireReference.child(itemID).setValue(null);
}
}.start();
Please let me know how to keep the Timer going even if user closes the app.
As I understand you're creating this timer in onClick method.
Try to create some global variable
CountDownTimer timer
After that create it in onclick, as you do.
and in onpause:
if (timer != null) {
timer.cancel
}
You have to use service class here
is the link which may be help you.
You need to store the timer data in some global scope so the timer once set not get altered with activity life cycle.
best practice suggest, use service like answered by #shahid17june
also if you don't want to use that, or setup variable to store counttimerdata in application class (global data), and update it appropriately.

How to use a JProgressBar in a different Thread?

I'm using POI in a function to fill the content of my excel document (it takes 10 seconds) and when i call my function I want to use a JProgressBar to see the progress, but the button and the program is block, i need to to make in other thread? and how can I do it? an example of my code:
btnEjecutar.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
//the function
generarDocumento(nombre);
}
Try to use an invokeLater, like the example bellow:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generarDocumento(nombre);
});
Event listeners are executed in the UI thread. If an event listener takes a long time, the UI will stop working/lock up/block/hang.
My guess is that the method generarDocumento() takes a long time. If you want the UI to continue working, you must run it in a worker thread. The Java documentation contains several examples how to do that: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
The last example in the tutorial contains demo code how to update a progress bar: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/ProgressBarDemoProject/src/components/ProgressBarDemo.java
Note: The linked content is copyrighted; therefore I can't copy it here.

Android - Display the loading text

I am trying to display Loading text only when its loading.
The problem is im setting it to visible and straight after to invisible once finished loading. But text never has a chance to update. Is there a way to force refresh the screen, or maybe there is another way to do this?
Thanks
This is my code
SearchBtn = (Button) findViewById(R.id.SearchButton);
SearchBtn.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
//this is never seen because its set straight after to invisible
LoadingText.setVisibility(View.VISIBLE);
SearchFor(EditSearchField.getText().toString()); // all loading done here
LoadingText.setVisibility(View.INVISIBLE);
HideKeyboard();
}
});
You need to do the actual load in a separate thread. You'd be best off using an AsyncTask for this. Take a look at http://www.vogella.com/articles/AndroidPerformance/article.html

How can I schedule a particular thread in Blackberry

I want to auto-schedule a thread with a particular time interval. I also need to execute this in the background continously without hangs to the device.
I have tried this with Application Manager Class but it's for application scheduling and I need to schedule thread within the application.
I would use TimerTask:
public class MyScreen extends MainScreen {
private Timer mTimer;
public MyScreen() {
mTimer = new Timer();
//start after 1 second, repeat every 5 second
mTimer.schedule(mTimerTask, 0, 5000);
}
TimerTask mTimerTask = new TimerTask() {
public void run() {
// some processing here
}
};
}
see BlackBerry API Hidden Gems (Part Two)
use UiApplication.getUiApplication().invokeLater()
it accepts a delay and repeat parameters and will perform exactly what you need.
EDIT
I know this post is old but this is by far the best option to schedule repeating events and I would like to add that to stop the scheduled event the following is required:
//Start repeating "runnable" thread every 10 seconds and save the event ID
int eventId = UiApplication.getUiApplication().invokeLater(runnable, 10000, true);
//Cancel the repetition by the saved ID
UiApplication.getUiApplication().cancelInvokeLater(eventId);
Assuming you want it to run a thread on device startup:
Create a second project and list it as an alternate entry point.
In your UiApplication or Application main(), check the argument passed to the project. Do your periodic stuff there via Thread.sleep and don't call enterEventDispatcher.
search for "autostart":
http://docs.blackberry.com/en/developers/deliverables/1076/development.pdf
Or if you want to do something once a user "starts" it, then look into creating a new thread to do your timing stuff. Override your screen's onClose() and use Application.getActivation().deactivate() to throw the screen into the background.
Or there's a other ways to do something like this like invokeLater, etc. Maybe eventlisteners may do what you need, but you didn't give a lot of details.
As long as the application is running - just create the thread and after each bit of work call Thread.sleep for as long as you need it to stay dormant.
If you need it to wake up at a particular time, rather than just sleep for a particular time, then you can do something like the following:
Date wakeUpAt = ...; // Get this however
Date now = new Date();
long millisToSleepFor = wakeUpAt.getTime() - now.getTime();
Thread.sleep(millisToSleepFor);

Categories