Waiting for X time in loop using JAVA/Android - java

In my code i want to check longitude and latitude value. If values are empty, code will check for 15 seconds. If values are received , while loop will break and will show "You win". If they are still empty, it should show "error in gps" after 15 seconds.
The problem is that code is waiting perfectly but Progress Bar is not showing in the screen because screen got stuck during wait time. After 15 seconds screen is free. Please tell me how to resolve this issue. Thanks
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), longitude.getText(), Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), latitude.getText(), Toast.LENGTH_LONG).show();
pBar = new ProgressDialog(oproprietor.this);
pBar.setCanceledOnTouchOutside(false);
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pBar.setMessage("Waiting 15 seconds");
pBar.show();
long t= System.currentTimeMillis();
long end = t+15000;
while(System.currentTimeMillis() < end) {
if(!longitude.getText().equals("") || !latitude.getText().equals("") ){
pBar.dismiss();
break;
}
else continue;
}
if(longitude.getText().equals("") || latitude.getText().equals("")){
pBar.dismiss();
Toast.makeText(oproprietor.this, "Error in gps", Toast.LENGTH_LONG).show();
}
else if(!longitude.getText().equals("") || !latitude.getText().equals("") ){
pBar.dismiss();
Toast.makeText(oproprietor.this, "You win", Toast.LENGTH_LONG).show();
}
}
});

Since this is Android, I would definitely recommend using an AsyncTask over a thread. This question has all the relevant details on how to do this safely. Using a Java thread/Runnable introduces some UI issues in android when you are interacting with the UI thread from the external thread.

Try running it in a thread.
// Note: declare ProgressDialog progress as a field in your class.
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new Thread(new Runnable() {
#Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
#Override
public void run()
{
progress.dismiss();
}
});
}
}).start();

Related

Android method is not running

It has been a long time since I stopped by this problem: my FileObserver's onEvent method is not triggered, tested, and not even the "method entered" toast is being displayed.
FileObserver fileObserver = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String path) {
Toast.makeText(getApplicationContext(), "method entered", Toast.LENGTH_SHORT).show();
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();
Help me please! Thanks in advance.
Check existence of file prev, it should cause issue.
public void startWatching ()
Added in API level 1 Start watching for events. The monitored file or
directory must exist at this time, or else no events will be reported
(even if it appears later). If monitoring is already started, this
call has no effect.

Unable to use Toast message in loop in android

I am making an android application in which
1) A loop begins and it checks whether connection is present
2)If it is, it performs TASK A and exits
3)if it isn't, it displays a TOAST message
and then goes to step 1
To implement this, I tried putting my Toast message in a loop and trying
1)Creating a class which extended Asynch Tasks and displaying the Toast in doBackground()
2)Creating a handler . I displayed the Toast message in postDelayed
3)Displaying toast within runOnUiThread()
All of them met the same fate
For a small value (<10s), the App would halt indefinitely
For a large value (=30s), the App would force close
int t=0;
while (!t=1)
{
ConnectionCheck2 cd = new ConnectionCheck2(mContext);
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent)
{
//TASK A
t=1;
}
else
{
//made call to Handler, Asynch Tasks and runOnUiThread here to display the Toast message below
Toast.makeText(MainActivity.this,"Internet is NOT connected",
Toast.LENGTH_SHORT).show();
}
}
The class ConnectionCheck constructor is initialized with the context of the class displaying the toast message. It has a method called isConnectingToInternet(), which checks whether internet connection is there. Authenticity of this class and function has been confirmed.
I tried
public void doSomeWork()
{
final Timer someTimer= new Timer ();
someTimer.schedule (new TimerTask () {
#Override
public void run()
{
ConnectionCheck2 cd = new ConnectionCheck2(MainActivity.this.getApplicationContext());
final Boolean isInternetPresent = cd.isConnectingToInternet();
runOnUiThread (new Thread(new Runnable() {
public void run()
{
if (isInternetPresent)
{
Change();
someTimer.cancel();
}
Toast.makeText(MainActivity.this.getApplicationContext(),"NOT Connected",Toast.LENGTH_SHORT).show();
}
}));
}
}, 1000, 5000);
if (g==1)
{
Toast.makeText(MainActivity.this.getApplicationContext(), "Internet is connected", Toast.LENGTH_SHORT).show();
}
}//doSomeWork
public void Change()
{
g=1;
}
//g is declared as a global variable
However, if i initially put the net off and turn it on, Internet is connected doesn't get displayed
I put the toast message in the runOnUithread() But my problem is that , if i remove the control condition then, the control first goes to, the toast message which says "internet is connected" (the statement following the timer) and then to the "NOt connected" one. Also, when , Internet connectivity is found, and timer.cancel() is executed, the control doesn't go to the statement following the timer,instead it exits. As per my thinking, first the timer module should have been executed and then the statement succeeding it should have been executed, iff timer.cancel() condition was true
While loops is not a good way to go, you can run TimerTask to run after every specified value of time.
Timer someTimer= new Timer ();
someTimer.schedule (new TimerTask () {
#Override
public void run () {
// do your Checking here, for toast use runOnUIThread() or handler.
}
}, 0, 100);
Notes:
0 is for run on call
100 is to run every 100 of a second.
Update
final Timer someTimer = new Timer ();
someTimer.schedule (new TimerTask () {
#Override
public void run () {
ConnectionCheck2 cd = new ConnectionCheck2 (MainActivity.this.getApplicationContext ());
final Boolean isInternetPresent = cd.isConnectingToInternet ();
runOnUiThread (new Thread (new Runnable () {
public void run () {
if (isInternetPresent) {
Change ();
someTimer.cancel ();
return;
}
Toast.makeText (MainActivity.this.getApplicationContext (), "NOT Connected", Toast.LENGTH_SHORT).show ();
}
}));
}
}, 0, 5000);
if (g == 1) {
Toast.makeText (MainActivity.this.getApplicationContext (), "Internet is connected", Toast.LENGTH_SHORT).show ();
}
}

