I'm doing a Udacity Android Basics course and am trying to change my app to use a Loader rather than AsyncTask. My app uses a locationListener to generate a custom URL that is then passed to the loader, loader calls ChargePointLoader class which initates the HTTP request and returns a list of chargePoints, which should populate the adapter once loaded.
However nothing appears on my screen. Do I have the order of my loader wrong or is the locationListener interfering with the loader? Thanks for any help
Here is a link to the old Async Project: https://github.com/Kovah101/ChargeMyCarBareBones/blob/master/app/src/main/java/com/example/android/chargemycar/MainActivity.java
Here is my Main activity
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<ChargePoint>> {
public static final String LOG_TAG = MainActivity.class.getName();
public static double myLat;
public static double myLong;
private static String ChargePoint_REQUEST_URL = "http://chargepoints.dft.gov.uk/api/retrieve/registry/postcode/SW15+5QS/dist/7/format/json/limit/10";
private ChargePointAdapter adapter;
private LocationManager locationManager;
private LocationListener locationListener;
private static final int CHARGEPOINT_LOADER_ID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find a reference to the {#link ListView} in the layout
final ListView chargePointListView = (ListView) findViewById(R.id.list);
// Create a ChargingPointAdapter, whose data source is a list of ChargePoints, which creates listview items for each item
adapter = new ChargePointAdapter(this, new ArrayList<ChargePoint>());
//possible error with order of loaders or inside listener
final LoaderManager loaderManager = getLoaderManager();
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//set lat & long variables
myLat = location.getLatitude();
myLong = location.getLongitude();
String myLatString = Double.toString(myLat);
String myLongString = Double.toString(myLong);
//test with toast
Context context = getApplicationContext();
CharSequence text = " my latitude=" +myLatString +"\nmy longitude=" +myLongString ;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//create request URL using live location
ChargePoint_REQUEST_URL = "http://chargepoints.dft.gov.uk/api/retrieve/registry/lat/" +myLat + "/long/" +myLong +"/dist/10/format/json/limit/10";
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
chargePointListView.setAdapter(adapter);
loaderManager.initLoader(CHARGEPOINT_LOADER_ID, null, MainActivity.this );
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 100, locationListener);
//time in milliseconds
//distance in meters
}
// On click take to maps
chargePointListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String myLatString = Double.toString(myLat);
String myLongString = Double.toString(myLong);
ChargePoint currentChargePoint = (ChargePoint) chargePointListView.getItemAtPosition(position);
double destinationLatitude = currentChargePoint.getLatitude();
double destinationLongitude = currentChargePoint.getLongitude();
String destLatString = Double.toString(destinationLatitude);
String destLongString = Double.toString(destinationLongitude);
//create uri for map intent
String url = "http://maps.google.com/maps?saddr="+myLatString+","+myLongString+"&daddr="+destLatString+","+destLongString+"&travelmode=driving";
Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url));
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 25, locationListener);
//time in ms, distance in meters
}
}
}
#Override
public Loader<List<ChargePoint>> onCreateLoader(int i, Bundle bundle) {
return new ChargePointLoader(this, ChargePoint_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<ChargePoint>> loader, List<ChargePoint> chargePoints) {
// Clear the adapter of previous data
adapter.clear();
//check for null charge point list, return early if that is the case, if there is a valid list then add to the adapter
if (chargePoints != null && !chargePoints.isEmpty()){
adapter.addAll(chargePoints);
}
}
#Override
public void onLoaderReset(Loader<List<ChargePoint>> loader) {
// TODO: Loader reset, so we can clear out our existing data.
adapter.clear();
}
}
Loaders are now deprecated, use Android Architecture Components (LiveData and ViewModel) with your old AsyncTask. It works more efficiently, faster and cleaner than Loaders. It also makes your AsyncTask to be lifecycle aware. Lifecycle aware in a sense that your network request will not be made again after once no matter how many times you call onCreate() because it automatically caches downloaded data. Configuration changes won't affect your app. For more information on using AsyncTask with LiveData and ViewModel, visit https://medium.com/androiddevelopers/lifecycle-aware-data-loading-with-android-architecture-components-f95484159de4
Related
I am trying to build a weather app.I have an API link which I am taking as String variable whose scope is global and I have another method by which I obtain longitude and latitude. I want to save these latitude and longitude values in my variable whose scope is global. While I am inside my geocoder method where I am taking out latitude and longitude values (my global variable API link changes and gives me the desired result because I am concatenating longtiude and latitude with my variable whose scope is global. But once I go out of this method and try using my API link in a different method (I loose the values latitude and longitude I had obtained and concatenated in geocoder method hoping that it would permanently change my global variable value.
Here is the code. (I have 4-5 files but I am pasting only main activity code where I am actually working) If I hardcode the latitude and longitude values I am getting the desired results but I am just trying to get better at this by obtaining latitude and longitude.
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Model>> {
public static final int WEATHERLOADER = 1;
RecyclerView recyclerView;
WeatherAdapter mAdapter;
List<Model> modelList;
FusedLocationProviderClient fusedLocation;
String latitude;
String longit;
Button getweather;
String APILINK = "http://api.openweathermap.org/data/2.5/weather?lat=";
String APIKEY = "&appid=5c161192e5aa828fc6a8896eddaf89e2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getweather = findViewById(R.id.getWeather);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
modelList = new ArrayList<>();
mAdapter = new WeatherAdapter(this, modelList);
recyclerView.setAdapter(mAdapter);
ConnectivityManager conn = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (conn!=null) {
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
if (networkInfo!=null){
LoaderManager loaderManager = getSupportLoaderManager();
loaderManager.initLoader(WEATHERLOADER, null, this);
}
}
fusedLocation = LocationServices.getFusedLocationProviderClient(this);
getweather.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {
wantLocation();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
}
}
});
}
private void wantLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocation.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if (location != null) {
try {
Geocoder geocoder = new Geocoder(
MainActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
/*cityname.setText(Html.fromHtml("<font color='#6200EE'><b>City Name:</b><br></font>" + addresses.get(0).getAdminArea()));
longtitude.setText(Html.fromHtml("<font color='#6200EE'><b>Longtitude:</b><br></font>" + addresses.get(0).getLongitude()));
lattitude.setText(Html.fromHtml("<font color='#6200EE'><b>Lattitude:</b><br></font>" + addresses.get(0).getLatitude()));
countryname.setText(Html.fromHtml("<font color='#6200EE'><b>Country Name:</b><br></font>" + addresses.get(0).getCountryName()));
*/
APILINK = APILINK + addresses.get(0).getLatitude() + "&lon=" + addresses.get(0).getLongitude() + APIKEY;
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
#NonNull
#Override
public Loader<List<Model>> onCreateLoader(int i, #Nullable Bundle bundle) {
Toast.makeText(MainActivity.this, String.valueOf(APILINK), Toast.LENGTH_SHORT).show();
return new WeatherLoader(this, APILINK);
}
#Override
public void onLoadFinished(#NonNull Loader<List<Model>> loader, List<Model> modelList) {
if (modelList!=null && !modelList.isEmpty()) {
mAdapter = new WeatherAdapter(this, modelList);
recyclerView.setAdapter(mAdapter);
}
}
#Override
public void onLoaderReset(#NonNull Loader<List<Model>> loader) {
}
}
I'm not sure I understand the question/situation entirely, but from the code provided it looks like APILINK should be correctly modified in the onComplete method. If you are trying to access APILINK from a different class, you could create a "getter" method, which when called, returns APILINK:
public String getAPILINK() {
return APILINK;
}
By setting a String equal to getAPILINK(), you can make a copy of APILINK in different classes or methods.
Edit 1:
To concatenate Strings, you simply use the + operator as you did. This likely means the problem lies elsewhere. To troubleshoot, try adding
System.out.println(APILINK);
to various points in the program, like before calling onComplete and after.
If "&lon=" and APIKEY were appended, but not the latitude and longitude, then the problem is retrieving those values.
I am using googleAPIClient to get the current lat long values using Location. I am getting the values of both my current lat and long in a separate class. I need to pass these current lat and long values inside my MapsActivity ( GoogleMap Activity), Since I have already created the object for the another class, from which I need to get the values, I don't know how to pass the values to this activity from the class.
Here's what I have tried. This is the class which I have created to get the current lat long values:
CurrentValues.java:
public class CurrentValues implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = CurrentValues.class.getSimpleName();
private Context context;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public CurrentValues( Context context){
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(context, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
private boolean checkLocation() {
if(!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private boolean isLocationEnabled() {
mLocationManager = (LocationManager)context. getSystemService(Context.LOCATION_SERVICE);
return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, (com.google.android.gms.location.LocationListener) context);
Log.d("reque", "--->>>>");
}
}
Now I need to pass the lat long values I got from this class to MapsActivity. Since I had already created object for the currentvalues class here in this activity, I don't know how to pass the value from there to here.
Here's my MapActivity (GoogleMap Activity)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private CurrentValues currentValues;
private Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// // Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//
// LatLng chennai = new LatLng(13.06,80);
// mMap.addMarker(new MarkerOptions().position(chennai).title("Marker in Chennai"));
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 8f));
// creating object for currentValues class
CurrentValues currentValues = new CurrentValues(this);
}
}
I don't know how to proceed after this to pass the lat long values here. How can I proceed?
I have an activity which uses onLocationChanged method and upon performing a parse query it makes a toast. It works fine. However, when I go to another activity (it's a maps activity), if I change the coordinates (I'm using an emulator) the toast pops up. I would like to know why the onLocationChanged method is still running. I thought it may be due to context, but I specified the activity in the context field.
locationManager = (LocationManager) DriverChoicesActivity.this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
final ParseGeoPoint parseGeoPoint = new ParseGeoPoint(location.getLatitude(), location.getLongitude());
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null && objects.size() > 0) {
for (ParseObject object : objects) {
object.put("driverLocation", parseGeoPoint);
object.saveInBackground();
Toast.makeText(DriverChoicesActivity.this, "User found", Toast.LENGTH_SHORT).show();
}
}
}
});
updateRequestList(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
All that is within onCreate of the original activity (DriverChoicesActivity.class). The other activity (DriverMapActivity.class) has no code in it apart from getting the intent from this activity to collect some latitude and longitude points. Here is the code which makes the intent (also within onCreate)
requestListView.setAdapter(arrayAdapter);
requestListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (requestLatitude.size() > position && requestLongitude.size() > position) {
if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(DriverChoicesActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location getLastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (getLastKnownLocation != null) {
Intent intent = new Intent(getApplicationContext(), DriverMapActivity.class);
intent.putExtra("requestLatitude", requestLatitude.get(position));
intent.putExtra("requestLongitude", requestLongitude.get(position));
intent.putExtra("driverLatitude", getLastKnownLocation.getLatitude());
intent.putExtra("driverLongitude", getLastKnownLocation.getLongitude());
startActivity(intent);
}
}
}
}
});
I assume my problem is with context somehow. If someone could be kind enough to explain.
Thank you
You must add:
locationManager.removeUpdates(listener);
Before move to next Activity.
and
LocationManager locationManager;
LocationListener locationListener;
on the top, under class declaraction
I have an activity in which I have a text view where I want to display the distance between the user's current location and a specific address. I have the Latitude and Logitude of the address but my issue is getting the user's location. My target is when the activity is created that's when I want to get his location' without pressing any button. I have tried multiple ways: getLastKnownLocation, onLocation changed etc, but the value returned is always null.
It's important to note that I am running the app on an emulator.
Sample code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_list);
Bundle bundleUser = getIntent().getExtras();
final String owneruser = bundleUser.getString("username");
Bundle bundleType = getIntent().getExtras();
String type = bundleType.getString("type");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final TextView t = (TextView) findViewById(R.id.textView2);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
t.append("\n " + location.getLongitude() + " " + location.getLatitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
final Location userLocation = new Location("");
userLocation.setLatitude(latitude);
userLocation.setLongitude(longitude);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
update();
break;
default:
break;
}
}
void update(){
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
}
else {
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
}
implement your activity to LocationListener :
public class MyActivity extends AppCompatActivity implements LocationListener {
private Location userLocation = new Location("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
#Override
public void onLocationChanged(Location location) {
if(location != null){
userLocation.setLatitude(location.getLatitude());
userLocation.setLongitude(location.getLongitude());
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
TRY this to grant permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block this thread waiting for the user's response! After the user sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
}
}
and add this in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
As I am trying to fetch latitude and longitude of my current location on google maps, its not returning any value neither it is enabling my button to get the current location.
I am pretty new in android .
public class ChatFragment extends Fragment{
// Google Map
private GoogleMap googleMap;
GPSTracker gpsTracker = new GPSTracker(getContext());
protected String latitude,longitude;
public ChatFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View chatfrag = inflater.inflate(R.layout.chatfragment, container, false);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
return chatfrag;
}
/**
* function to load map. If map is not created it will create it for you
*/
private void initilizeMap()
{
if (googleMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
googleMap = mapFrag.getMap();
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
Location getLastLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
double currentlong = getLastLocation.getLatitude();
double currentlat = getLastLocation.getLongitude();
System.out.print(currentlat);
System.out.print(currentlong);
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getActivity(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public void onResume() {
super.onResume();
// initilizeMap();
}
}
Any kind of help would be appreciated.
If you want to get current location from google map then try this,
googleMap.setMyLocationEnabled(true);
double currentlong = googleMap.getMyLocation().getLatitude();
double currentlat = googleMap.getMyLocation().getLongitude();
// if you want to get location update then implement this
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location loc) {
// get current location update
}
});
I hope it is useful to you.