The app crashed after sending location to server Android Java - java

I am able to send the location (String address) + messages to my server; however, my app crashed after sending data to server. I used Volley library to make a POST request. Can someone help me fix this issue?
First I get the location and the list of the address.
public class MainActivity extends AppCompatActivity {
//Declare LocationManager and LocationListener
LocationManager locationManager;
LocationListener locationListener;
String address = "Unable to get the address!";
EditText Message;
AlertDialog.Builder builder;
String server_url ="https://schoolserver-tand089.c9users.io/Report.php";
//Process when users give the permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Start the location service
startListening();
}
}
//Checking permission granted method
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
//Update location method. 1 variable location
public void updatedLocationInfo(Location location) {
Log.i ("Location", location.toString());
//Cast the textViews
TextView latTextView = (TextView) findViewById(R.id.txtLat);
TextView lonTextView = (TextView) findViewById(R.id.txtLong);
TextView altTextView = (TextView) findViewById(R.id.txtAltitude);
TextView accTextView = (TextView) findViewById(R.id.txtAccuracy);
//get the string from location
latTextView.setText("Latitude: " + location.getLatitude());
lonTextView.setText("Longitude: " + location.getLongitude());
altTextView.setText("Altitude: " + location.getAltitude());
accTextView.setText("Accuracy: " + location.getAccuracy());
//Create Geocoder object to Get the address
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
//Using try/catch to prevent the app from crashing when failing to get Addresses
try {
//Declare the error string
//String address = "Unable to get the address!";
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
//Check if the address is valid
if (listAddresses != null && listAddresses.size() > 0) {
//Set address to empty string again when we know it is working
address = "Address: \n";
// Log.i("Address", listAddresses.get(0).toString());
//check for every item in the list Addresses is valid
if (listAddresses.get(0).getSubThoroughfare() != null) {
address += listAddresses.get(0).getSubThoroughfare() + " ";
}
//Street name
if (listAddresses.get(0).getThoroughfare() != null) {
address += listAddresses.get(0).getThoroughfare() + "\n";
}
//City name
if (listAddresses.get(0).getLocality() != null) {
address += listAddresses.get(0).getLocality() + "\n";
}
//Zip code
if (listAddresses.get(0).getPostalCode() != null) {
address += listAddresses.get(0).getPostalCode() + "\n";
}
//Country name
if (listAddresses.get(0).getCountryName() != null) {
address += listAddresses.get(0).getCountryName() + "\n";
}
TextView addressTextView = (TextView) findViewById(R.id.txtAddress);
//set the address into the text View
addressTextView.setText(address);
//Log.i("Address", address.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up locationManager and locationListener above and cast them into their type
//Using built-in location service
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
//Get the location when it changes
#Override
public void onLocationChanged(Location location) {
//call the updated location above
updatedLocationInfo(location);
}
//
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Check for the version of SDK
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
// above 23 we need to check for permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//ask for permission. Number 1 is just a request queue.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
//we have permission
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//Get the last location from the built-in GPS
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//In case location does not have lastknownlocation, we call the updatedLocation method above
if (location != null) {
updatedLocationInfo(location);
}
}
}
}
Next, I used the onClick method to send the Address and a message to server when user clicks the button.
// using onClick
public void bntTap (View bnt) {
Message = (EditText) findViewById(R.id.message);
//Hide virtual keyboard after click the button
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
final String message;
message = Message.getText().toString();
if (message.equals("")) {
builder.setTitle("Unable to report");
//Creating a AlertDialog to display errors
AlertDialog alertDialog = builder.create();
alertDialog.setMessage("Please Enter All Required Fields*");
alertDialog.show();
} else {
//Post request
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//get response form server to check if it is successfully submitted
builder.setTitle("Server Response");
builder.setMessage("Congratulation" + " " + response);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Message.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error!!!", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//send data to mySQL server
//the keys must be same as field names in mySQL server
// get the list of the address
params.put("LOCATION", address);
params.put("MESSAGES", message);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addTorequestqueue(stringRequest);
//Log.i("Address", address.toString());
}
}
All the data successfully sent to the server, but the app crashed.
Updated: logcat when crashing
logcat when crashing

