I run a class LokasyonBulucu()
LokasyonBulucu lokasyonBulucu= new LokasyonBulucu();
lokasyonBulucu.LokasyonBul(context);
I take two variable from this class lat and lon
lat=lokasyonBulucu.location.getLatitude();
lon= lokasyonBulucu.location.getLongitude();
but I want to waiting class found coordinates... because it take amount time.
if it find lat and lon I want to run this function
new arkaPlanIsleri(kategori_id, lat , lon).execute();
Use a for loop to check every second with a maximum number of seconds to wait. Check every second if the lat and lon are already found. If so execute the method and break out of the waiting loop:
for(int i = 0; i < 10; i++) { //maximum 10 seconds to wait
if(lat != null && lon != null) { //check if the lat and lon are already found
new arkaPlanIsleri(kategori_id, lat , lon).execute();
break; //stop the waiting loop
}
SystemClock.sleep(1000); //wait one second
}
Related
I am trying to make an Android app which takes the location data in certain intervals e.g:- 5 sec, 1 min,etc. Here is my code :-
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(loc!=null)
{
//Required Interval
tInterval =(minInterval*60*1000) + (secInterval)*1000 - 1000;
//The app also supports interval mode
RadioButton sel = (RadioButton) findViewById(mode.getCheckedRadioButtonId());
//Code for Manual Functionality
if(sel.getText().equals(MANUAL_RADIO))
{
Time t = new Time();
t.setToNow();
db.addLocationAtTime(loc, t);
Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
locate.removeUpdates(this);
b.setText(MANUAL_BUTTON);
d.setEnabled(true);
}
//Code for Interval functionality
else if(sel.getText().equals(INTERVAL_RADIO))
{
//count is object of Countdown class which is a Thread object
if(count == null)
{
//t is a Time object
t.setToNow();
//SQLiteDatabase object for logging Location with Time
db.addLocationAtTime(loc, t);
Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
count = new CountDown( tInterval);
count.start();
}
else if(count.getState().toString().equals("TERMINATED"))
{
t.setToNow();
db.addLocationAtTime(loc, t);
Toast.makeText(getApplicationContext(), "Location Added to Database",Toast.LENGTH_SHORT).show();
count = new CountDown(tInterval);
count.start();
}
}
}
}
Here is the code for the Countdown class:-
This class is used to add the interval to the app
public class CountDown extends Thread
{
long time;
public CountDown(long duration)
{
time = duration;
}
public void run()
{
long t1 = System.currentTimeMillis();
long t2 = 0;
do
{
t2 = System.currentTimeMillis();
}while(t2 - t1 < time);
}
}
The problem is that using the above code I am not getting accurate intervals. I am always getting 1 sec extra (due to which I subtracted 1000 in the formula) , but this 1 sec is not happening always. So can anyone please tell me what I am doing wrong ?
Look at LocationManager.requestLocationUpdates, just pass your time interval in parameter..
LocationManager mLocationManager = (LocationManager).getSystemService(mActivity.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, new GeoUpdateHandler());
i think here you need to use default features , no need to use Timer
NETWORK_PROVIDER
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, networkLocationListener);
GPS_PROVIDER
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, gpsLocationListener);
Here ,
minTime(2nd field) => minimum time interval between location updates, in milliseconds
minDistance(3rd field) => minimum distance between location updates, in meters
Documentation
I don't think the minTime param of the requestLocationUpdates(...) methods does anything at all. It does not seem to prevent distance-based updates from coming at shorter intervals, and it definitely does not cause updates to come at the specified interval, as many people seem to think. I've tried it on devices from Android 2.3.6 to 4.0.4.
I'm developing an Android app which is using Google Places API.
Once I get all the places result, I want to sort it according to the algorithm.
Which is, the places result will only being put into the Hash Map if the algorithm is >= 0.
But the problem now is, when I run it, the algorithm result in the for loop did not change during the looping.
My algorithm is:
balance = user_hour-visi-duration.
balance = 240-60-20 = 160
Let's say the balance is 160, it will remain 160 until the for loop ended.
I wanted each time of the looping, the value of balance will decreased untill negative value.
FYI, balance variable is not a local variable.
Does anybody know how to solve this?
Here is the part of the code.
// loop through each place
for (Place p : nearPlaces.results) {
balance = user_hour - duration - visit;
HashMap<String, String> map = new HashMap<String, String>();
//////////////////////////////////////////////////////////////////
googlePlaces = new GooglePlaces();
try {
placeDetails = googlePlaces.getPlaceDetails(p.reference);
} catch (Exception e) {
e.printStackTrace();
}
if(placeDetails != null){
String statuss = placeDetails.status;
// check place deatils status
// Check for all possible status
if(statuss.equals("OK")){
lat = gps.getLatitude();
lang = gps.getLongitude();
double endlat = placeDetails.result.geometry.location.lat;
double endlong = placeDetails.result.geometry.location.lng;
Location locationA = new Location("point A");
locationA.setLatitude(lat);
locationA.setLongitude(lang);
Location locationB = new Location("point B");
locationB.setLatitude(endlat);
locationB.setLongitude(endlong);
double distance = locationA.distanceTo(locationB)/1000;
Double dist = distance;
Integer dist2 = dist.intValue();
//p.distance = String.valueOf(dist2);
p.distance = String.valueOf(balance);
dist3 = p.distance;
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(MainActivity.this, "Near Places",
"Sorry no place found.",
false);
}
}
///////////////////////////////////////////////////////////////
if (balance > 0){
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
map.put(KEY_DISTANCE, p.distance);
// adding HashMap to ArrayList
placesListItems.add(map);
}
else {
//
}
}//end for loop
What exactly are you trying to do here?
You have balance = user_hour - duration - visit; on the first line after your for loop. I cannot see where user_hour, duration or visit is declared, but I'm assuming it's outside the loop. This means it will always be the same value for each Place in nearPlaces.results. If this code is genuinely how you want it, you might as well declare it before the loop as you are pointlessly re-calculating it for every Place.
You also never do anything with balance except to print it out or set another value to it, so it's tricky to work out what you're expecting to happen.
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.
I want it to be shown every iteration (for example every 5 seconds).
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 requestLocationUpdates which will use callbacks so your app can do things between updates. A couple quick notes:
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.
Some pre-Jelly Bean devices may not observe the minTime parameter, but you can enforce your time parameter yourself as I describe in Android Location Listener call very often.
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);
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();
}
}
I have a function in my application and when user clicks button, it will display the nearest office. Functionality works in part of Sweden but does not work in the north of Sweden. I use try-catch statement and I'll catch the null pointer exception. When I shut down my network and the location, I get the error message, but in north Sweden, there is no message, the app just crashes. My code is down there. onFindOfficeClick () is a single function and independent. How can I solve this problem? I tried debug but fails to hit the error ... do not know what to do. I take all coordinates from xml file. Does anybaody have any suggestions?
private void onFindOfficeClick() {
try {
LocationManager lm = (LocationManager)getSystemService(Service.LOCATION_SERVICE);
List<String> providersName = lm.getProviders(false);
if(providersName.size()>0){
Location location = lm.getLastKnownLocation(providersName.get(0));
float results [] = new float [1];
final double longitude = location.getLongitude();
final double latitude = location.getLatitude();
final int officeCount = mOfficesInfo.length;
double minDistance = 0;
int officeNum = 0;
for(int i=0; i<officeCount; i++){
Location.distanceBetween(latitude, longitude,
mOfficesInfo[i].getLatitude(), mOfficesInfo[i].getLongitude(), results);
if(i==0){
minDistance = results[0];
} else if(results[0]<minDistance){
minDistance=results[0];
officeNum = i;
}
}
int countryPosition = mCountries.indexOf(mOfficesInfo[officeNum].getCountry());
mCountrySpiner.setSelection(countryPosition);
mFindedOfficeName = mOfficesInfo[officeNum].getOfficeName();
mOfficesSpiner.setSelection(officeNum);
}
}
catch (NullPointerException e)
{
Toast.makeText(getApplicationContext(),"check your network and GP:s connections",Toast.LENGTH_SHORT).show();
}
}
put a null check before calling
LocationManager lm = (LocationManager)getSystemService(Service.LOCATION_SERVICE);
if(lm!=null){
lm.getProviders(false);.
}
and also might be
Location location = lm.getLastKnownLocation(providersName.get(0));
giving you null in the location variable so just do modify your code and put null check before getting latitude and laongitude from location.
if(location!=null){
final double longitude = location.getLongitude();
final double latitude = location.getLatitude();
}
becuase it is not good practice to catch NullPointerException in you code.
My Problem is I have 4 Location's Latitude and Longitude into my local database, I am fetching those data and use for draw route path in android but problem is first to second location route is not display on mapview other second to third and third to fourth route path is display on mapview. Sorry for bad English communication.
i am getting code from following link for draw route path.
MapRoute Example
and call drawing class using following function:-
public void drawpath(){
mDb.open();
Cursor cr = mDb.getAllTitles();
cr.moveToFirst();
if (cr.getCount() > 0) {
for (int i = 0; i <= cr.getCount()/2; i++) {
fromlat = Double.parseDouble(cr.getString(1));
fromlng = Double.parseDouble(cr.getString(2));
cr.moveToNext();
tolat = Double.parseDouble(cr.getString(1));
tolng = Double.parseDouble(cr.getString(2));
String url = RoadProvider
.getUrl(fromlat, fromlng, tolat, tolng);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
}
cr.close();
mDb.close();
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
It is happening because you are using cr.getCount()/2.
When you will have even number of count then it will work not work fine
For example if you have 4 number of rows then you cr.getCount()/2 = 2
so your loop will continue from 0 to 2 means 3 times.
Actually it should be continue 2 times as your coding.
Now lat take a odd numbers say 5 so cr.getCount()/2 = 2 because i is the integer value so your loop will work total 3 times.
So you have different mechanism.
Like try to add all the lat and long in the arraylist and then after loop complete.
Make a loop of the size of that arrayList and create a path.May be for that you required two additional variable to store the previous lat and long.