current location not display accurately by google location API

When I am running this code it gives current location after I clicked the button_currentlocation. But when I checked the accuracy it is very low accuracy (sometime 5000m). But I need to get current location for one time with high accuracy (around 10m). If someone can help me to correct my coding,it will be great help for my research.

My cordings are as follow

in my manifest

 uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"

LocationProvider Class

public class LocationProvider implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

public abstract interface LocationCallback {
    public void handleNewLocation(Location location);
}

public static final String TAG = LocationProvider.class.getSimpleName();

/*
 * Define a request code to send to Google Play services
 * This code is returned in Activity.onActivityResult
 */
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

public LocationProvider(Context context, LocationCallback callback) {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationCallback = callback;

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

    mContext = context;
}

public void connect() {
    mGoogleApiClient.connect();
}

public void disconnect() {
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");

    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    else {
        mLocationCallback.handleNewLocation(location);
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution() && mContext instanceof Activity) {
        try {
            Activity activity = (Activity)mContext;
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        /*
         * Thrown if Google Play services canceled the original
         * PendingIntent
         */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
        /*
         * If no resolution is available, display a dialog to the
         * user with the error.
         */
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

@Override
public void onLocationChanged(Location location) {
    mLocationCallback.handleNewLocation(location);
}
}

In HomePage Class

package com.ksfr.finaltest01;


import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.maps.model.LatLng;

public class HomePage extends Activity implements  AdapterView.OnItemSelectedListener,LocationProvider.LocationCallback {

public static final String TAG = HomePage.class.getSimpleName();

Button button_disFinder;
private LocationProvider locationProvider;
String Provider,Str_endLocation;
double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_page);

    locationProvider = new LocationProvider(this,this);

    Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.school_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });


}

  public void CurrentLocationClicked(View view) {
    if (cur_latitude!=0&&cur_longitude != 0 ){
        Spinner spinner = (Spinner) findViewById(R.id.spinner_schools);
        spinner.setClickable(true);
        String message= String.format("Current Location\n" + "Latitude  :" + cur_latitude + "\nLongitude :" + cur_longitude+"\nAccuracy :"+cur_accuracy+"\nProvider :"+Provider);
        Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
    }
    else{
        String message= String.format("Location services disconnected.\nSwich ON Location Service to work App.");
        Toast.makeText(HomePage.this, message, Toast.LENGTH_LONG).show();
        //System.exit(0);

    }
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if(position!= 0) {
        Str_endLocation=String.valueOf(parent.getItemAtPosition(position));
        Toast.makeText(getApplicationContext(), Str_endLocation + " Selected", Toast.LENGTH_SHORT).show();
        switch (Str_endLocation){
                //end location latitude and logitude will be taken from here.
                case "Kahagolla National School":
                end_latitude = 6.816703;end_longitude = 80.9637076;
                break;
        }

        String message3= String.format("End Location\n"+"Latitude  :"+end_latitude+"\nLongitude :"+end_longitude);//For Testing
        Toast.makeText(HomePage.this, message3, Toast.LENGTH_LONG).show();//For Testing
    }
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
}

  public void FindDistanceClicked (View view){
    Location curlocation = new Location("");
    curlocation.setLatitude(cur_latitude);
    curlocation.setLongitude(cur_longitude);

    Location endlocation = new Location("");
    endlocation.setLatitude(end_latitude);
    endlocation.setLongitude(end_longitude);
    distance_cur_to_end = curlocation.distanceTo(endlocation)/1000;

    String message5= String.format("Distance from current location to\n" + Str_endLocation + "  :" + String.format("%.3g%n", distance_cur_to_end)+"km");//For testing
    Toast.makeText(HomePage.this, message5, Toast.LENGTH_LONG).show();//For testing

}


public void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());

    cur_latitude = location.getLatitude();
    cur_longitude = location.getLongitude();
    cur_accuracy = location.getAccuracy();
    Provider = location.getProvider();


    LatLng cur_latLng = new LatLng(cur_latitude, cur_longitude);

}

@Override
protected void onResume() {
    super.onResume();
    locationProvider.connect();
}

@Override
protected void onPause() {
    super.onPause();
    locationProvider.disconnect();
}

public  void ClearClicked (View view){

}

}

Answers


Try reversing your onConnected method location code. First try to get current location and if that is not available then try getting lastKnown location. Some thing like this

if(location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if(locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if(location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

I corrected my issue finally, From this method i got locations in 3m accuracy,which I want.

Here's code DistanceFinderActivity.java

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5*1000; // in Milliseconds

protected LocationManager locationManager;


double cur_latitude, cur_longitude,cur_accuracy, end_latitude, end_longitude;
float distance_cur_to_end;
public LatLng cur_latLng,end_latLng;
MyLocationListener myLocationListener =new MyLocationListener();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_distance_finder);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(
            GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            myLocationListener
    );
//......
}

protected void showCurrentLocation() {

    Location location = locationManager.getLastKnownLocation(GPS_PROVIDER);
    if (location != null) {
        cur_latitude = location.getLatitude();
        cur_longitude = location.getLongitude();
        cur_accuracy = location.getAccuracy();
        Provider = location.getProvider();
        DecimalFormat df = new DecimalFormat("#.###");
        df.setMinimumFractionDigits(2);
        String message = String.format(
                "Current Location \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
                        " Provider: %4$s\nWait until new location capture",
                cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)),Provider.toUpperCase()
        );
        Toast.makeText(MainDistanceFinderActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        cur_latitude = location.getLatitude();
        cur_longitude = location.getLongitude();
        cur_accuracy = location.getAccuracy();
        Provider = location.getProvider();
        DecimalFormat df = new DecimalFormat("#.###");
        df.setMinimumFractionDigits(2);
        String message = String.format(
                "New Location Captured. \nLatitude: %1$s\nLongitude: %2$s\nAccuracy: %3$s\n" +
                        " Provider: %4$s",
                cur_latitude, cur_longitude,String.valueOf(df.format(cur_accuracy)), Provider.toUpperCase()
        );
        Toast.makeText(MainDistanceFinderActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainDistanceFinderActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainDistanceFinderActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainDistanceFinderActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

Need Your Help

Php Session don't see Servername and ServerAlias

php apache session alias server-name

I am working on a Intranet using Wordpress and setup in Apache (httpd-vhosts.conf) in order to access to the Intranet as intranet or intranet.domain.lcl like this :

Uploading PDF to database by using PHP form

php mysql forms pdf ms-word

I am trying to upload pdf or word files with PHP to mysql database. my code works with images that i specified but it doesn't work with pdf and word files.