Real time location tracking delays on updates - android

I am creating an app for real time gps tracking for a group of users. I managed to display every user location with a marker on the map (map activity - using Google Maps), and also to update the location on the map every 5 seconds (I update the 'longitude' and 'latitude' fields of the user in Firebase Database every 3 seconds, and then read this fields every 5 seconds and update all the markers on the map).
I tried walking around with 3 different phones, and noticed that not all the markers (its not always the same markers, but if some marker is stuck on one phone, the same marker is stuck on the other phones) are moving with me as I walk. They start moving in the beginning for a small amount of time and then they stop moving at all. After I keep walking for a while they suddenly update (jump to the current location) and then stuck again... Or in other words the updates of some of the markers happens with big delays.
What could be the reason for such delays and how can I fix it?
Pictures of my Firebase Database (Managers and Users):
Pictures of my Firebase Database - Managers
Pictures of my Firebase Database - Users
(I create a manager which represents a group, and the manager have a list of users that are in his group, and then I go through the list of users of the manager and update their location on Firebase Database. Then when a user click on 'map' button it goes through to GroupMapActivity and there I read the locations from Firebase Databse every 5 seconds and update the markers).
The code for updating the location on Firebase Database using service:
package com.example.lidor.findmygroup;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class FindMeService extends IntentService
{
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
String userEmail = "", key = "";
LocationTrack locationTrack;
double longitude, latitude;
User user;
public FindMeService()
{
super("FindMeService");
}
#Override
protected void onHandleIntent(Intent intent)
{
firebaseDatabase = FirebaseDatabase.getInstance();
if (intent.hasExtra("email"))
userEmail = intent.getStringExtra("email").toString();
databaseReference = firebaseDatabase.getReference("USERS");
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
User curUser = d.getValue(User.class);
if (userEmail.equals(curUser.Email))
{
key = d.getKey();
user = curUser;
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
while (true)
{
try
{
Thread.sleep(3000);
locationTrack = new LocationTrack(FindMeService.this);
if (locationTrack.canGetLocation())
{
longitude = locationTrack.getLongitude();
latitude = locationTrack.getLatitude();
databaseReference.child("USERS").child(key).
addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> updates = new HashMap<>();
for (DataSnapshot s : dataSnapshot.getChildren())
{
updates.put(s.getKey(), s.getValue());
}
updates.put("UserName", user.UserName);
updates.put("Age", user.Age);
updates.put("Phone", user.Phone);
updates.put("City", user.City);
updates.put("Email", user.Email);
updates.put("longitude", longitude);
updates.put("latitude", latitude);
updates.put("Is_In_Group", user.Is_In_Group);
updates.put("ManagerEmail", user.ManagerEmail);
updates.put("Is_Manager", user.Is_Manager);
updates.put("Is_Connected", user.Is_Connected);
databaseReference.child(key).updateChildren(updates);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else
{
locationTrack.showSettingsAlert();
Toast.makeText(FindMeService.this, "No GPS signal",
Toast.LENGTH_LONG).show();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
#Override
public void onDestroy()
{
super.onDestroy();
}
}
The Group Map Activity:
package com.example.lidor.findmygroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class GroupMapActivity extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
Handler handler;
String email = "", managerEmail = "", managerKey = "";
int i = 0;
Marker marker;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase, firebaseDatabase1, firebaseDatabase2;
DatabaseReference databaseReference, databaseReference1, databaseReference2;
Boolean endFor = false, endFor1 = false, endFor2 = false;
ProgressDialog progressDialog;
HashMap<String, Marker> markers;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabase1 = FirebaseDatabase.getInstance();
firebaseDatabase2 = FirebaseDatabase.getInstance();
//builder = new LatLngBounds.Builder();
Intent intent = getIntent();
if (intent.hasExtra("email")) email = intent.getStringExtra("email").toString();
markers = new HashMap<>();
progressDialog = new ProgressDialog(GroupMapActivity.this);
progressDialog.setMessage("Map Loading Please Wait...");
progressDialog.show();
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
Real_Time_Group_Map();
progressDialog.dismiss();
handler.postDelayed(this, 1000);
}
}, 1000);
}
public void Real_Time_Group_Map()
{
// 1# -------------------------------------------------------------------------------------
databaseReference = firebaseDatabase.getReference("USERS");
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (endFor) continue;
User curUser = d.getValue(User.class);
if (email.equals(curUser.Email))
{
endFor = true;
managerEmail = curUser.ManagerEmail;
databaseReference = firebaseDatabase.getReference("MANAGERS");
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (endFor1) continue;
Manager curManager = d.getValue(Manager.class);
if (managerEmail.equals(curManager.Email))
{
endFor1 = true;
managerKey = d.getKey();
databaseReference1 = firebaseDatabase1.getReference("MANAGERS").
child(managerKey).child("Group Users");
databaseReference1.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
final String curFriend = d.getValue().toString();
databaseReference2 = firebaseDatabase2.getReference("USERS");
databaseReference2.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
User curUser = d.getValue(User.class);
String emailUser = curUser.Email;
if (curFriend.equals(emailUser))
{
LatLng location = new LatLng(
curUser.latitude, curUser.longitude);
Marker delMarker = markers.get(emailUser);
if (delMarker != null) delMarker.remove();
markers.remove(emailUser);
if (curUser.Is_Manager)
{
marker = mMap.addMarker(new MarkerOptions()
.position(location).title(curUser.UserName).icon(
BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_BLUE)).
snippet(emailUser));
}
else
{
marker = mMap.addMarker(new MarkerOptions()
.position(location).title(curUser.UserName)
.snippet(emailUser));
}
markers.put(emailUser, marker);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location,18));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(Marker marker)
{
Intent intent = new Intent(GroupMapActivity.this, MemberActivity.class);
intent.putExtra("email", marker.getSnippet());
startActivity(intent);
return false;
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

Related

Fetching location data using volley and creating multiple markers in Google maps

This is my first time working with google maps in android.I was able to create a map showing my current user location.
However, I would like to display multiple markers whose data I'm fetching using volley. To do this I'm using a backgroundTask class with a singleton class. The backgroundTask class is the one returning the arrayList of the location data.
For this reason I need to populate my BackgroungTask class with the arrayList before my MapActivity become active and access the arraylist of objects in onCreate but it seems the MapActivity loads very fast and a reference to the arrayList of objects from the BackgroungTask class is always null.
This is the BackgroundTask class which is fetching the data
package com.example.carwashplaces;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class BackgroundTask {
private Context context;
private ArrayList<ModelLocation> locationArrayList = new ArrayList<>();
String json_url = "http://histogenetic-exhaus.000webhostapp.com/location.php";
public BackgroundTask(Context context) {
this.context = context;
}
public ArrayList<ModelLocation> getLocationArrayList(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest (
Request.Method.POST,
json_url,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count<response.length()){
try {
JSONObject jsonObject = response.getJSONObject(count);
ModelLocation modelLocation = new ModelLocation(
jsonObject.getString("id"),
jsonObject.getString("name"),
jsonObject.getString("latitude"),
jsonObject.getString("longitude"),
jsonObject.getString("staff"),
jsonObject.getString("comment"),
jsonObject.getString("phone"));
locationArrayList.add(modelLocation);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error fetching car wash places... ", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestque(jsonArrayRequest);
return locationArrayList;
}
}
This is the MapActivity where I want to display the locations.
package com.example.carwashplaces;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.FetchPlaceResponse;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.mancj.materialsearchbar.adapter.SuggestionsAdapter;
import com.skyfishjy.library.RippleBackground;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlacesClient placesClient;
private List<AutocompletePrediction> predictionList;
private ArrayList<ModelLocation> locations;
private BackgroundTask backgroundTask;
private Location mLastKnownLocation;
private LocationCallback locationCallback;
private MaterialSearchBar materialSearchBar;
private View mapView;
private Button btnFind;
private RippleBackground rippleBg;
private final float DEFAULT_ZOOM = 18;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//init views
materialSearchBar = findViewById(R.id.searchBar);
btnFind = findViewById(R.id.btnFind);
rippleBg = findViewById(R.id.ripple_bg);
//an object of backgroung task
backgroundTask = new BackgroundTask(MapActivity.this);
locations = new ArrayList<>();
//getting location data from background task
locations = backgroundTask.getLocationArrayList();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
Places.initialize(MapActivity.this, "MY_KEY");
placesClient = Places.createClient(this);
final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString(), true, null, true);
}
#Override
public void onButtonClicked(int buttonCode) {
if (buttonCode == MaterialSearchBar.BUTTON_NAVIGATION){
//opening or closing a navigation drawer
}else if (buttonCode == MaterialSearchBar.BUTTON_BACK){
materialSearchBar.disableSearch();
}
}
});
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
FindAutocompletePredictionsRequest predictionsRequest = FindAutocompletePredictionsRequest.builder()
.setCountry("ke")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(s.toString())
.build();
placesClient.findAutocompletePredictions(predictionsRequest).addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() {
#Override
public void onComplete(#NonNull Task<FindAutocompletePredictionsResponse> task) {
if (task.isSuccessful()){
//predictions found, find out what suggestions we have from google
FindAutocompletePredictionsResponse predictionsResponse = task.getResult();
if (predictionsResponse != null){
predictionList = predictionsResponse.getAutocompletePredictions();
//converting predictionList into a list of string
List<String> suggestionsList = new ArrayList<>();
for (int i = 0; i < predictionList.size(); i++){
AutocompletePrediction prediction = predictionList.get(i);
suggestionsList.add(prediction.getFullText(null).toString());
}
//pass suggestion list to our MaterialSearchBar
materialSearchBar.updateLastSuggestions(suggestionsList);
if (!materialSearchBar.isSuggestionsVisible()){
materialSearchBar.showSuggestionsList();
}
}
}
else {
//some error
Log.i("mytag", "prediction fetching task failed");
}
}
});
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setSuggstionsClickListener(new SuggestionsAdapter.OnItemViewClickListener() {
#Override
public void OnItemClickListener(int position, View v) {
// seek the longitude and latitude of that suggestion
if (position >= predictionList.size()){
return;
}
AutocompletePrediction selectedPrediction = predictionList.get(position);
String suggestion = materialSearchBar.getLastSuggestions().get(position).toString();
materialSearchBar.setText(suggestion);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
materialSearchBar.clearSuggestions();
}
},1000);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (imm != null){
imm.hideSoftInputFromWindow(materialSearchBar.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
String placeId = selectedPrediction.getPlaceId();
List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG);// get latitude and longitude of a place
FetchPlaceRequest fetchPlaceRequest = FetchPlaceRequest.builder(placeId, placeFields).build();
placesClient.fetchPlace(fetchPlaceRequest).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
#Override
public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
// place found, update camera Factory
Place place = fetchPlaceResponse.getPlace();
Log.i("mytag", "place found: "+place.getName());
LatLng latLngOfPlace = place.getLatLng();
if (latLngOfPlace != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngOfPlace, DEFAULT_ZOOM));
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException){
ApiException apiException = (ApiException) e;
apiException.printStackTrace();
int statusCode = apiException.getStatusCode();
Log.i("mytag", "place not found: " +e.getMessage());
Log.i("mytag", "status code: "+statusCode);
}
}
});
}
#Override
public void OnItemDeleteListener(int position, View v) {
}
});
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get the current location of the marker
LatLng currentMarkerLocation = mMap.getCameraPosition().target;
rippleBg.startRippleAnimation();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
rippleBg.stopRippleAnimation();
Toast.makeText(MapActivity.this, "Nearest Car Wash", Toast.LENGTH_SHORT).show();
}
},3000);
}
});
}
//Called when the map is loaded
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null){
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 40, 180);
}
//check if gps is enabled or not and then request user to enable it
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MapActivity.this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(MapActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
getDeviceLocation();
setMarkersToCarWashes();
}
});
task.addOnFailureListener(MapActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException){
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(MapActivity.this, 51);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}
}
}
});
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (materialSearchBar.isSuggestionsVisible())
materialSearchBar.clearSuggestions();
if (materialSearchBar.isSearchEnabled())
materialSearchBar.disableSearch();
return false;
}
});
setMarkersToCarWashes();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 51) {
if (resultCode == RESULT_OK) {
getDeviceLocation();
setMarkersToCarWashes();
}
}
}
private void setMarkersToCarWashes() {
if (locations != null){
for(int i = 0; i < locations.size(); i++){
double lati = Double.parseDouble(locations.get(i).getLatitude());
double longLat = Double.parseDouble(locations.get(i).getLongitude());
//set markers to car wash places
mMap.addMarker(new MarkerOptions().position(
new LatLng(lati, longLat))
.title(locations.get(i).getName())
.snippet(locations.get(i).getComment()));
}
}
}
private void getDeviceLocation() {
mFusedLocationProviderClient.getLastLocation()
.addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()){
mLastKnownLocation = task.getResult();
if (mLastKnownLocation != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
}else {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult == null){
return;
}
mLastKnownLocation = locationResult.getLastLocation();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
};
mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
}else {
Toast.makeText(MapActivity.this, "Unable to get last Location", Toast.LENGTH_SHORT).show();
}
}
});
}
}
And This is the part of the code in MapActivity where I'm trying to get the arraylist from the BackgroundTask class
//an object of backgroung task
backgroundTask = new BackgroundTask(MapActivity.this);
locations = new ArrayList<>();
//getting location data from background task
locations = backgroundTask.getLocationArrayList();
How do I display the markers in onMapReady method i.e populate the BackgroundTask before the onMapReady method executes?
This is my approach, based off of this solution from related thread. First let's create an interface to handle the volley's response.
public interface LocationsCallback {
void onSuccess(ArrayList<ModelLocation> fetchedLocations);
}
Then modify your getLocationArrayList method as follows:
public ArrayList<ModelLocation> getLocationArrayList(final LocationsCallback locationsCallback)
Inside the onResponse method of getLocationArrayList, right at the end, add the callback:
public ArrayList<ModelLocation> getLocationArrayList(final LocationsCallback locationsCallback) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.POST,
json_url,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// your code here...
// Add this at the end here
ArrayList<ModelLocation> locations = locationArrayList;
locationsCallback.onSuccess(locations);
}
//...
Now assign your MapActivity's locations to the fetched array:
locations = new ArrayList<>();
backgroundTask = new BackgroundTask(MapActivity.this);
backgroundTask.getLocationArrayList(new LocationsCallback() {
#Override
public void onSuccess(ArrayList<ModelLocation> fetchedLocations) {
locations = fetchedLocations;
// Your other code goes here...
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
Places.initialize(MapActivity.this, "KEY");
placesClient = Places.createClient(MapActivity.this);
//...
}
});
And the markers will now be displayed on the map. See screenshot below. :)