You are getting an NPE, as you forgot to define builder. You have only declared it in your code as
AlertDialog.Builder builder;
Please define the builder as
builder = new AlertDialog.Builder(MainActivity.this);
in your onCreate().

Related

getSpeed() always 0

It's a location tracking application.
I test it in home, so location doesn't change. To do that I change them manually by incrementing the latitude and longitude by 2 everytime. I see the location change in my phone everytime, but the speed is still always 0! I don't know if it's working because I haven't tried this method before. If someone did I would appreciate the help.
public class MainActivity extends AppCompatActivity {
private Button b;
private TextView t;
private LocationManager locationManager;
private LocationListener listener;
private static int a=2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.textView);
b = (Button) findViewById(R.id.button);
t.setText(""); t.setTextSize(16);
b.setText("Demarer");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//to change location manually
location.setLatitude(location.getLatitude()+a);
location.setLongitude(location.getLongitude()+a);
a=a+10;
System.out.println("\n\nlocation changed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
//
Long id = new Long(1);
String rs = null;
String json = null;
//post
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
PostLocation pl = new PostLocation();
json = pl.bowlingJson(location.getLongitude(), location.getLatitude(),id);
//System.out.println(json);
rs = pl.post("http://192.168.1.50:8080/api/v1/locations", json);
}catch (IOException EX){ EX.printStackTrace();
}finally {
if (rs == null)
t.setText("\nID : " +id+"\nLongitude : "+ location.getLongitude() + "\nLatitude : " + location.getLatitude() +"\nVitesse : "+(location.getSpeed()*3600/1000)+"km/h\n\nnon envoyée" );
//t.setText(location.getLatitude()+" : "+location.getLongitude()+"\n"+oldLocation.getLatitude()+" : "+oldLocation.getLongitude());
else
{
t.setText("\nID : " +id+"\nLongitude : "+ location.getLongitude() + "\nLatitude : " + location.getLatitude() +"\nVitesse : "+(location.getSpeed()*3600/1000)+"km/h\n\nbien envoyée" );
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) { }
#Override
public void onProviderEnabled(String s) { }
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button(){
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
return;
}
// va pas executer si n y a pas de privilege un return existe avant
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
//noinspection MissingPermission
try{
locationManager.requestLocationUpdates(locationProvider, 1000, 0, listener);
}catch (SecurityException e){
}
}
});
}
}

How to track friends location?

I am new in this field and I am trying to make application to track my friends like "snap-map". I am able to get my real-time location but I don't know what should I add to get real-time location of people who are using same application.
Here is my Java code, it will really helpful for me if you guys give me a code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private FirebaseAuth mAuth;
final static int PERMISSION_ALL = 1;
final static String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
private GoogleMap mMap;
MarkerOptions mo;
Marker marker;
private Location user;
LocationManager locationManager;
private HashMap<Float, Location> otherUser = new HashMap<Float, Location>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mAuth = FirebaseAuth.getInstance();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
if (Build.VERSION.SDK_INT >= 27 && !isPermissionGranted()) {
requestPermissions(PERMISSIONS, PERMISSION_ALL);
} else requestLocation();
if (!isLocationEnabled())
showAlert(1);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
marker = mMap.addMarker(mo);
}
//Called when the location has changed.
#Override
public void onLocationChanged(Location location) {
LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
marker.setPosition(myCoordinates);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));
}
//Called when the provider status changes.
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
//Called when the provider is enabled by the user.
#Override
public void onProviderEnabled(String provider) {
}
//Called when the provider is disabled by the user. If requestLocationUpdates
#Override
public void onProviderDisabled(String provider) {
}
private void requestLocation() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
String provider = locationManager.getBestProvider(criteria, true);
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;
}
locationManager.requestLocationUpdates(provider, 10000, 10, this);
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isPermissionGranted() {
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.v("mylog","Permission is granted");
return true;
}else{
Log.v("mylog","Permission not granted");
return false;
}
}
private void showAlert(final int status) {
String message, title, btnText;
if (status == 1) {
message = "Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app";
title = "Enable Location";
btnText = "Location Settings";
} else {
message = "Please allow this app to access location!";
title = "Permission access";
btnText = "Grant";
}
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(false);
dialog.setTitle(title)
.setMessage(message)
.setPositiveButton(btnText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
if (status == 1) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
} else
requestPermissions(PERMISSIONS, PERMISSION_ALL);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}

