setText causes crash after second implementation? - android

public void displayCurrentLocation(){
mCurrentLocation=mLocationClient.getLastLocation();
TextView coordinates = (TextView)findViewById(R.id.coordinates);
coordinates.setText(mCurrentLocation.getLatitude()+", "+mCurrentLocation.getLongitude());
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
displayCurrentLocation();
}
}, 2000);
}
Just testing the concepts here. I am trying to get an updated current location every 2 seconds and display it in a TextView. I set this up so that it would do it once, but when I added the timer, it will setText once, but the next time it crashes. What is wrong?

I am trying to get an updated current location every 2 seconds and display it in a TextView.
My guess (based on above comment) is you are updating ui from a Timer task. Timer tasks runs on a different thread. You can't update ui from it. You need to update ui from a ui thread.
Use a Handler or runOnUiThread
runOnUiThread(new Runnable() {
public void run() {
// update ui here
}
});
Handler is a better option.
http://developer.android.com/reference/android/os/Handler.html
When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
So if you create handler on the ui thread it is bound to it and you can update ui there.
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 2000);
}
};
m_handlerTask.run();
To cancel the run
m_handler.removeCallbacks(m_handlerTask); // cancel run

Timer runs in a separate Thread and where as you can not touch the UI views in non UI Thread...
use Handler of a TextView or runOnUiThread()
this may help you...
public void displayCurrentLocation() {
mCurrentLocation = mLocationClient.getLastLocation();
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView coordinates = (TextView) findViewById(R.id.coordinates);
coordinates.setText(mCurrentLocation.getLatitude() + ", "
+ mCurrentLocation.getLongitude());
}
});
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
displayCurrentLocation();
}
}, 2000);

Related

Interrupting execution of handler/timer if user input occurs Android

I am trying to make feature that will display text on screen and after few sec to disappear. I have managed that with Handler and Timer classes.
The problem is that I need to somehow stop executing these timers if user makes input over keyboard before timer's time pass and rerun timer again to display different data.
I am facing with problem that the view has remaining visible after user input and disappears after 1-2 sec instead after 5 sec.
the codes that I have used:
//do something
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//do something again
}
}, 5000);
}
AND
//do something
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// this code will be executed after 5 seconds
//do something again
}
}, 5000);
Can you help me to solve this problem?
THanks
For timer you can use timer.cancel(); and for handler you can use handler.removeCallbacks(runnable);
So just declare a Runnable runnable as a global variable, then instantiate it as below
handler.postDelayed(runnable = new Runnable() {
#Override
public void run() {
//do something again
}
}, 5000);
this is the runnable you will pass when you removeCallbacks. Similarly you can use this handler.removeCallbacks(null); this will stop all the handlers that have been declared. I would suggest that you declare both the handler and the timer as global variables and only instatntiate them when you are calling the timer tasks.

How to call AsyncTask recursively in android?

i tried both the links : Starting AsyncTask recursively after a gap of 5 minutes and Need advice new AsyncTask recursive calling
but they didnt solve my problem.
i want to use asynctask recursively after every 10sec of gap.
iam creating an app in which a dialog box shows with some content whenever some condition full fill and i need to change that content for that i am trying to call asynctask with a combination of thread and handler.
Thanks in advance!!!!
This repeats every 1000ms:
handler must be final as it is accessed within inner class
final Handler handler = new Handler();
Thread threadObj = new Thread() {
public void run() {
// Asynctask
// delay
handler.postDelayed(this, 1000);
}
};
//to start thread
threadObj.start();
//to stop thread
handler.removeCallbacks(threadObj);
Create a runnable where you start the asynctask again and again and the start the task for the first time by calling handler.postDelayed(repeatingTask , 1000);
private Runnable repeatingTask = new Runnable() {
public void run() {
new MyAsyncTask().execute("my String");
handler.postDelayed(this, 1000);
}
};
This way the runnable will be repeated again and again.Hope this helps you.
public void recur()
{
private Runnable repeat = new Runnable() {
public void run() {
new AsycnCaller().execute();
handler.postDelayed(this, 10000);
}
};
}
call this function where you want Start
and also call this in postexecution of asyntask

