Sorry for asking such a basic question, Actually i need to call a method after certain time interval which is actually assigning a text to textView in android,which is supposed to change.So please suggest me the best way to do this.
Thanking you in anticipation.
{
int splashTime=3000;
int waited = 0;
while(waited < splashTime)
{
try {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
waited+=100;
}
Have you considered CountDownTimer ? For example something like this:
/**
* Anonymous inner class for CountdownTimer
*/
new CountDownTimer(3000, 1000) { // Convenient timing object that can do certain actions on each tick
/**
* Handler of each tick.
* #param millisUntilFinished - millisecs until the end
*/
#Override
public void onTick(long millisUntilFinished) {
// Currently not needed
}
/**
* Listener for CountDownTimer when done.
*/
#Override
public void onFinish() {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
}
}.start();
Of course, you can put it in a loop.
you can use Timer to update your UI with delay like this:
long delayInMillis = 3000; // 3s
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// you need to update UI on UIThread
runOnUiThread(new Runnable() {
#Override
public void run() {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
}
});
}
}, delayInMillis);
Use a handler and put it in a Runnable:
int splashTime = 3000;
Handler handler = new Handler(activity.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
ds.open();
String quotes=ds.getRandomQuote();
textView.setText(quotes);
ds.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}, splashTime);
Related
I'm trying to create a class that sequentially performs the Bluetooth tasks without user intervention aside from starting the process. In this class an external event calls the overridden method "executeCentral" from there it calls setup() to enable and request permissions. If they complete successfully the initialize() method is called and waits for one second before calling the Bluetooth initialize() which is executed in the EDT. If it runs without exception it calls startScanning() which also waits 1 second before calling Bluetooth startScan() in the EDT. After scanning has started it waits 10 seconds before calling Bluetooth stopScan() in the EDT.
I recreated the project for a clean setup and used the "downloader" in the Codename One Settings. It compiles successfully and runs, but reports an exception on "Bluetooth not initialized"
Any idea on what I am doing wrong? I'm under the impression that all calls must be done in the EDT.
The single form BTDemo compiles and executes each task as a separate user initiated event.
public class UITaskBluetoothEx extends com.crumptech.library.mobile.ui.tasks.UITaskBluetooth {
protected Bluetooth bt = new Bluetooth();
protected Map devices = new HashMap();
public UITaskBluetoothEx() {
super();
}
#Override
public String getReplacement() {
return "UITaskBluetoothEx";
}
protected void showDebug(String message) {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
UIApplication.showDebug("UITaskBluetoothEx " + message);
completed(result(false));
}
});
}
#Override
protected void executeCentral() {
bt = new Bluetooth();
try {
setup();
initialize();
} catch (Exception e) {
showDebug(e.getMessage());
}
}
protected void setup() throws IOException {
if (!bt.isEnabled()) {
bt.enable();
}
if (!bt.hasPermission()) {
bt.requestPermission();
}
}
protected void initialize() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
try {
if (!bt.isInitialized()) {
bt.initialize(true, false, "ShopMyLocalStores");
}
startScanning();
} catch (Exception e) {
showDebug(e.getMessage());
}
}
});
}
}, 1000);
}
protected void startScanning() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
try {
if (!bt.isScanning()) {
bt.startScan(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
try {
JSONObject res = (JSONObject) evt.getSource();
if (res.getString("status").equals("scanResult")) {
if (!devices.containsKey(res.getString("address"))) {
devices.put(res.getString("address"), res);
}
}
} catch (JSONException e) {
}
}
}, null, true, Bluetooth.SCAN_MODE_LOW_POWER, Bluetooth.MATCH_MODE_STICKY, Bluetooth.MATCH_NUM_MAX_ADVERTISEMENT, Bluetooth.CALLBACK_TYPE_ALL_MATCHES);
stopScanning();
}
} catch (Exception e) {
showDebug(e.getMessage());
}
}
});
}
}, 1000);
}
protected void stopScanning() {
try {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
try {
if (bt.isScanning()) {
bt.stopScan();
}
} catch (Exception e) {
showDebug(e.getMessage());
}
showResults();
}
});
}
}, 10000);
} catch (Exception e) {
}
}
protected void showResults() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
String text = "";
Iterator it = devices.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
text += (pair.getKey() + " = " + pair.getValue() + "\r\n");
}
UIApplication.showDebug(text);
completed(result(true));
}
});
}
}, 1000);
}
}
It looks like some methods currently aren't supported on iOS. These will throw IOExceptions if they are called on iOS. This is a limitation that is baked into the Cordova plugin that we ported. These methods literally return "Unsupported Operation" inside the plugin. I'm not sure if these are just omissions of the plugin, or if they can't be supported. The list of methods that are currently unsupported on iOS are:
isEnabled()
enable()
disable()
mtu()
requestConnectionPriority()
hasPermission()
requestPermission()
isLocationEnabled()
requestLocation()
I have marked these in the javadocs for the Bluetooth class to help identify them. We'll likely have to do something here to clean it up ... perhaps an exception is not the best thing.
In any case, your test app is failing because you call isEnabled() and initialize() inside the same try/catch block. isEnabled throws an exception so it never gets to initialize() and your tests aren't run.
I have adapted your code into my own test case, and made that modification, and it appears to run fine.
I have the following code:
int x=0;
private void startTimerThread() {
System.out.println("enter");
System.out.println("percentage"+percentage);
System.out.println("x"+x);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
for (x = 0; x>= percentage; x++ ) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
textpercentage.animate(x, x++);
System.out.println("enter"+x);
}
});
}
}
};
new Thread(runnable).start();
}
I am trying to animate digits on a textview using timely text view, however when I call startTimerThread from my code which is outside of onCreate neither do I get the text view to display not does the system.out execute. What do I miss here?
try like this
Handler handler = new Handler();
int delay=1000;
Runnable rann=new Runnable() {
#Override
public void run() {
//Write Your logic here which you want to perform periodically
System.out.println("Handler is running : ");
//to call the same thread repeatedly calling handler again
handler.postDelayed(rann, delay);
}
};
private void startHandler() {
//here the handler will executes the rannable after that particulary delay milli seconds
handler.postDelayed(rann, delay);
}
private void stopHandler() {
handler.removeCallbacks(rann);
}
I need stop thread and handler when my progress bar reaches 0 from 100 when thread runs the progress bar reaches but the progressStatus value going in negative please help me to stop thread after progress bar reaches 0
new Thread(runn =new Runnable() {
public void run() {
while (progressStatus <= 100) {
progressStatus += doWork();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i=-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
}
}
});
}
}
private int doWork() {
return i;
}
}).start();
your program is not thread safe, you actually reading and writing a variable (progressStatus) from two different threads, you must avoid doing that or if you want to do that you must use synchronized block. In order to solve your problem you can do this way:
Thread t;
progressStatus = 100;
t = new Thread(runn =new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
// Update the progress bar
handler.post(runn1=new Runnable() {
public void run() {
bar.setProgress(progressStatus);
progressStatus=progressStatus-1;
if(bar.getProgress()==0)
{
handler.removeCallbacks(runn);
handler.removeCallbacks(runn1);
System.out.println("Reached");
congrats.setVisibility(View.VISIBLE);
restart.setVisibility(View.VISIBLE);
rightbutton.setVisibility(View.GONE);
wrongbutton.setVisibility(View.GONE);
t.interrupt();
}
}
});
another way that i recommend you is using ScheduledThreadPoolExecutor with the function scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit). something like:
final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
}
});
}
}
}, 0,10, TimeUnit.MILLISECONDS);
and in order to close it use myTimer.shutdownNow();
I am writing simple game, where some action must accelerating during the process. The question is how to change timer's period?
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//
// I need to change timer's period here
//
}
});
}
};
timer.schedule(timerTask, 0, period);
Will be glad to hear any advices.
I assume that you are performing some logic within the run() method of the TimerTask.
I think a simpler way to go about this would be to use a Handler. This is possibly more idiomatic for Android:
private final Handler mHandler = new Handler();
private final Runnable mTask = new Runnable() {
#Override
public void run() {
// Do your logic.
// Now post again.
mHandler.postDelayed(mTask, /* choose a new delay period */);
}
};
public void init() {
delay = 1000L; // 1 second.
mHandler.postDelayed(mTask, delay);
}
I want to update the text of a notification every second. i wrote this code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Text");
builder.setContentText("value updated every 1 second");
}
}
}, 1*1000);
but the value is not updated every 1 second but only one time. why? how can i do this?
Try to use Timers Handler ll invoke one time.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
updateUI();
}
};
timer.scheduleAtFixedRate(task, 0,1000);
put your Handler to separate method
public void updateUI(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Text");
builder.setContentText("value updated every 1 second");
}
}, 1000);
}
his code starts an thread which sleeps 1000 milliseconds every round.
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// update TextView here!
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();