有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当用户再次登录时,数据从Firebase数据库中删除

我创建了一个数据库,存储用户信息,如电子邮件、密码、纬度、经度和工厂位置plant location是指当用户点击地图时,该位置的纬度和经度会保存在plant location中

之前的数据库映像: enter image description here

但当我注销当前用户,然后再次使用相同的电子邮件登录时,工厂位置被删除。正如你们现在可以看到的,工厂的位置和它的子节点被删除了

数据库之后:

enter image description here

请帮帮我

地图活动。爪哇

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        NavigationView.OnNavigationItemSelectedListener,
        AppCompatCallback {
    private static final String Tag = "MapsActivity";
    private GoogleMap mMap;
    GeoFire geoFire;
    SharedPrefrence mShared;
    public AppCompatDelegate delegate;
    private final float DEFAULT_ZOOM = 15f;
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    public Boolean mLocationPermissionGranted = false;
    private static final int LOCATION_PERMISSION_REQUESTCODE = 1234;
    public static DatabaseReference mReference,user_ref;
    DrawerLayout drawerLayout;
    boolean doubleBackToExitPressedOnce = false;
    Toolbar tool;
    FirebaseAuth mAuth;
    ImageView img;
    FirebaseAuth.AuthStateListener authStateListener;
    ActionBarDrawerToggle actionBarDrawerToggle;
    String userID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        delegate = AppCompatDelegate.create(this, this);
        delegate.onCreate(savedInstanceState);
        delegate.setContentView(R.layout.activity_maps);
        getlocationpermission();
        mShared=new SharedPrefrence(this);
        mAuth = FirebaseAuth.getInstance();
        userID=mAuth.getCurrentUser().getUid();
        img = findViewById(R.id.tree_button);
        mReference = FirebaseDatabase.getInstance().getReference().child("UserData");
        user_ref=FirebaseDatabase.getInstance().getReference().child("You");
        tool = findViewById(R.id.toolbar);
        delegate.setSupportActionBar(tool);
        delegate.getSupportActionBar().setDisplayShowTitleEnabled(true);
        drawerLayout = findViewById(R.id.drawer);
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.setDrawerIndicatorEnabled(true);//use for toggling navbar
        actionBarDrawerToggle.syncState();
        NavigationView navigationView = findViewById(R.id.navigation);
        navigationView.setNavigationItemSelectedListener(this);    
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() == null) {
                    Toast.makeText(getApplicationContext(), "Logged Out", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(MapsActivity.this, Login.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(i);
                }
            }
        };
       geoFire = new GeoFire(user_ref);
    }


    void initMap() {
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        supportMapFragment.getMapAsync(MapsActivity.this);
    }

    private void getlocationpermission() {
        String[] permission = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
                initMap();
            } else {
                ActivityCompat.requestPermissions(this, permission, LOCATION_PERMISSION_REQUESTCODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUESTCODE: {
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionGranted = true;
                            return;
                        }
                    }
                    mLocationPermissionGranted = true;
                    initMap();
                }
            }
        }
    }

    private void getDeviceLocationMethod() {
        Log.d(Tag, "getting the device location");
        FusedLocationProviderClient mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        final Task<Location> location = mFusedLocationProviderClient.getLastLocation();
        location.addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                    Location currentlocation = task.getResult();
                    User_Data user_data=new User_Data(mShared.getUser_pass(),mShared.getUser_email(),currentlocation.getLatitude(),
                            currentlocation.getLongitude());
                  mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentlocation.getLatitude(),
                  currentlocation.getLongitude()), DEFAULT_ZOOM));
                  DatabaseReference user=FirebaseDatabase.getInstance().getReference("UserData");
                  user.child(userID).setValue(user_data);
                  addMarker(new LatLng(currentlocation.getLatitude(), currentlocation.getLongitude()), mMap);
                } else {
                    Toast.makeText(MapsActivity.this, "Error while finding the location" + task.getException(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        getDeviceLocationMethod();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mMap.setMyLocationEnabled(true);
        location_to_firebase(googleMap);
    }

    private void location_to_firebase(final GoogleMap google_map) {
        int height = 150;
        int width = 150;
        final BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.icon);
        Bitmap b = bitmapdraw.getBitmap();
        final Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
        google_map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng point) {
                Marker marker = google_map.addMarker(new MarkerOptions().position(point));
                marker.setIcon(BitmapDescriptorFactory
                        .fromBitmap(smallMarker));
                final LatLng latLng = marker.getPosition();
                final DatabaseReference newPost = mReference.child(userID);
                newPost.child("plant location").push().setValue(latLng);
            }
        });
        mReference.child(userID).child("plant location").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot s:dataSnapshot.getChildren()){
                    final LatLng lng = new LatLng(s.child("latitude").getValue(Double.class),
                            s.child("longitude").getValue(Double.class));
                    google_map.addMarker(new MarkerOptions().
                            position(lng).title(s.getKey())).setIcon(BitmapDescriptorFactory.fromBitmap(smallMarker));
                    google_map.addCircle(new CircleOptions().center(lng).radius(500).strokeColor(Color.TRANSPARENT));
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

登录。爪哇

public class Login extends AppCompatActivity {

    EditText _email, _password;
    Button _submit,_signup;
    SharedPrefrence mShared;
    private FirebaseAuth mAuth;
    private static final int LOCATION_PERMISSION_REQUESTCODE=1234;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        _email = findViewById(R.id.email);
        _password = findViewById(R.id.password);
        _submit = findViewById(R.id.login);
        _signup=findViewById(R.id.signup);
        mShared=new SharedPrefrence(this);
        _signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this,Signup.class));
            }
        });
        mAuth = FirebaseAuth.getInstance();
        _submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSignin();
            }
        });
        runtimepermission();
    }


    private void startSignin() {
        final String email = _email.getText().toString();
        final String pass = _password.getText().toString();
        if (TextUtils.isEmpty(email) || TextUtils.isEmpty(pass)) {
            Toast.makeText(this, "Invalid Email or Password", Toast.LENGTH_SHORT).show();

        } else {
            mAuth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (!task.isSuccessful()) {
                        Toast.makeText(Login.this, "SigninProblem", Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        mShared.saveEmail(Login.this,email);
                        mShared.savePass(Login.this,pass);
                        Intent i=new Intent(Login.this,MapsActivity.class);
                        startActivity(i);
                        finish();
                    }

                }
            }).addOnCanceledListener(new OnCanceledListener() {
                @Override
                public void onCanceled() {
                    Toast.makeText(Login.this,"Login Canceled",Toast.LENGTH_LONG).show();
                }
            });
        }
    }

共 (1) 个答案

  1. # 1 楼答案

    But when I signout the current user and then login back again with the same email then plant location was removed.

    当你重新登录时,问题并没有发生,而每次你的地图准备好时,问题都会发生。您在onMapReady()方法中调用getDeviceLocationMethod(),这意味着每次地图准备就绪时,您都在创建一个新的User_Data对象,这意味着您正在覆盖数据库中的现有用户。这样plant location节点中的所有数据都会被删除。要解决这个问题,只需检查用户是否已经存在。如果没有,请将其添加到数据库中,否则不采取任何操作