Reading and Writing Data in Android From Firebase
Note:- Sorry for my bad English considering 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 electric current location I am using FireBase realtime database. And 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 ane trouble when I am trying to fetch the user data from firebase. Information technology is non reflecting in the correct way. The data is reflecting in ii different lines in the log:
- line 1:- Latitude & Longitude is 0.0 merely electronic mail 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 take searched a lot on google only failed. Kindly help me empathize how information technology can exist washed in the correct way.
Below is my lawmaking 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)); } }); concluding 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 e-mail = details.email; Double lat = details.latitude; Double lon = details.longitude; tname.setText(lat+" "+'\n'+lon+'\n'+email); Organisation.out.println("-->"+ lat+" " + lon+" "+ email); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); }
MapsActivity.java
@Override protected void onCreate(Package savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); Firebase.setAndroidContext(this); if (android.bone.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } //Check if Google Play Services Available or non if (!CheckGooglePlayServices()) { Log.d("onCreate", "Finishing test example since Google Play Services are not available"); cease(); } else { Log.d("onCreate", "Google Play Services bachelor."); } 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 engagement = new Date(); mLastUpdateTime = ((dateFormat.format(date).toString())); saveToFirebase(); if (mCurrLocationMarker != cipher) { 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(truthful); markerOptions.title("Electric 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 Electric current Location", Toast.LENGTH_LONG).bear witness(); //end 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 Cord[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } else { // No explanation needed, nosotros 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 == zero) { buildGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { // Permission denied, Disable the functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).testify(); } return; } } } @Override public boolean onMarkerClick(Marker marker) { marking.setDraggable(true); render false; } @Override public void onMarkerDragStart(Marker marker) {} @Override public void onMarkerDrag(Marker marker) {} @Override public void onMarkerDragEnd(Marking marker) { end_latitude = marker.getPosition().latitude; end_longitude = mark.getPosition().longitude; Log.d("end_lat",""+end_latitude); Log.d("end_lng",""+end_longitude); } }
Login.class
@Override protected void onCreate(Parcel 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 = (Push) 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 five) { startActivity(new Intent(LoginActivity.this, SignupActivity.class)); } }); btnReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View 5) { 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 countersign = inputPassword.getText().toString(); if (TextUtils.isEmpty(email)) { Toast.makeText(getApplicationContext(), "Enter e-mail address!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).testify(); return; } progressBar.setVisibility(View.VISIBLE); //authenticate user auth.signInWithEmailAndPassword(electronic mail, password) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Chore<AuthResult> task) { progressBar.setVisibility(View.GONE); if (!chore.isSuccessful()) { // in that location was an error if (countersign.length() < 6) { inputPassword.setError(getString(R.cord.minimum_password)); } else { Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).bear witness(); } } else { Intent intent = new Intent(LoginActivity.this, MainActivity.form); startActivity(intent); cease(); } } }); } }); } public void userLoginInfo(){ String email = inputEmail.getText().toString(); mDatabase = FirebaseDatabase.getInstance().getReference().child("Email").push(); String userId = mDatabase.kid("e-mail").getKey(); mDatabase.child(userId).setValue(email); } }
UserInformation.class
public class UserInformation { public Cord e-mail; public double breadth; public double longitude; public UserInformation() { } public UserInformation(String email, double breadth, double longitude) { this.email = email; this.latitude = latitude; this.longitude = longitude; } public String getEmail() { return email; } public double getLatitude() { return breadth; } public double getLongitude() { return longitude; } }
Firebase Database screenshot Android Studio log screenshot
Source: https://stackoverflow.com/questions/46702930/reading-and-writing-data-in-firebase-database
0 Response to "Reading and Writing Data in Android From Firebase"
Post a Comment