firebase data not shown before pressing back button in RecyclerView

I i am working with firebase realtime database.. I retrieved data and everything but my main problem is that the data is not being displayed unless i press back button.. I went through stacks everywhere it suggested to notifyDataSetChanged(); which i did before, but still no luck. As i am using GridLayout i cant use the adapter in the addListeneOnDatachange function as it shows error saying that it is not allowed to add the adapter there for my RecyclerViewAdapter.
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> listCourse;
TextView btnSignOut, UserName;
/*---- Firebase Database stuff ----*/
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
RecyclerView myrv = findViewById(R.id.recyclerviewcourse);
myrv.setLayoutManager(new GridLayoutManager(this,2));
// CourseCode();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
myRef = rootRef.child("Users");
/*------------------------------------------------------------------*/
listCourse = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse myAdapter = new RecyclerViewAdapterCourse(this,listCourse);
myAdapter.notifyDataSetChanged();
myrv.setAdapter(myAdapter);
}
}
You need to call myAdapter.notifyDataSetChanged() every time the data changes. In your case this means you need to call it at the end of the onDataChanged(DataSnapShot dataSnapShot) function.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
myAdapter.notifyDataSetChanged()
}

Don't write to all child nodes on Firebase

I have an app that asks a series of questions. These questions are stored on the firebase db. I am trying to change the child node "Status" from the click of the button. The button being pressed for testing is button "AnswerA".
To date i have managed to change all "Status" nodes to the button press but i only want to change one at a time as the questions are being asked.
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You are looping though all questions and performing the same logic on all of them. You want to select only the question you are interested in, e.g.:
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals()) { // TODO: How you chose the child from your index
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
Adding full playing activity for review,
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.hiverecord.kee01.hiverecord.Common.Common;;
import com.hiverecord.kee01.hiverecord.Model.Question;
import com.hiverecord.kee01.hiverecord.Model.QuestionList;
import com.hiverecord.kee01.hiverecord.Model.User;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 5000; //5sec
final static long TIMEOUT = 60000; //70 sec
int progressValue = 0;
CountDownTimer mCountDown;
int index=0,
thisQuestion=0,
totalQuestion,
correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA,btnB;
TextView txtQuestionNum,question_text;
FirebaseDatabase database;
DatabaseReference test;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
database = FirebaseDatabase.getInstance();
test = database.getReference("Questions"); //get the reference
//Views
txtQuestionNum = findViewById(R.id.txtTotalQuestion);
question_text = findViewById(R.id.question_text);
question_image = findViewById(R.id.question_image);
progressBar = findViewById(R.id.progressBar);
btnA = findViewById(R.id.btnAnswerA);
btnB = findViewById(R.id.btnAnswerB);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion)
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals(Common.questionList.get(index).getKey())){
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correctAnswer++;
showQuestion(++index); //next question
}
});
}
else {
Map<String, Object> userUpdates = new HashMap<>();
//userUpdates.put("AnswerA", "");
//userUpdates.put("AnswerB", "NO");
test.updateChildren(userUpdates);
//choose answer false
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
showQuestion(++index);
}
}
}
private void showQuestion(int index) {
if(index < totalQuestion)
{
thisQuestion++;
txtQuestionNum.setText(String.format("%d/%d",thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue=0;
if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
{
//if is image
Picasso.with(getBaseContext())
.load(Common.questionList.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.VISIBLE);
}
else
{
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text, we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
mCountDown.start(); //Start timer
}
else
{
//if it is a final question
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT,INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
Solution:
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//logcat and show the index
Log.i("Button A Index accessed", index + "");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get DataSnapShot of Children in ref Questions
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals("0" + index)) {
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Android Studio Log.d doesn't work in Fragment of Google Maps

I have this code, a Fragment in Navigation drawer which makes a map with google maps API and also makes marks, and the log.d doesn't show in the Logcat box of the Android Studio, if somebody can help me so that I can do tests, thanks!!!
(I wrote this code because I want to create markers of Google Maps from FireBaseDatabase).
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MapFragment extends Fragment {
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference perdidosUbiRef = rootRef.child("Perdidos").child("UbicaciĆ³n");
public MapFragment() {
}
MapView mMapView;
private GoogleMap googleMap;
ArrayList<LatLng> markerPoints;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//PON TITULO BAR
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Mapa");
View rootView = inflater.inflate(R.layout.fragment_perdidosmap, container, false);
mMapView= (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
googleMap.setMyLocationEnabled(true);
}
}
markerPoints = new ArrayList<LatLng>();
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
//PROVA BASE DADES
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Float Lat = ds.child("Lat").getValue(Float.class);
Float Long = ds.child("Long").getValue(Float.class);
Log.d("ValuesofLat", "HELLOOO");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
perdidosUbiRef.addListenerForSingleValueEvent(eventListener);
// For dropping a marker at a point on the Map
LatLng Barcelona = new LatLng(Float.parseFloat(String.valueOf(41.3818)), Float.parseFloat(String.valueOf(2.1685)));
googleMap.addMarker(new MarkerOptions().position(Barcelona).
title("Tetsuo").snippet("Es perro macarra"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(Barcelona).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition
(cameraPosition ));
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation 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.
new AlertDialog.Builder(getActivity())
.setTitle("")
.setMessage("")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
} else {
}
return;
}
}
}
}
Log.d is in this part of code:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Float Lat = ds.child("Lat").getValue(Float.class);
Float Long = ds.child("Long").getValue(Float.class);
Log.d("ValuesofLat", "HELLOOO");
}
}
My Logcat's box
image
You need to remove ValuesofLat from Search bar in your logcat and it will work fine
Just clear search bar from logcat's it will work fine
Check below image
clear search bar like below image and it will work fine