What code do i implement to have a time limit in my game

I'm createing a quiz that has a time limit and i dont know what to implement to have a timelimit in my level 1 class. what should i implement? can you show me a complete code?
am i correct?
private Runnable task = new Runnable() {
public void run() {
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
};
private void onCreate() {
Handler handler = new Handler();
handler.postDelayed(task, 60000);
There are different ways to do it. One way is to use a Runnable and a Handler.
First, define the Runnable:
private Runnable task = new Runnable() {
public void run() {
Log.i(TAG, "Time limit reached!");
// Execute code here
}
};
Then you call it (say at the start of the level, onCreate) with this Handler and postDelayed
Handler handler = new Handler();
handler.postDelayed(task, 60000);
The code within the run() method of the Runnable will execute 60 seconds after you call postDelayed
If you need regular notifications you can also use a CountDownTimer

Using toast inside timertask

Found someone has similar issue online here.
This doesn't work:
Timer t = new Timer(false);
t.schedule(new TimerTask() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "msg", Toast.LENGTH_LONG).show();
}
}, 5000);
But if I instantiate the toast outside the timertask then show it inside run,it works.
I think it may relate to the so-called UI thread,
but how exactly ?
try this
Timer t = new Timer(false);
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "msg", Toast.LENGTH_LONG).show();
}
});
}
}, 5000);
Using Timer starts a new thread, I suppose that thread does not have access to getApplicationContext. The proper way to do it is to use Handler and call the postDelayed method of the Handler - which does not start a new thread.
Read about this: http://developer.android.com/resources/articles/timed-ui-updates.html
The link you posted has a working example, which is the proper way to do it:
final Context ctx = this;
Handler mHandler = new Handler();
Runnable
makeToast = new Runnable() {
public void run() {
Toast.makeText(ctx, "msg", Toast.LENGTH_LONG).show();
}
};
mHandler.postDelayed(makeToast, 1000);
Everytime you start an application, it starts on the UI Thread (also called the Main Thread).
Whenever you create a new Thread, or Timer, or AsyncTask, by definition, they're creating new Threads. Threads that aren't the main thread simply don't have permission to modify the UI.
Toast use on UIThread. You can by Handler or runOnUiThread

How to Delay Execution of Code For X Amount of Time in Android

On button click I want to begin a timer of 5 minutes and then execute a method that will check for certain conditions and set off alerts if conditions are right. I've seen examples with timers and postDelay, but don't really understand why one would use one vs another. What is the best way to accomplish what I am trying to do? I don't want to lock up the UI during the 5 minutes. The user should be free to use the app as normal during the countdown.
EDIT: I am trying the postDelayed suggestion but visual studio is not liking something about my code. It looks exactly like examples I've found. My be a mono for android thing.
Handler h = new Handler();
Runnable r = new Runnable(){
public void run()
{
Dialog d = inst2.showBuilder(this, "test", "test");
d.Show();
}
};
h.postDelayed(r, 5000);
Specifically the code block inside of run throws all kinds of "} expected" and "a namespace cannot directly contain members such as fields or methods" exceptions.
Try using Timer Object :
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask()
{
#Override
public void run()
{
// Your code goes here
}
}, 1000); // 1sec
final Handler handler = new Handler();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
handler.post(new Runnable()
{
public void run()
{
// YOUR Code
}
});
}
}, 1000); // 1sec
You can start a simple Thread that will sleep in background for 5 minutes and then call a function. While the thread sleeps in background the UI will not freeze. When the thread finish executing what you want you can set off alerts by sending some intents as notifications and receive them in some Broadcast Receivers.
Hope this helps
Use Handler.postDelayed(Runnable block); method to execute delay, as android also not recommend to use timer.
Handler h = new Handler();
Action myAction = () =>
{
// your code that you want to delay here
};
h.PostDelayed(myAction, 1000);

Categories

Resources