how to save Location Info in Firebase - java

I am trying to save location (so latitide and longitude) as one of the keys/fields in Firebase. In their example SFVehicles, they do show how to query once the information is stored but my problem is how do i save in the first place.
In their blog post, GeoFire goes Mobile, they are showing how the data would look like - but how do I get that location field populated?
I am able to save other types of strings to the Firebase though. I just use the code below.
Question is What data type should the location field be?
Firebase ref = new Firebase("https://myfirebaselink.firebaseio.com/");
//User
alan = new User("Alan Turing", 1912);
alanRef.setValue(obj);
I tried location to be a List<String>, but that did not work -- the location field looked like below:
Edit: On more research, found this blog post by Google but they are also saving as keys latitude1 and longitude. This probably was written before GeoFire` was introduced.

The GeoFire for Java project has a great README, that covers (amongst other) setting location data:
In GeoFire you can set and query locations by string keys. To set a location for a key simply call the setLocation() method. The method is passed a key as a string and the location as a GeoLocation object containing the location's latitude and longitude:
geoFire.setLocation("firebase-hq", new GeoLocation(37.7853889, -122.4056973));
To check if a write was successfully saved on the server, you can add a GeoFire.CompletionListener to the setLocation() call:
geoFire.setLocation("firebase-hq", new GeoLocation(37.7853889, -122.4056973), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, FirebaseError error) {
if (error != null) {
System.err.println("There was an error saving the location to GeoFire: " + error);
} else {
System.out.println("Location saved on server successfully!");
}
}
});
To remove a location and delete it from the database simply pass the location's key to removeLocation:
geoFire.removeLocation("firebase-hq");

It looks from here
That the type of the object is GeoLocation , like in line 83.

Related

How to add pagination in data retreived from FIREBASE STORAGE in android?

I'm trying to add pagination in images data that I'm retrieving from firebase using Firebase Storage. I have 10 images there and I want to display 2 at a time in RecyclerView and when the user scrolls down to end vertically, it loads the next 2 until all the images are displayed, I have also read some documentation of Firebase where it was mentioned to use storage.list(int max results) method but with that, it only shows the number of results that I pass in the method for instance if I pass 2 it shows 2 images only, and I can't load anymore. I've found one method too on the official documentation i.e below: https://firebase.google.com/docs/storage/android/list-files
public void listAllPaginated(#Nullable String pageToken) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference listRef = storage.getReference().child("files/uid");
// Fetch the next page of results, using the pageToken if we have one.
Task<ListResult> listPageTask = pageToken != null
? listRef.list(100, pageToken)
: listRef.list(100);
listPageTask
.addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult listResult) {
List<StorageReference> prefixes = listResult.getPrefixes();
List<StorageReference> items = listResult.getItems();
// Process page of results
// ...
// Recurse onto next page
if (listResult.getPageToken() != null) {
listAllPaginated(listResult.getPageToken());
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Uh-oh, an error occurred.
}
});
}
I'm confused about how to use it, I don't know where I can get a page token from in order to provide a reference to open the next page
The thing is I have 200 images in my Firebase Storage and I directly want to apply pagination to the URLs that I'm retrieving from Firebase Storage.
To achieve that, you have two options. The first one would be to use StorageReference#listAll() method which:
List all items (files) and prefixes (folders) under this StorageReference.
And according to the official documentation regarding how to list files with Cloud Storage on Android, please note that:
Cloud Storage for Firebase allows you to list the contents of your Cloud Storage bucket. The SDKs return both the items and the prefixes of objects under the current Cloud Storage reference:
So you have to explicitly differentiate that (items vs. prefixes) in your application code and provide your own pagination algorithm.
The second option that you have, and the simplest one, in my opinion, would be to store the image URLs in the Firestore and implement the pagination as explained here:
Paginate data with query cursors

Android - Firebase realtime database reference pointing to invalid url [duplicate]

This question already has answers here:
Firebase Database points to wrong database URL
(3 answers)
Closed 1 year ago.
Android Java.
When trying to reference my Realtime Database I'm using this to get the reference:
FirebaseDatabase rootDatabase;
DatabaseReference rootReference;
rootDatabase = FirebaseDatabase.getInstance();
Log.i("rootDatabase", String.valueOf(rootDatabase));
rootReference = rootDatabase.getReference("users");
Log.i("rootReference", String.valueOf(rootReference));
The URL shown in the console is different from that associated with my firebase project:
Output in the console
I/rootDatabase: com.google.firebase.database.FirebaseDatabase#<ProjectID>
I/rootReference: https://<Project-Name>-default-rtdb.firebaseio.com/users
When I open the URL from the console I get a page saying "not found".
But the URL that is shown above the database in the firebase console and in the google-services.json under firebase_url is:
https://<Project-Name>-default-rtdb.europe-west1.firebasedatabase.app/
Is there any way that I can either change the location of the Firebase database to no be in the Europe-west region or change some way to get the reference to the new server region? Many thanks.
When you are using the following line of code:
Log.i("rootDatabase", String.valueOf(rootDatabase));
You are passing to the valueOf() method the rootDatabase object, which is of type FirebaseDatabase. So you are only printing the String representation of the object, which is actually a memory address. However, when you are using this line:
Log.i("rootReference", String.valueOf(rootReference));
You are passing a different object to the valueOf() method. This time the object is of type DatabaseReference. Now the String representation of the object is actually a URL that points to your project.
Is there any way that I can either change the location of the firebase database to no be in the Europe-west region
Once you set the location, this cannot be changed. If you need another location, you need to create another project, set the location to be in another region than the Europe-west region, download the JSON file again and you'll be good to go.

Can Google's Places API findCurrentPlace method be used to get the exact current address, rather than the address of the closest 'Place'?

I am currently using the Google Places API within my (Java) Android application to get the current device location and display it into an editText. Currently when I make the call to placesClient.findCurrentPlace(request), a list of the closest places and the likelihood of the device being there are returned, like so:
Place 'XXXXXXX' has likelihood: 0.600000
Place 'YYYYYYY' has likelihood: 0.0500000
Place 'ZZZZZZZ' has likelihood: 0.00000
Where the places are things like "Thames River" or "Telus Stadium". I can then get the address from each of these from the response. My question is, is there any way to get back the address of the phones current location, opposed to the address of the closest 'Place'?
I have done something similar with the Places Autocomplete so that it suggests addresses rather than places, which works very well. Getting the current place is done in a slightly different way though, and therefore I can't seem to make the same change.
The reason that I am attempting to do this using the Places API is because I have a start and end location AutoCompleteEditText which the user can type into. They can choose to have their current location shown in the Start Location AutoCompleteEditText, and I was hoping to show the address in the same format as it would be in if they had typed in the address and clicked it using the Places AutoComplete.
Here is the code currently being used to get the address of the closest place, which I would like to modify to get the address the phone is currently at.
List<Place.Field> placeFields = Collections.singletonList(Place.Field.ADDRESS);
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);
...
Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
placeResponse.addOnCompleteListener(new OnCompleteListener<FindCurrentPlaceResponse>() {
#Override
public void onComplete(#NonNull Task<FindCurrentPlaceResponse> task) {
if (task.isSuccessful()) {
FindCurrentPlaceResponse response = task.getResult();
for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
Log.i(LOG_TAG, String.format("Place '%s' has likelihood: %f",
placeLikelihood.getPlace().getAddress(),
placeLikelihood.getLikelihood()));
}
} else {
Log.e(LOG_TAG, "Error finding current location");
}
}
});
Forget having to use the Google Places API for this - It's simple to do without having to interact with any API.
Simply get the current location using a FusedLocationProviderClient to return the last known latitude and longitude of the device (as seen here), and then use an instance of Geocoder to get addresses from that latitude and longitude using the getFromLocation method. This can then easily be converted into a string which matches what the Google Places API would have returned (as seen here).

Download user from Firebase, Messenger app

I'm trying to write messenger app using Firebase.
In database I have a few entries, which are User.class objects. I'm trying to write function which can download User object from database. I though that it'd be better to build separate class (UserManager) for this task, because I don't like making mess in code. But there is a problem, because in onCreate method I need to use User object to download some additional info from database to create conversation list, so downloading user from server should be done before that. Also if user is not in database, it should create and push User to database using FirebaseAuth (I've got that working).
Should I build class extending AsynchTask, and there put downloading user, and then updating UI with the data downloaded after user ?
How do I know if the user was already downloaded. Probably I should build some listener but I don't know how to do that.
Additional question:
If I use this reference with value listener, do i get a user object or some value from inside of the object?
DatabaseReference userReference = FirebaseDatabase.getInstance().getReference().child("users/" + mUserID);
Here is my database:
Each entry key is userID from FirebaseAuth for easier implementation.
I've been cracking my head on this for a few days and tried different approaches. I'll apriciate any help. I think, that some code or a scheme would be a huge help.
How do I know if the user was already downloaded?
You can add a flag to each user with the value of false and once you have downloaded the user object, to set the value to true but this is not how things are working with Firebase. You cannot know when a user from the database is completed downloaded becase Firebase is a realtime database and getting data might never complete. That's why is named a realtime database because in any momemnt the data under that User object can be changed, properties can be added or deleted.
You can use a CompletionListener only when you write or update data and you'll be notified when the operation has been acknowledged by the Database servers but you cannot use this interface when reading data.
If I use this reference with value listener, do i get a user object or some value from inside of the object?
If the value that you are listening to is a User object, then you'll get a User object. If the value is another type of object, which can also be a String (which is also an object) then you'll get that type of object, which can also be a String object. Remember, that only the keys in a Firebase database are always strings.
Maybe this part of my code will help you figure out:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users")
.child(mUserID);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "DatabaseError: " + databaseError.getMessage());
}
});

Android: Why does a new instance of Location require a provider?

I have a lot of geo data stored online with latitude and longitude and I'd like to use the distanceTo method instead of my own haversine formula.
So I need to put each record into a Location field, but here's my question: it requires a "provider" string. Why? What will Android do with that information?
for (ArrayList<String> item : Places_Data) {
Location itemloc = new Location("provider");
itemloc.setLatitude(latIn);
itemloc.setLongitude(lonIn);
//do something with my new location
}
From the source code for Location, it doesn't use the string to do anything meaningful. It just uses it to describe the Location internally. If you do Location#toString(), it prints out the co-ordinates, the provider and other details (accuracy, etc). That's all it's used for, internal description.
You can make the provider anything, as seen in this answer: Creating Android Location Object
Use correctly the way
package android.location.LocationManager
Location location = new Location(LocationManager.GPS_PROVIDER);
Use NETWORK_PROVIDER o GPS_PROVIDER
https://developer.android.com/reference/android/location/LocationManager.html#GPS_PROVIDER
https://developer.android.com/reference/android/location/LocationManager.html#NETWORK_PROVIDER

Categories

Resources