Firebase: Querying a list of data created with push()

So I have Firebase Database that looks like this:
{
"lists" : {
"-KZh-vvPcPGVqC22k2Bo" : {
"dateCreated" : "2016-12-23",
"listDescription" : "My Christmas Wish List for 2016",
"listTitle" : "William's Christmas List",
"user" : "ztGAx7eplGeZgdjqnegrtbfuyUy2"
}
},
"users" : {
"8pJJuscerZRGdwGGImnWlCKSEed2" : {
"email" : "example#example.com",
"name" : "Alyson"
},
"ztGAx7eplGeZgdjqnegrtbfuyUy2" : {
"email" : "example#example.com",
"name" : "William"
}
}
}
I am trying to only return the lists objects where the user field equals the UID of the logged in user. That way the logged in user gets all his lists. But I am having trouble querying the data that is in lists because of the unique key that is generated by push() which I use to append to lists whenever a user creates a new list object. How do I go about querying lists so that I get only the lists that match the UID of the signed in user? I have this so far
package com.fanciestw.listpro;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class allList extends AppCompatActivity {
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mList = mDatabase.getReference().child("lists");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_list);
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null) {
Log.d("User Activity", "User Signed In");
} else {
Log.d("User Activity", "User Signed Out");
signout(getCurrentFocus());
}
}
};
mList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
List newList = dataSnapshot.getValue(List.class);
Log.d("List Returned", newList.listTitle + " " + newList.listDescription);
updateList();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
updateList();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
Log.d("allList Activity", "onStart");
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
public void onStop(){
super.onStop();
Log.d("allList Activity", "onStop");
if(mAuthStateListener != null) mAuth.removeAuthStateListener(mAuthStateListener);
}
public void addNewList(View view){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add New List");
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.add_new_list_form, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogView);
// Set up the buttons
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = ((EditText)dialogView.findViewById(R.id.add_list_title)).getText().toString();
String desc = ((EditText)dialogView.findViewById(R.id.add_list_desc)).getText().toString();
Log.d("New List Details", title + ", " + desc);
//TODO::Store created list with title and desc in database
List newList = new List(title, desc, mAuth.getCurrentUser().getUid());
String newListID = mList.push().getKey();
mList.child(newListID).setValue(newList);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void updateList(){
//Want to get lists where lists.user == firebaseAuth.getCurrentUser().UID();
}
public void signout(View view){
mAuth.signOut();
Intent intent = new Intent(this, login.class);
startActivity(intent);
}
}
Declare
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private String userId = null;
Initialize
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
userId = mCurrentUser.getUid().toString();
String UIDstring = (String) dataSnapshot.child("users").getValue();
Determine
if (userId.equals(UIDstring)) {
//true
} else {
// false
}

Categories

Resources