76534

Toast in loop is not displaying properly

Question:

I have the following code in my main activity (Note: GPSTracker in this application works):

double latitude, longitude; gps = new GPSTracker(MainActivity.this); if(gps.canGetLocation()){ latitude = gps.getLatitude(); longitude = gps.getLongitude(); Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); } else{ gps.showSettingsAlert(); }

I want to create a loop, which would display in some time intervals Toast with my current position. I´ve tried this:

double latitude, longitude; long currentTime = System.currentTimeMillis(); long myTimestamp = currentTime; int i = 0; gps = new GPSTracker(MainActivity.this); while(i < 5) { myTimestamp = System.currentTimeMillis(); if((myTimestamp - currentTime) > 5000) { i++; currentTime = System.currentTimeMillis(); if(gps.canGetLocation()){ latitude = gps.getLatitude(); longitude = gps.getLongitude(); Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); }else{ gps.showSettingsAlert(); } } }

With this code, Toast is shown only one time (the last iteration). Could you help me with this? Thanks in advance.

Answer1:

<blockquote>

I want it to be shown every iteration (for example every 5 seconds).

</blockquote>

The code above doesn't loop every five seconds, it loops continuously but only increments your counter every five seconds... This is a very inefficient way of creating a time delay because nothing else can happen while the loop runs. (Even if you run this on a separate thread it is still not good tactic.)

Instead use LocationManager's <a href="https://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29" rel="nofollow">requestLocationUpdates</a> which will use callbacks so your app can do things between updates. A couple quick notes:

<ul><li>Understand that the GPS may not be able to get a fix every five seconds and that this interval is really short so use it sparingly or you'll run the battery down. </li> <li>Some pre-Jelly Bean devices may not observe the minTime parameter, but you can enforce your time parameter yourself as I describe in <a href="https://stackoverflow.com/q/13093613/1267661" rel="nofollow">Android Location Listener call very often</a>.</li> </ul><hr />

All that aside, you use your existing code but I recommend a Handler and Runnable, like this:

handler.postDelayed(new Runnable() { @Override public void run() { // Fetch your location here // Run the code again in about 5 seconds handler.postDelayed(this, 5000); } }, 5000);

Answer2:

One problem is that this method does a 'busy-wait', which, I suspect, prevents the toast from being displayed. Try doing a sleep() to wait until it's time for the next Toast:

public void sleepForMs(long sleepTimeMs) { Date now = new Date(); Date wakeAt = new Date(now.getTime() + sleepTimeMs); while (now.before(wakeAt)) { try { long msToSleep = wakeAt.getTime() - now.getTime(); Thread.sleep(msToSleep); } catch (InterruptedException e) { } now = new Date(); } }

Recommend

  • Iterate twice through a DataReader
  • How to create two column output from a single column
  • How can I get the choice “H2” back in the H2 consol?
  • Approximate Order-Preserving Huffman Code
  • calculate gradient output for Theta update rule
  • Blackberry - Custom EditField Cursor
  • MongoDb aggregation
  • print() is showing quotation marks in results
  • Content-Length header not returned from Pylons response
  • Play WS (2.2.1): post/put large request
  • Q promise. Difference between .when and .then
  • Body moving without any force applied? (Box2d)
  • How to access EntityManager inside Entity class in EJB3
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • Update CALayer sublayers immediately
  • Illegal mix of collations for operation for date/time comparison
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • vba code to select only visible cells in specific column except heading
  • Rearranging Cells in UITableView Bug & Saving Changes
  • R: gsub and capture
  • retrieve vertices with no linked edge in arangodb
  • PHP: When would you need the self:: keyword?
  • Benchmarking RAM performance - UWP and C#
  • Acquiring multiple attributes from .xml file in c#
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Android Google Maps API OnLocationChanged only called once
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Sorting a 2D array using the second column C++
  • reshape alternating columns in less time and using less memory
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal
  • Net Present Value in Excel for Grouped Recurring CF
  • How can I use threading to 'tick' a timer to be accessed by other threads?