hi to all can any one help me with this problem i have brackets problem there is 1 that is either extra or missing cant find it
thank you
Handler speedHandler = new Handler();
Runnable unitspeedtimer = new Runnable() {
public void run() {
speedTextView=(TextView)findViewById(R.id.speedTextView);
MaxspeedTextView=(TextView)findViewById(R.id.MaxspeedTextView);
//1 m/s = 3.6 km/h
float MySpeed = location.getSpeed() * 3.6;
float MaxSpeed = 75.00;
Timer updateTimer = new Timer("velocityUpdate");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI();
}
}, 0, 3000);
}
You need one more }; at the end to close the Runnable. Consistent indentation would really help here.
Handler speedHandler = new Handler();
Runnable unitspeedtimer = new Runnable() {
public void run() {
speedTextView=(TextView)findViewById(R.id.speedTextView);
MaxspeedTextView=(TextView)findViewById(R.id.MaxspeedTextView);
//1 m/s = 3.6 km/h
float MySpeed = location.getSpeed() * 3.6;
float MaxSpeed = 75.00;
Timer updateTimer = new Timer("velocityUpdate");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI();
}
}, 0, 3000);
}
};
Related
I'm trying to use "handler" to repeat a function (really trying to learn how to use it), but the function is only executed once.
public Runnable runnableCode = new Runnable() {
#Override
public void run() {
if (changeColor) {
myPaint.setColor(Color.BLUE);
Rect r = new Rect(0, 0, widthInPixels * 90, heightInPixels * 90);
myCanvas.drawRect(r, myPaint);
changeColor = false;
} else {
myPaint.setColor(Color.RED);
Rect r = new Rect(0, 0, widthInPixels * 90, heightInPixels * 90);
myCanvas.drawRect(r, myPaint);
changeColor = true;
}
handler.postDelayed(runnableCode, 1000);
}
};
public void play (View view) {
handler.post(runnableCode);
}
You should loop through your handler to repeat itself. But you are just calling it once.
Try this code below:
final Handler handler = new Handler();
int count = 0; //keep track of count
final Runnable runnable = new Runnable() {
public void run() {
if (count++ < 5) { //how many times do you want to repeat?
handler.postDelayed(this, 5000); //repeat handler
}
}
};
//initial trigger
handler.post(runnable);
Let me know if you have any questions. Thanks.
Ensure that your bool changeColor is being modified by making it a final one element array
Try code below:
final Handler handler = new Handler();
final boolean[] changeColor = {false};
Runnable runnableCode = new Runnable() {
#Override
public void run() {
if (changeColor[0]) {
// code here
changeColor[0] = false;
} else {
// other code here
changeColor[0] = true;
}
messageHandler.postDelayed(this, 1000);
}
};
handler.post(runnableCode);
I tried adding a "toast", and that does get repeated; the problem's the drawing for some reason.
I tried firing the function from a button, and it looks like the repetitions accumulate and then fire all at once when I hit the button again.
Still fighting with this. I've also tried a timer, thread.sleep and ScheduledThreadPoolExecutor, and nothing.
I am developing an app in which a thread will run in main thread and it will call a list of users in every 1 sec,but i am getting the pop up that ANR. please suggest. How To Resolve?
Below is my code
super.onCreate(savedInstanceState);
System.setProperty("java.net.preferIPv4Stack", "true");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
mHandler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
listofUsers = GcmIntentService.getListOfUsers();
if (listofUsers.size() > 0) {
for (int index = 0; index < listofUsers.size(); index++) {
if (index == 0) {
startTime = listofUsers.get(0).getLoggedinDateTime();
} else {
Calendar calender1 = Calendar.getInstance();
calender1.setTime(startTime);
calender1.add(Calendar.SECOND, i);
newTime = calender1.getTime();
listofUsers.get(index).setLoggedinDateTime(newTime);
i = i + 72;
}
///user time is checked with the current system time.
Iterator<UserInformation> userDetailsIter = listofUsers.iterator();
Calendar calender2 = Calendar.getInstance();
while (userDetailsIter.hasNext()) {
UserInformation newUserInfo = userDetailsIter.next();
Date userTime=newUserInfo.getLoggedinDateTime();
Date systemTime=calender2.getTime();
if ( userTime.compareTo(systemTime) < 0 ) {
userDetailsIter.remove();
}
}
}
}
mHandler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
mHandler.postDelayed(this, 100);
}
}
};
mHandler.postDelayed(runable, 100);
}
Please help me by guiding me about what I have done wrong
You can't make a while loop or any kind of long running operation on main queue
why don't you make a normal thread inside a repeated timer
like the below code
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
check();
}
}, 0, 100);
and inside check make a thread and do what ever you want
public void check(){
new Thread(new new Runnable() {
#Override
public void run() {
// do what you want here
}
}).start();
}
Hi every one can you help to create a 5 seconds timer that runs for every 3 or 5 seconds.. im new in android pls help me
i have only created a 5 seconds timer but it only run once.. i want it to run for every 5 seconds..
and here is my code :
txt1 = (TextView)findViewById(R.id.textView1);
final Handler handler = new Handler();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// pos=rand.nextInt(10);
//txt1.setText(""+pos);
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
}
});
}
};
Timer timer = new Timer();
timer.schedule(task, 1000, 1000);
Thx :)
You can do it using below code, handler calls itself again and again.
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
handler.postDelayed(this, 3000);
}
catch (Exception e) {
// handle exception
}
}
};
handler.postDelayed(runable, 5000);
I am scheduling a simple task that should update a text field in 4 seconds.
However everytime this is called the activity pauses and does not show the value in the text field until I restart the activity.
private void showDelayedValue() {
Runnable longRunningTask = new Runnable() {
public void run() {
int randomVal = randomNumberGenerator.nextInt(30 - -10) - 10; //random number between -10 and 30
String randomValStr = Integer.toString(randomVal);
Log.i(this.getClass().getSimpleName(),
"FIRED startScheduler: " + randomValStr);
theFieldOnScreenTV.setText(randomTempStr);
}
};
//show the value in 2 seconds
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
The log shows:
FIRED startScheduler: 4
but does not update the TextView theFieldOnScreenTV
Instead onPause is called right after Fired startScheduler: is displayed in LogCat.
Many thanks!
EDIT:
This worked for me following Alex' approach:
private void showDelayedValue() {
int randomX = randomNumberGenerator.nextInt(30 - -10) - 10;
final String randomXStr = Integer.toString(randomX);
final Runnable updateFieldR = new Runnable() {
public void run() {
theFieldOnScreenTV.setText(randomXStr);
}
};
Runnable longRunningTask = new Runnable() {
public void run() {
theFieldOnScreenTV.post(updateFieldR);
}
};
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
instead of
theFieldOnScreenTV.setText(randomTempStr);
try
theFieldOnScreenTV.post(new Runnable() { theFieldOnScreenTV.setText(randomTempStr); } );
Have a try using Handlers.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
theFieldOnScreenTV.setText(randomTempStr);
}
});
This is the problem about loading.
My application should wait for 3 seconds and then draw path. Now, the loading message box appears within 3 seconds but the application does not wait for 3 seconds and draw immediately . Is there any problem in my coding ?
Many Thanks!!
public void drawpath(){
// first to do some checking
if (sourceLat.equals("22.3366467") && destinationLat.equals("35.68449"))
ShowMsgDialog("Please enter the starting point and destination");
else if (sourceLat.equals("22.3366467") )
ShowMsgDialog("Please enter the starting point by touch");
else if (destinationLat.equals("35.68449") )
ShowMsgDialog("Please enter the destination by touch");
else if (pairs != null ){
// go to loading function
loading();
// Start to draw the path
String[] lngLat = pairs[0].split(",");
GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
mc = mapView.getController();
geoPoint = startGP;
mc.setCenter(geoPoint);
mc.setZoom(15);
mapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
......
}
in the loading() function:
private void loading() {
progressDialog = ProgressDialog.show(this, "Showing Data..", "please wait", true, false);
new Thread()
{
public void run()
{
try{
sleep(3000);
}
catch (Exception e){
e.printStackTrace();
}
finally{
progressDialog.dismiss();
}
}
}.start();
}
You can also do it in the following way:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
drawPath();
}
}, 5000);
This won't display any lint warnings.
A handler would do the job very easily.You won't need a separate thread or AsyncTask(). Use a Handler in your Activity to delay events such as calling the method drawPath() in your case:
private RefreshHandler mRedrawHandler = new RefreshHandler();
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
drawPath();
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
In your onCreate() of Activity (or In onClick() of any button, whenever you want to start a delay), call mRedrawHandler.sleep(3000); , drawPath(); is a method where you are starting the draw.
After you spawn a new thread your code regains control and continues executing. Your additional thread is waiting not the original one.
for delayer in android activity
import android.os.Handler;
in code main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 5000);
But the above code is obsolete
It is better to use the following code
Use it for Java
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
// Your Code
}
}, 3000);
Use it for Kotlin
Handler(Looper.getMainLooper()).postDelayed({
{
//Your Code
}
}, 3000)