Reading and writing data in Firebase Database - java

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.

Related

Check if is user first login on Android App using Firebase Auth and Database

I am making an chat app and I want to do the following:
When starting the MainActivity, check if the user is logged in. If not, start FirebaseAuthUI.
But FirebaseAuth only supports a few parameters and, to add more, I created a Database node do each user, which store other parameters.
To get this parameters, after finishing FirebaseAuth, the user is redirected to an Activity that get all extra information and store in the user's node in the Database. All of this is working just fine.
But after the user fill the information in this Info Activity and finish the register, it should go back to MainActivity and stay there. How can I do that?
I am trying it this way:
I added to each user a Boolean variable called userCompleted, which informs if the user have already gave their information. I check if this variable is false, and if so, I call the Info Activity intent and, in the when the user press the button to complete the registration in this Activity, it sets the userCompleted value to true in the user node in the Database and then start an intent that leads to MainActivity.
The problem is that in the Database, userCompleted is set to true and then immediately goes back to false, and I don't know why. Also, I guess I am having trouble on reading userCompleted from the Database, probably because I haven't worked much with asynchronous tasks.
I used a variable isUserCompleted declared in Main Activity to get track of the userCompleted value.
A way to check if is the first time the user is logging in would be useful too, although it wouldn't solve my whole problem.
This is my current code:
(if need more to try to understand the problem just ask in the comments)
Create AuthStateListener
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
onSignInInitialize(user);
Log.d(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
onSignInInitialize()
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.d(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.d(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.d(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
Go back to Main Activity
mFinishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mUserDatabaseReference.child("userCompleted").setValue(true);
Intent intent = new Intent (CreateVolunteerProfile.this, SearchActivity.class);
startActivity(intent);
}
});
Entire MainActivity block (Actually it's called SearchActivity)
public class SearchActivity extends AppCompatActivity implements RecyclerAdapter.UserItemClickListener {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<User> users = new ArrayList<User>();
private String mLoggedUserId = "user2";
private String mLoggedUsername;
private User mLoggedUser;
private FirebaseUser mLoggedFBUser;
//private boolean isUserCompleted;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPreferencesEditor;
private boolean firstTime = true;
private static final String TAG = "Search Activity";
private static final int USER_CLICK = 1;
private static final int RC_SIGN_IN = 1;
private static final int RC_CREATE_PROFILE = 2;
//Firebase
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mUsersDatabaseReference;
private DatabaseReference mUserReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
View loadingView = findViewById(R.id.cl_loading);
loadingView.setVisibility(View.VISIBLE);
//RecyclerView
recyclerView = findViewById(R.id.rv_users);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter(users, this);
recyclerView.setAdapter(adapter);
//Firebase
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mUsersDatabaseReference = mFirebaseDatabase.getReference().child("users");
setAuthStateListener();
loadingView.setVisibility(View.GONE);
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null)
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
detachChildEventListener();
clearAdapter();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.wtf(TAG, "onSaveInstanceState userId = "+ mLoggedUserId);
//Log.wtf(TAG, "UserCompleted (onSaveInstanceState) " + isUserCompleted);
outState.putString("userId", mLoggedUserId);
//outState.putBoolean("isUserCompleted", isUserCompleted);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mLoggedUserId = savedInstanceState.getString("userId");
//isUserCompleted = savedInstanceState.getBoolean("isUserCompleted");
//Log.wtf(TAG, "UserCompleted (onRestoreInstanceState) " + isUserCompleted);
Log.wtf(TAG, "onRestoreInstanceState userId = "+ mLoggedUserId);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if((requestCode == RC_SIGN_IN) && firstTime){
if (resultCode == RESULT_OK){
//Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED){
Toast.makeText(this, "Sign in canceled!", Toast.LENGTH_SHORT).show();
finish();
}
}
if((requestCode == RC_CREATE_PROFILE)){
if (resultCode == RESULT_OK){
//isUserCompleted = true;
}
}
}
#Override
public void onUserItemClick(int clickedUserIndex) {
Intent intent = new Intent (this, ChatActivity.class);
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if(user != null) {
mLoggedUserId = user.getUid();
intent.putExtra("user1", mLoggedUserId);
String mUserRecieverId = users.get(clickedUserIndex).getUid();
intent.putExtra("user2", mUserRecieverId);
Log.wtf(TAG, "SearchActivity // user = " + users.get(clickedUserIndex));
Log.wtf("1", "SearchActivity // mLoggedUserId = " + mLoggedUserId + " // users.getUid() = " + users.get(clickedUserIndex).getUid());
startActivityForResult(intent, USER_CLICK);
}
else {
Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
}
}
public void setAuthStateListener(){
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
mUserReference = mUsersDatabaseReference.child(user.getUid());
onSignInInitialize(user);
Log.wtf(TAG, "userUid = " + user.getUid());
Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
} else {
onSignOutCleanup();
startLoginUI();
}
}
};
}
public void onSignInInitialize(final FirebaseUser user){
mLoggedFBUser = user;
mUserReference = mUsersDatabaseReference.child(user.getUid());
mUserReference.child("uid").setValue(user.getUid());
boolean isUserCompleted = false;
mUserReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
isUserCompleted = user.isUserCompleted();
Log.wtf(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Log.wtf(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
if (!isUserCompleted) {
startCreateProfileActivity(user);
}
Log.wtf(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
mUserReference.child("username").setValue(user.getDisplayName());
mUserReference.child("email").setValue(user.getEmail());
attachChildEventListener();
}
public void onSignOutCleanup(){
mLoggedUser = null;
mLoggedUserId = null;
mLoggedUsername = null;
detachChildEventListener();
clearAdapter();
}
public void attachChildEventListener(){
if (mChildEventListener == null){
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
User user = dataSnapshot.getValue(User.class);
users.add(user);
Log.d(TAG, "onChildAdded userId = "+ user.getUid());
//adapter.notifyItemInserted(users.size()-1);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) { }
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) { }
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) { }
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
};
}
mUsersDatabaseReference.addChildEventListener(mChildEventListener);
}
public void detachChildEventListener(){
if (mChildEventListener != null){
mUsersDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
public void clearAdapter() {
final int size = users.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
users.remove(0);
}
adapter.notifyItemRangeRemoved(0, size);
}
}
public void startCreateProfileActivity(FirebaseUser user){
mUsersDatabaseReference.child(user.getUid()).child("userCompleted").setValue(false);
Intent intent = new Intent(SearchActivity.this, CreateProfileActivity.class);
intent.putExtra("userId", user.getUid());
startActivityForResult(intent, RC_CREATE_PROFILE);
}
public void startLoginUI(){
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setLogo(R.mipmap.logo)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.GoogleBuilder().build(),
//new AuthUI.IdpConfig.FacebookBuilder().build(),
//new AuthUI.IdpConfig.TwitterBuilder().build(),
//new AuthUI.IdpConfig.GitHubBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build()))
//new AuthUI.IdpConfig.PhoneBuilder().build(),
//new AuthUI.IdpConfig.AnonymousBuilder().build()))
.build(),
RC_SIGN_IN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_item:
AuthUI.getInstance().signOut(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I think the simplest way is if a user clicked on finish Btn successfully make a flag with true else make it false
in your MainActivity
firebase.auth().onAuthStateChanged(function(user) {
// User signed in and not registered
if (user&&!isPressedOnFinishBtn) {
// User is signed in.
}
user clicked on finish btn
else if(isPressedOnFinishBtn) {
// No user is signed in.
}
});
This is how you can do that .
Create a method inside your Login activity .
private void AllowUserToLogin() {
String userName = userEmail.getText().toString();
String userPass = userPassword.getText().toString();
if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) {
Toast.makeText(this, "Enter user Name / password first . . .", Toast.LENGTH_SHORT).show();
} else {
dialogBar.setTitle("Sign In ");
dialogBar.setMessage("Please Wait . . .");
dialogBar.setCanceledOnTouchOutside(true);
dialogBar.show();
mAuth.signInWithEmailAndPassword(userName, userPass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String currentUserID = mAuth.getCurrentUser().getUid();
String deviceToken = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
UsersRef.child(currentUserID).child("device_token")
.setValue(deviceToken)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserToMainActivity();
Toast.makeText(LoginPage.this, "Logged in Successfull . . . ", Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
} else {
String error = task.getException().toString();
Toast.makeText(LoginPage.this, "Wrong Email or Password: " + error, Toast.LENGTH_SHORT).show();
dialogBar.dismiss();
}
}
});
}
}
and on ur onClick() method .
#Override
public void onClick(View v) {
if (v == needNewAccount) {
sendUserToRegisterActivity();
} else if (v == loginButton) {
AllowUserToLogin();
}else if(v == phone_button){
Intent phoneLoginIntent = new Intent(LoginPage.this , PhoneLoginActivity.class);
startActivity(phoneLoginIntent);
}
}
this is sendUserToRegisterActivity()
private void sendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginPage.this, RegisterationForm.class);
startActivity(registerIntent);
}
This is sendUserToMainActivity() .
private void sendUserToMainActivity() {
Intent mainIntent = new Intent(LoginPage.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}

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();
}