To replace a place by coordinates

I try of creating an app that shows me distance and duration travel from my current location and another point, I work with the below code, and I need to replace the origin by my current location and destination by any point but in coordinates.
How I can modify this code, for to log rate the functions described
This is my ActivityMain
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
btnFindPath = (Button) findViewById(R.id.btnFindPath);
etOrigin = (EditText) findViewById(R.id.etOrigin);
etDestination = (EditText) findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
}
private void sendRequest() {
String origin = etOrigin.getText().toString();
String destination = etDestination.getText().toString();
if (origin.isEmpty()) {
Toast.makeText(this, "Please enter origin address!", Toast.LENGTH_SHORT).show();
return;
}
if (destination.isEmpty()) {
Toast.makeText(this, "Please enter destination address!", Toast.LENGTH_SHORT).show();
return;
}
try {
new DirectionFinder(this, origin, destination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng hcmus = new LatLng(10.762963, 106.682394);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("Đại học Khoa học tự nhiên")
.position(hcmus)));
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;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(this, "Please wait.",
"Finding direction..!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
You can get current location by using fused location
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.getResult();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
for further detail check the link below
https://developers.google.com/maps/documentation/android-api/current-place-tutorial

extract current location only works in my phone

The code works in my phone properly but doesn't works sometime. Also, this code doesn't work in other phone properly. I have tried many times. And while sending this app's apk file through xender the installation fails. Please help to improve my code so that it works properly in all phone when location is turned ON.
Mainactivity.java
public class MainActivity extends AppCompatActivity {
TextView result;
Double latitude, longitude;
Geocoder geocoder;
List<Address> addressList;
Getgps gps;
Context mContext;
protected LocationManager locationManager;
boolean isGPSEnabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.abcd);
geocoder = new Geocoder(this, Locale.getDefault());
mContext = this;
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled)
{
getlonglat(); //check location
if(CheckInternetConnection(MainActivity.this)) {
getaddress();
// getlocation
if(result.getText().toString().matches(""))
{
Toast.makeText(mContext, "Poor Internet Connection", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet Connection",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"Turn ON Your Location",Toast.LENGTH_LONG).show();
showgpsSettingsAlert();
startActivity(new Intent(MainActivity.this, Main2Activity.class));
Toast.makeText(mContext, " after delay khatey", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void getlonglat() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else {
Toast.makeText(mContext, "GPS Permission Granted", Toast.LENGTH_SHORT).show();
gps = new Getgps(mContext, MainActivity.this);
// Check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
}
}
public void getaddress() {
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
String address = addressList.get(0).getAddressLine(0);
String area = addressList.get(0).getLocality();
String city = addressList.get(0).getAdminArea();
String country = addressList.get(0).getCountryName();
String postalcode = addressList.get(0).getPostalCode();
String fullAddress = address + ", " + area + ", " + city + ", " + country + ", " + postalcode;
Toast.makeText(mContext, "Internet Permission Granted", Toast.LENGTH_SHORT).show();
result.setText(fullAddress);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static boolean CheckInternetConnection(Context context) {
ConnectivityManager connectivity =
(ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showgpsSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
this.setFinishOnTouchOutside(false);
alertDialog.setTitle("GPS Setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(mContext, "Sorry we cannot proceed", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();// Showing Alert Message
}
}
Getgps.java
package com.example.bibash28.locationfinal2;
/**
* Created by Bibash28 on 11/3/2017.
*/
public class Getgps extends Service
{
private Context mContext; // Flag for GPS status
boolean isGPSEnabled = false; // Flag for network status
boolean canGetLocation = false;
Location location; // Location
Double latitude,longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000;// The minimum distance to change Updates in meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;// 10 meters// The minimum time between updates in milliseconds// 1 minute
Activity activity;
protected LocationManager locationManager;
public Getgps(Context context, Activity activity)
{
this.mContext = context;
this.activity = activity;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
this.canGetLocation = true;
if (isGPSEnabled) {
if (location == null) {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Function to get latitude
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
// Function to get longitude
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
//Function to check GPS/Wi-Fi enabled #return boolean
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}

Reading and writing data in Firebase Database

Note:- Sorry for my bad English because English is not my native language i have used google translator for this.
I am working on an android Map app in which a user can find their friends' current location and for storing the current location I am using FireBase realtime database. So when a user clicks on the find button, their friends' current location will be on the Map with their user name.
But I am unable to solve one problem when I am trying to fetch the user data from firebase. It is not reflecting in the correct way. The data is reflecting in 2 different lines in the log:
line 1:- Latitude & Longitude is 0.0 but email is showing and in
line 2:- Latitude & Longitude is reflecting correctly but Email is null
I don't know how to get both in one line. I have searched a lot on google but failed. Kindly help me understand how it can be done in the correct way.
Below is my code and android studio screen shot.
MainActivity.java
findfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, MapsActivity.class));
}
});
final TextView tname;
tname = (TextView) findViewById(R.id.textview);
ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://ffinder-b4617.firebaseio.com/Email");
mReferece2 = ref.child("email");
mReferece2 = ref.child("location");
proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
UserInformation details = dataSnapshot1.getValue(UserInformation.class);
String email = details.email;
Double lat = details.latitude;
Double lon = details.longitude;
tname.setText(lat+" "+'\n'+lon+'\n'+email);
System.out.println("-->"+ lat+" " + lon+" "+ email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
MapsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Firebase.setAndroidContext(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
} else {
Log.d("onCreate", "Google Play Services available.");
}
auth = FirebaseAuth.getInstance();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseDatabase.getInstance().getReference().child("Location");
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date();
mLastUpdateTime = ((dateFormat.format(date).toString()));
saveToFirebase();
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
}
public void saveToFirebase() {
Firebase firebase = new Firebase("https://ffinder-b4617.firebaseio.com").child("Email").child("location");
Map mLoactions = new HashMap();
mLoactions.put("timestamp",mLastUpdateTime);
mLoactions.put("latitude", mLastLocation.getLatitude());
mLoactions.put("longitude", mLastLocation.getLongitude());
firebase.setValue(mLoactions);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public boolean onMarkerClick(Marker marker) {
marker.setDraggable(true);
return false;
}
#Override
public void onMarkerDragStart(Marker marker) {}
#Override
public void onMarkerDrag(Marker marker) {}
#Override
public void onMarkerDragEnd(Marker marker) {
end_latitude = marker.getPosition().latitude;
end_longitude = marker.getPosition().longitude;
Log.d("end_lat",""+end_latitude);
Log.d("end_lng",""+end_longitude);
}
}
Login.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Firebase.setAndroidContext(this);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
public void userLoginInfo(){
String email = inputEmail.getText().toString();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Email").push();
String userId = mDatabase.child("email").getKey();
mDatabase.child(userId).setValue(email);
}
}
UserInformation.class
public class UserInformation {
public String email;
public double latitude;
public double longitude;
public UserInformation() {
}
public UserInformation(String email, double latitude, double longitude) {
this.email = email;
this.latitude = latitude;
this.longitude = longitude;
}
public String getEmail() {
return email;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
Firebase Database screenshot
Android Studio log screenshot
Your userLoginInfo() method uses push() to create a unique key within the database to store the email address, and your saveToFirebase() method stores the latitude/longitude values differently, which means the data ends up in different places.
It would be beneficial to make use of your UserInformation object to standardise your database and use DatabaseReference#setValue(Object)
and DataSnapshot#getValue(Class<CT>) to store and retrieve the data. So when you want to store a user's location you do:
public void saveToFirebase() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Email").push();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
UserInformation userInformation = new UserInformation(email, mLastLocation.getLatitude(), mLastLocation.getLongitude());
ref.setValue(userInformation);
}
Then, to retrieve these details later, you can use your existing ValueEventListener with a couple of adjustments:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Email");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()){
UserInformation details = child.getValue(UserInformation.class);
System.out.println("-->" + details.getLatitude() +" " + details.getLongitude() +" "+ details.getEmail());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
I hope I've understood your requirements correctly, please let me know if I've missed anything.

Categories