Android Studio - GoogleAPIClient deprecated fix - java

I am building a GPS app, but GoogleAPIClient is deprecated and I'm not sure how to fix it. Also when I run the app, I get a sign-in button that doesn't lead to anything, which may be related to this since I know that GoogleSignInClient exists. Also, if you could link me to a more detailed explanation of GoogleApi I would really appreciate it!
public static final String MA = "MainActivity";
private final static int REQUEST_CODE = 100;
private GoogleApiClient gac;
private Location location;
private TextView locationTV;
private TextView distanceTV;
private TextView addressET;
private TextView timeLeftTV;
private String destinationAddress = "";
private TravelManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationTV = (TextView) findViewById(R.id.location_tv);
manager = new TravelManager();
addressET = (EditText) findViewById(R.id.destination_et);
distanceTV = (TextView) findViewById(R.id.distance_tv);
timeLeftTV = (TextView) findViewById(R.id.time_left_tv);
gac = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}
public void updateTrip(View v) {
String address = addressET.getText().toString();
boolean goodGeoCoding = true;
if (!address.equals(destinationAddress)) {
destinationAddress = address;
Geocoder geocoder = new Geocoder(this);
try {
List<Address> addresses = geocoder.getFromLocationName(destinationAddress, 5);
if (address != null) {
double latitude = addresses.get(0).getLatitude();
double longitude = addresses.get(0).getLongitude();
Location destinationLocation = new Location("destination");
destinationLocation.setLatitude(latitude);
destinationLocation.setLongitude(longitude);
manager.setDestination(destinationLocation);
}
} catch (IOException ioException) {
goodGeoCoding = false;
}
}
FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
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;
}
Location current = fusedLocationProviderApi.getLastLocation(gac);
if (current != null && goodGeoCoding) {
distanceTV.setText(manager.milesToDestination(current));
timeLeftTV.setText(manager.timeToDestination(current));
}
}
public void displayLocation() {
FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
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;
}
location = fusedLocationProviderApi.getLastLocation(gac);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
locationTV.setText(latitude + ", " + longitude);
Log.w(MA, "latutude = " + latitude + "; longitude = " + longitude);
}else
locationTV.setText("Error locating the device");
}
public void onConnected(Bundle hint) {
Log.w(MA, "connected");
displayLocation();
}
public void onConnectionSuspended(int cause) {
Log.w(MA, "connection suspended");
}
public void onConnectionFailed(ConnectionResult result) {
Log.w(MA, "connection failed");
if (result.hasResolution()){
try {
result.startResolutionForResult(this, REQUEST_CODE);
}catch (IntentSender.SendIntentException sendIntentException) {
Toast.makeText(this,"Google Play services problem, exiting", Toast.LENGTH_LONG).show();
finish();
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
gac.connect();
}
}
protected void onStart() {
super.onStart();
if (gac != null)
gac.connect();
}
}

Regarding your concern for reference related to Google API, this API might help you with your GPS app needs.
Location and Context APIs
The location and context APIs harness the sensors and signals of mobile devices to provide awareness of user actions and their environment, enabling delightful and engaging experiences that simplify user interactions, provide assistance, and help users to better understand themselves.
This contains a list of APIs' and Platforms that you can use depending on what you are looking for.
In your case, you may check the following:
Places API
Give your users contextual information about where they are, when they’re there. Access detailed information about 100 million places across a wide range of categories.
Geofencing
Geofencing combines awareness of the user's current location with awareness of the user's proximity to locations that may be of interest.
Fused Location Provider API
Get location data for your app based on combined signals from the device sensors using a battery-efficient API.
Places API
Before you start using the Places API, you need a project with a billing account and the Places API enabled. (Please refer to the link on how to create a project with billing account)
You need to get an API key that will authenticate you request.
For more details regarding this API, you can visit the link provided.
The following place requests are available:
Place Search returns a list of places based on a user's location or search string.
Place Details returns more detailed information about a specific place, including user reviews.
Place Photos provides access to the millions of place-related photos stored in Google's Place database.
Place Autocomplete automatically fills in the name and/or address of a place as users type.
Query Autocomplete provides a query prediction service for text-based geographic searches, returning suggested queries as users type.
Fused Location Provider API
The fused location provider is one of the location APIs in Google Play services. It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power. It also optimizes the device's use of battery power.
Support for common location scenarios:
Last known location
Includes step-by-step procedures to setup and access fused location provider
Location settings
Location updates
You can explore this reference to learn more:
https://developer.android.com/training/location