I want to retrieve current logged in user data from firestore but it shows blank where I want to show my data

I am trying to get the current logged in user from the google firestore database
and i saw this same problem in stackoverflow of a user and i used that same method but showing blank in place user details.
Please help me Thanks.
I am earlier using querysnapshot as it gives all the users.
image description here
the image for database is
enter image description here
The code is:
public class UserProfile extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int GALLERY_INTENT = 2;
private static final String TAG = "UserProfile";
String UserId;
FirebaseAuth auth;
ImageButton Photo;
ImageView photoview;
TextView name, email, password, phone;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
if(getSupportActionBar()!=null ){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DatabaseReference Database = FirebaseDatabase.getInstance().getReference("users");
DatabaseReference DBRef = Database.child("users");
auth = FirebaseAuth.getInstance();
UserId = auth.getCurrentUser().getUid();
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
StorageReference mStorage = FirebaseStorage.getInstance().getReference();
FirebaseStorage storage = FirebaseStorage.getInstance();
photoview = (ImageView)findViewById(R.id.photoview);
Photo = (ImageButton)findViewById(R.id.Photoedit);
name = (TextView)findViewById(R.id.username);
email = (TextView)findViewById(R.id.useremail);
password = (TextView)findViewById(R.id.password1);
phone = (TextView)findViewById(R.id.userPhone);
mFirestore.collection("users").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String Name = documentSnapshot.getString("Name");
String Email = documentSnapshot.getString("Email");
String Password = documentSnapshot.getString("Password");
String Phone = documentSnapshot.getString("Phone Number");
name.setText(Name);
email.setText(Email);
password.setText(Password);
phone.setText(Phone);
}
});
Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_INTENT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
photoview.setImageBitmap(photo);
} else if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
photoview.setImageBitmap(thumbnail);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent i = new Intent(UserProfile.this,category.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
My database structure is
Ramiki(my app name)
So here it is
Ramiki --> users(collection)--> SiQEIDaQJfUBqZBBt1eo(document uid)----> fields(Email, Name, Password, Phone Number).
Well sorry i am not able to give screenshort because i am not allowed by stack overflow 10 points needed.
And my code for writing data in firestore is
public class LoginActivity extends AppCompatActivity implements View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LoginActivity";
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private TextInputEditText textInputEditTextPhone;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private FirebaseAuth auth;
private ProgressBar progressBar;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private SignInButton btnSignIn;
private FirebaseFirestore mFirebaseFirestore;
private FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
mFirebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build();
mFirebaseFirestore.setFirestoreSettings(settings);
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
}
};
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignIn.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
appCompatTextViewLoginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, account.class);
startActivity(i);
finish();
}
});
//if the user is already logged in we will directly start the category activity
if (SavesharedPreferences.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, category.class));
finish();
return;
}
findViewById(R.id.appCompatButtonRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("Name", Name);
user.put("Email", Email);
user.put("Password", Password);
user.put("Phone Number", Phone_Number);
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if(Password.length() < 7){
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!textInputEditTextPassword.getText().toString().equals(textInputEditTextConfirmPassword.getText().toString())) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else {
// Add a new document with a generated ID
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
registerUser();
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
}
});
initViews();
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
}
}
private void registerUser() {
final String Name = textInputEditTextName.getText().toString().trim();
final String Email = textInputEditTextEmail.getText().toString().trim();
final String Password = textInputEditTextPassword.getText().toString().trim();
final String Phone_Number = textInputEditTextPhone.getText().toString().trim();
final String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
return;
}
if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
return;
}
if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
return;
}
if(Password.length() < 7 ) {
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
return;
}
if (TextUtils.isEmpty(ConfirmPassword)) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this, "Register Successful " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
sendEmailVerification();
}
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
else if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Nothing Happens", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Please Check Your Email For Verification",Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(LoginActivity.this, account.class));
finish();
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private void initViews() {
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextPhone = (TextInputEditText) findViewById(R.id.textInputEditTextPhone);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this, "You Got an Error",Toast.LENGTH_LONG).show();
}
protected void onStart(){
super.onStart();
auth.addAuthStateListener(authListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
This unique id SiQEIDaQJfUBqZBBt1eo is generated when you are adding the user as a Map or when you are using a call to document() method without passing an argument.
In order to solve this, there are two ways. One would be to create a model class (UserModel), then create an object of that class and in the end get the uid of the user once it authenticated and add the object to the database like this:
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
UserModel userModel = new UserModel(Name, Email, Password, Phone_Number, ConfirmPassword);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(userModel);
See, I have passed the uid as argument to the document() method.
The second approach would be to pass no argument to the document() method but to store that key into a variable like this:
String key = usersRef.document().getKey();
usersRef.document(key).set(userModel);
Edit:
There also another method, which I recommend you use it. Instead of using this line of code:
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(/* ... */)
Use the following line of code:
mFirebaseFirestore.collection("users")
.document(uid)
.set(user)
.addOnSuccessListener(/* ... */)
Remove the old data, add fresh one and your problem will be solved.

The app crashed after sending location to server Android 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().

how to solve turning off Location

I have following script to get Location using GoogleAPI. Working on My App is based on Location. When This Activity was opened, thanks to using GoogleAPI is got Location Known as Latitude and Longitude.
When MainActivity is opened, if Location turns on within Device Settings.(Android smart Phone).Location Knowledge is obtained as a successfully way and in MainActivity doesn't happen any Problems. Conversely, when Location Turns off on
my android device, while the Activity is started, I have error and App close with a message that called "Unfortunately The App has stopped".
How can I solve this problem? while The Activity is opening How to Control whether Location turns on or off.
thanks in advance for the whole help.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
, LocationListener , DialogInterface.OnClickListener {
public static final String KEY_LOC_ADD_URL = "http://xxxxxxxx/android_api/insertlocation.php";
public static final String KEY_LATITUDE = "enlem";
public static final String KEY_LONGITUDE = "boylam";
public static final String KEY_ID="id";
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location mevcutKonum;
private String[] seconds={"1","3","5","7","10"};
private String sonGuncellemeZamani;
private String employee_id;
private Long requestTime;
private TextView enlemTextView;
private TextView boylamTextView;
private TextView sonGuncellemeTextView;
private TextView employee_name;
private AlertDialog dialogSelectInternal;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enlemTextView = (TextView) findViewById(R.id.enlem);
boylamTextView = (TextView) findViewById(R.id.boylam);
sonGuncellemeTextView = (TextView) findViewById(R.id.guncellemezamani);
sonGuncellemeZamani = "";
employee_name= (TextView) findViewById(R.id.userName);
Intent intent = getIntent();
employee_name.setText("Welcome User " + intent.getStringExtra(Login_Activity.KEY_USERNAME));
employee_id=intent.getStringExtra(Login_Activity.KEY_ID);
buildGoogleApiClient();
selectRequestTimeDialog();
createLocationRequest();
}
protected void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
locationRequest = LocationRequest.create()
.setInterval(3000)
.setFastestInterval(1000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void updateUI() {
if (mevcutKonum != null) {
enlemTextView.setText(String.valueOf(mevcutKonum.getLatitude()));
boylamTextView.setText(String.valueOf(mevcutKonum.getLongitude()));
sonGuncellemeTextView.setText(sonGuncellemeZamani);
}
}
#Override
protected void onResume() {
super.onResume();
googleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (googleApiClient.isConnected()) {
stopLocationUpdates();
}
googleApiClient.disconnect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mevcutKonum == null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mevcutKonum = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
try {
addLocationToUser(String.valueOf(mevcutKonum.getLatitude()),String.valueOf(mevcutKonum.getLongitude()),employee_id);
} catch (JSONException e) {
e.printStackTrace();
}
updateUI();
}
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mevcutKonum = location;
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void addLocationToUser(final String latitude, final String longitude,final String id) throws JSONException {
StringRequest stringRequest = new StringRequest(Request.Method.POST, KEY_LOC_ADD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(KEY_LATITUDE,latitude);
params.put(KEY_LONGITUDE, longitude);
params.put(KEY_ID,id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void selectRequestTimeDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Konumunuzu Güncellemek istediğiniz zaman aralığını seçiniz");
builder.setItems(seconds,this);
builder.setNegativeButton("Cancel", null);
dialogSelectInternal=builder.create();
dialogSelectInternal.show();
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
Above Code has worked when location only turns on
In your onCreate() , First check if your GPS is enabled in your device, if yes create location update, else go to Location Settings.
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createLocationRequest();
} else {
Toast.makeText(this, "Please enable your gps first.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent, 1);
}
On GPS -> HIGH ACCURACY selection:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
switch (requestCode) {
case 1:
createLocationRequest();
break;
}
}
}
Hope this helps.

Categories