Use UI thread to display toast messages?

I have a listener that is getting updates from a separate process. (I'm using IPC.)
Log.i("Test1", Thread.currentThread().toString()); // Thread[Binder_3,5,main]
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("Test2", Thread.currentThread().toString()); // Thread[main,5,main]
switch (taskId) {
case Constants.DOWNLOAD_TASK_EXECUTED: {
long time = prefs.getLong(Constants.LAST_UPDATED_KEY, System.currentTimeMillis());
String msg = Utils.getLastUpdatedString(res, time, Locale.getDefault(), false);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
break;
}
case Constants.DELETED_TASK_EXECUTED: {
String msg = res.getString(R.string.delete_success);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
break;
}
}
}
});
Is it necessary to call the runOnUiThread method and pass in a Runnable to display toast messages when I get updates? Or is it okay to just display them in the same thread (Binder_3)? I'm not modifying anything in the UI.
Tost Or Log Work in thread or other processes (but it's better to NOT Risk ! ) but Changing the UI must always Run in UI thread as you told with runOnUiThread or using handler
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
My Professional Android 4 Application Development book states, "Toasts must be created and shown on the GUI thread; otherwise, you risk throwing a cross-thread exception."

Android Timer/Clock

i want a clock/timer that's not insanely fast and force closes like a while loop.
This force closes:
while(loopEnabled == true)
{
//Do stuff
Toast toast Toast.makeText(this, "Hi!", 10000);
toast.show();
}
And so does this:
public void loop()
{
//Do stuff
Toast toast Toast.makeText(this, "Hi!", 10000);
toast.show();
resetLoop();
}
public void resetLoop()
{
Thread.sleep(100);
loop();
}
Any alternatives to stop this? I'm meaning for code to happen rapidly over and over.
Look at Handler especially the postAtTime or postDelayed methods.
For example:
private int mInterval = 1000; // in ms, so 1s here
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle)
{
mHandler = new Handler();
}
Runnable mRepeatingTask = new Runnable()
{
#Override
public void run() {
// do something here
// schedule run again for mTnterval ms from now
mHandler.postDelayed(mRepeatingTask , mInterval);
}
};
void startRepeatingTask()
{
mRepeatingTask.run();
}
void stopTask()
{
mHandler.removeCallbacks(mRepeatingTask);
}
Are you doing this in the UI thread? If so, avoid it as there is a high chance that you will get a Application Not Responding dialog.
In android timers can be implemented using TimerTask and also by Handlers.
Check this link for all sample codes. Async task, handler and timer

Android ProgressBar message change when percent is loaded

I am trying to add message when the progress bar loads on a specific percent. So when 10 percent is loaded a title or a message appear that something is loaded.
I cant do it and it forcing to close.
Any Ideas how to do it.
Below is my sample code
public void onClick(View v) {
// prepare for a progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}
});
}
// file download simulator... a really simple
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
setProgressBarIndeterminate(true);
if (fileSize == 100000) {
progressBar.setMessage("10 percent loaded");
return 10;
} else if (fileSize == 200000) {
progressBar.setMessage("20 percent loaded");
return 20;
} else if (fileSize == 300000) {
progressBar.setMessage("30 percent loaded");
return 30;
}
// ...add your own
}
return 100;
}
Thanks StackOverFlow users
Try to update progress bar like below code...
//To use the AsyncTask, it must be subclassed
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
//Create a new progress dialog
progressDialog = new ProgressDialog(LoadingScreenActivity.this);
//Set the progress dialog to display a horizontal progress bar
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
//Set the dialog message to 'Loading application View, please wait...'
progressDialog.setMessage("Loading application View, please wait...");
//This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
//This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
//The maximum number of items is 100
progressDialog.setMax(100);
//Set the current progress to zero
progressDialog.setProgress(0);
//Display the progress dialog
progressDialog.show();
}
//The code to be executed in a background thread.
#Override
protected Void doInBackground(Void... params)
{
/* This is just a code that delays the thread execution 4 times,
* during 850 milliseconds and updates the current progress. This
* is where the code that is going to be executed on a background
* thread must be placed.
*/
try
{
//Get the current thread's token
synchronized (this)
{
//Initialize an integer (that will act as a counter) to zero
int counter = 0;
//While the counter is smaller than four
while(counter <= 4)
{
//Wait 850 milliseconds
this.wait(850);
//Increment the counter
counter++;
//Set the current progress.
//This value is going to be passed to the onProgressUpdate() method.
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
//Update the progress
#Override
protected void onProgressUpdate(Integer... values)
{
//set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
//after executing the code in the thread
#Override
protected void onPostExecute(Void result)
{
//close the progress dialog
progressDialog.dismiss();
//initialize the View
setContentView(R.layout.main);
}
}
and call this AsyncTask where you want to show progress bar...
//Initialize a LoadViewTask object and call the execute() method
new LoadViewTask().execute();
Use AsynTask instead of basic threads. Within asynctask, use the callback onProgressUpdate to call progressBar.setProgress(progressBarStatus);
You only can access UI elements from the main thread.

Categories