Related

Unable to detect data-matrix format with Google mobile vision API

Hey guys I have a problem with Google mobile vision API and especially with data-matrix format .
I'm able to scan almost every Barcode format but when I want to scan data-matrix, things getting harder . I can only detect one in 10, it's very embarrasing.
I followed the doc and I added followed detection formats like follow :
1D barcodes: EAN-13, EAN-8, UPC-A, UPC-E, Code-39, Code-93, Code-128, ITF, Codabar
2D barcodes: QR Code, Data Matrix, PDF-417, AZTEC
My Activity looks like this (took on : Google vision Android Github)
public class QrScanActivity extends AppCompatActivity implements BarcodeTracker.BarcodeTrackerListener {
private static final String TAG = QrScanActivity.class.getSimpleName();
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
public static final String BARCODE_OBJECT = "Barcode";
private CameraSource _cameraSource;
private CameraSourcePreview _preview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrscan);
_preview = this.findViewById(R.id.preview);
// Check for the camera permission before accessing the camera. If the
// permission is not granted yet, request permission.
int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (rc == PackageManager.PERMISSION_GRANTED) {
createCameraSource(true);
} else {
requestCameraPermission();
}
}
/**
* Handles the requesting of the camera permission. This includes
* showing a "Snackbar" message of why the permission is needed then
* sending the request.
*/
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(QrScanActivity.this, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
}
/**
* Creates and starts the camera. Note that this uses a higher resolution in comparison
* to other detection examples to enable the barcode detector to detect small barcodes
* at long distances.
* <p>
* Suppressing InlinedApi since there is a check that the minimum version is met before using
* the constant.
*/
#SuppressLint("InlinedApi")
private void createCameraSource(boolean autoFocus) {
Context context = getApplicationContext();
// A barcode detector is created to track barcodes. An associated multi-processor instance
// is set to receive the barcode detection results, track the barcodes, and maintain
// graphics for each barcode on screen. The factory is used by the multi-processor to
// create a separate tracker instance for each barcode.
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).setBarcodeFormats(Barcode.QR_CODE | Barcode.DATA_MATRIX | Barcode.AZTEC | Barcode.PDF417 | Barcode.CODE_39 |
Barcode.EAN_8 | Barcode.EAN_13 | Barcode.UPC_A | Barcode.UPC_E | Barcode.CODE_93 | Barcode.CODE_128 | Barcode.ITF | Barcode.CODABAR).build();
BarcodeTracker tracker = new BarcodeTracker(this);
barcodeDetector.setProcessor(
new FirstItemProcessor(barcodeDetector, tracker));
if (!barcodeDetector.isOperational()) {
// Note: The first time that an app using the barcode or face API is installed on a
// device, GMS will download a native libraries to the device in order to do detection.
// Usually this completes before the app is run for the first time. But if that
// download has not yet completed, then the above call will not detect any barcodes
// and/or faces.
//
// isOperational() can be used to check if the required native libraries are currently
// available. The detectors will automatically become operational once the library
// downloads complete on device.
Log.w(TAG, "Detector dependencies are not yet available.");
// Check for low storage. If there is low storage, the native library will not be
// downloaded, so detection will not become operational.
IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
if (hasLowStorage) {
Toast.makeText(this, "low storage", Toast.LENGTH_LONG).show();
Log.w(TAG, "low storage error");
}
}
// Creates and starts the camera. Note that this uses a higher resolution in comparison
// to other detection examples to enable the barcode detector to detect small barcodes
// at long distances.
CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
//.setRequestedPreviewSize(getWindow().getDecorView().getHeight(), getWindow().getDecorView().getWidth())
.setRequestedFps(30.0f);
builder = builder.setAutoFocusEnabled(autoFocus);
_cameraSource = builder.build();
}
/**
* Restarts the camera.
*/
#Override
protected void onResume() {
super.onResume();
startCameraSource();
((TracksApplication) getApplication()).set_currentClass(getClass().getSimpleName());
}
/**
* Stops the camera.
*/
#Override
protected void onPause() {
super.onPause();
if (_preview != null) {
_preview.stop();
}
}
/**
* Releases the resources associated with the camera source, the associated detectors, and the
* rest of the processing pipeline.
*/
#Override
protected void onDestroy() {
super.onDestroy();
if (_preview != null) {
_preview.release();
}
}
/**
* Callback for the result from requesting permissions. This method
* is invoked for every call on {#link #requestPermissions(String[], int)}.
* <p>
* <strong>Note:</strong> It is possible that the permissions request interaction
* with the user is interrupted. In this case you will receive empty permissions
* and results arrays which should be treated as a cancellation.
* </p>
*
* #param requestCode The request code passed in {#link #requestPermissions(String[], int)}.
* #param permissions The requested permissions. Never null.
* #param grantResults The grant results for the corresponding permissions
* which is either {#link PackageManager#PERMISSION_GRANTED}
* or {#link PackageManager#PERMISSION_DENIED}. Never null.
* #see #requestPermissions(String[], int)
*/
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != RC_HANDLE_CAMERA_PERM) {
Log.d(TAG, "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Camera permission granted - initialize the camera source");
// we have permission, so create the camerasourc
createCameraSource(true);
return;
}
Log.e(TAG, "Permission not granted: results len = " + grantResults.length +
" Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));
}
/**
* Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet
* (e.g., because onResume was called before the camera source was created), this will be called
* again when the camera source is created.
*/
private void startCameraSource() throws SecurityException {
if (_cameraSource != null) {
try {
_preview.start(_cameraSource);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
_cameraSource.release();
_cameraSource = null;
}
}
}
#Override
public void onBarcodeDetected(Barcode barcode) {
Intent data = new Intent();
data.putExtra(BARCODE_OBJECT, barcode);
setResult(CommonStatusCodes.SUCCESS, data);
finish();
}
}
I don't know what is wrong, if someone have an idea...
The problem is "solved" , it appears to be a problem with datamatrix that I received.
Because I tried to scan those with multiple scanner like an IOS device , or a Google play store application , everything and they are not recognized too.

What is the meaning of "status code = 7508" on Google Awareness API?

I implemented Google Awareness API on my application. All the features of Awareness api except getPlace are working. But nearby places features doesn't work. I get the status code 7508. There is no information about that specific code and it's also not handled in the official android documentation.
private void getPlace() {
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//noinspection MissingPermission
Awareness.SnapshotApi.getPlaces(mGoogleApiClient)
.setResultCallback(new ResultCallback<PlacesResult>() {
#Override
public void onResult(#NonNull final PlacesResult placesResult) {
if (!placesResult.getStatus().isSuccess()) {
Toast.makeText(getContext(), "Could not get places.", Toast.LENGTH_LONG).show();
return;
}
List<PlaceLikelihood> placeLikelihoodList = placesResult.getPlaceLikelihoods();
//do smth..
}
});
}

getLastKnownLocation first time return null issue

I'm developing a simple android location app but I have a little bit trauble.(Also sorry for my bad english.)
I want to get current location with button click, but getLastKnownLocation returns null all of first time.
But also if I first opened google maps and show my current location on map, after that I passed background it then I opened my own app, click the button that works. But I dont want this way, I just want provide location on the my app not with this way.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Object clipboardService = getSystemService(CLIPBOARD_SERVICE);
final ClipboardManager clipboardManager = (ClipboardManager) clipboardService;
tvEnlem = (TextView) findViewById(R.id.textViewEnlem);
tvBoylam = (TextView) findViewById(R.id.textViewBoylam);
retrieveLocationButton = (Button) findViewById(R.id.buttonNeredeyim);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
// 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;
}
retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
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(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
// 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;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
this.tvBoylam.setText(String.valueOf(location.getLongitude()));
this.tvEnlem.setText(String.valueOf(location.getLatitude()));
}
else{
Toast.makeText(MainActivity.this,"LOKASYON BİLGİLERİ BOŞ",
Toast.LENGTH_SHORT).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
How can I get location without null values?
this isn't a bug but simply the Google politics.
The getLastKnowLocation() method return the last location that google service has retrieved.
As Google Documentation says:
The location object may be null in the following situations:
Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because
disabling location also clears the cache.
The device never recorded its location, which could be the case of a new device or a device that has been restored to factory
settings.
Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested
location after the services restarted.
This is why if you switch from Google Maps to your app, you can get last location.
To get actual position without pass from an app to other, you need to implement a new client and request location updates yourself. For more information, see Receiving Location Updates.
I hope I have clarified your every doubt. Otherwise, do not hesitate to write :)

Why my app doesn't show location button when I accept the permission request dialog the second time is runned?

I am programming an Android App in Java. The activity holds a Google map and what I want is to have a button location at the top, like is shown in the picture:
I want that when I click the location to point to my current Location and for that I am using the class FusedLocationProviderClient.
When I run the program everything goes fine until i follow these steps sequencially:
1- Run app first time and I deny permissions
2- Run app second time. It request again permissions so I answer ok, but the button doesn't appear.
3- I close the app, and because I said yes last time, to the location permission, the button is on the map and is working.
Here is my code:
private void checkPermissions(int fineLocationPermission) {
if (fineLocationPermission != PackageManager.PERMISSION_GRANTED) { //If we don't have any permissions yet
// TODO: Consider calling
//We have to request permissions and in case the user refuse the permission we show an explanation of why he needs the permission
//The following method returns true in case the user reject the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_CODE);
} else
mLocationPermissionGranted=true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//If the user accepts the dialog box then we get the last location and show button
mLocationPermissionGranted=true;
} else {
mLocationPermissionGranted=false;
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
}
}
public void onLocationChanged(final Location location) {
String msg = "Updated location: " +
Double.toString(location.getLatitude()) + ", " +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//Show button to locate current position
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdateFactory.newLatLngZoom(latLng,12);
//mMap.setMaxZoomPreference(12);
return false;
}
});
// Add a marker our current position
LatLng CurrentPosition = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(CurrentPosition).title("Here you are!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(CurrentPosition));
}
#Override
public void onMapReady(GoogleMap googleMap) {
//Create the map
mMap = googleMap;
//Set the type of the map: HYBRID, NORMAL, SATELLITE or TERRAIN. In our case TERRAIN type
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
//Set the zoom
mMap.setMaxZoomPreference(12);
//Set the markers
MarkerOptions markerOptions= new MarkerOptions();
//Checking permissions with the permissions we have included in the manifiest
checkPermissions(permissionCheckFineLocation);
if (mLocationPermissionGranted) {
try {
mMap.setMyLocationEnabled(true);
//Last location task
Task<Location> locationResult = mFusedLocationClient.getLastLocation();
locationResult.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
//Got last known location. In some rare situations this can be null
if (location != null) {
//Logic to handle location object
onLocationChanged(location);
}
}
});
} catch (SecurityException e) {
Log.e("error", e.getMessage());
}
}
}
I know is a weird question, but I don't know how to express myself.
Any help would be great!
Thank you in advance!
onMapReady isn't called (again) after permission is granted (this happens after onMapReady).
Move the code in onMapReady in the if (mLocationPermissionGranted) clause to a separate method and call it from inside the if as well as from onRequestPermissionsResult if permission was granted.

ERROR: java.lang.IllegalArgumentException: invalid listener: null [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I use Database of Firebase to saved values of latitude and longitude, the problem is that send me this error:
Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
I tried with used a class for methods of onLocationChanged but send the same error.
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Context Android
setContentView(R.layout.activity_);
Firebase.setAndroidContext(this);
//This class is to connect with firebase
Firebase referencia = new Firebase(Path.URL_FIREBASE);
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
LocationClass ll = new LocationClass();
ll.setLatitud(lat);
ll.setLongitud(lon);
Firebase NuevaReferencia = referencia.child("Location").push();
NuevaReferencia.setValue(ll);
locationManager = (LocationManager) getSystemService(android.content.Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationListener);
NuevaReferencia.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
LocationClass LL = dataSnapshot.getValue(LocationClass.class);
String string = "Longitude:"+LL.getLongituded()+"Latitude"+LL.getLatituded();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
From what I can understand, your location object used at lat = String.valueOf(location.getLatitude()); and lon = String.valueOf(location.getLongitude()); seems to be null.
For a better analysis, I ask you to edit your question with the code for this whole class.

Categories

Resources