com.google.firebase.database.DatabaseException:Firebase数据库路径无效

时间:2018-01-02 10:19:23

标签: java android firebase-realtime-database

当我尝试在我的数据库中存储我的位置的纬度和经度时,我收到此错误

01-02 11:54:30.820 24616-24616/? E/Zygote: no v2
01-02 11:54:30.830 24616-24616/? E/SELinux: [DEBUG] 
get_category:   variable   seinfo: default sensitivity: NULL, cateogry: NULL
01-02 11:54:33.823 24616-24616/com.rescuex_za.rescuex
E/AndroidRuntime:    FATAL EXCEPTION: main

                                                                                  Process:
 com.rescuex_za.rescuex, 
PID: 24616
                                                                                 com.google.firebase.database.
 DatabaseException:
 Invalid Firebase Database path:
 https://rescuex-8f9c9.firebaseio.com/Users/NcZ0McVHEuRfaMv39gHbDlpjI1X2.    Firebase Database paths must not contain
   '.', '#', '$', '[', or ']'
                                                                        at com.google.android.gms.internal.zzelv.zzqh(Unknown Source)
                                                                        at com.google.firebase.database.DatabaseReference.child(Unknown Source)
                                                                        at com.rescuex_za.rescuex.MenuActivity.addEmergencyChat(MenuActivity.java:247)
                                                                        at com.rescuex_za.rescuex.MenuActivity.access$100(MenuActivity.java:55)
                                                                        at com.rescuex_za.rescuex.MenuActivity$1.onClick(MenuActivity.java:106)
                                                                        at android.view.View.performClick(View.java:5076)
                                                                        at android.view.View$PerformClick.run(View.java:20279)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5910)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

这是我的班级,我发送位置的纬度和经度

   public class MenuActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, 
       OnMapReadyCallback,
         ConnectionCallbacks,
         OnConnectionFailedListener  {

private static final  String TAG = "RescueX";
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private DatabaseReference mLocationDatabase;

ImageButton fakeCallBtn;
Button mRescue;
ImageButton notif;
ImageButton flash;
private  Double lati;
private GoogleMap mMap;
LocationManager locationManager;

private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private DatabaseReference user_id;
private String mChatUser;

private String message;
private String value_lat = null;
private String value_long = null;

private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);

    FirebaseApp.initializeApp(this);
    mRootRef = FirebaseDatabase.getInstance().getReference();
    mLocationDatabase = mRootRef.child("EmergencyMessages");
    mAuth = FirebaseAuth.getInstance();
    mCurrentUserId =  mAuth.getCurrentUser().getUid();
    user_id = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUserId);
    mChatUser = user_id.getRef().toString();
    buildGoogleApiClient();


    mRescue = (Button)findViewById(R.id.rescue);
    mRescue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            addEmergencyMessage();
            addEmergencyChat();


        }
    });

    fakeCallBtn = (ImageButton) findViewById(R.id.fake_callbtn);
    fakeCallBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent fakecallIntent = new Intent(MenuActivity.this, FakeCalling.class);
            startActivity(fakecallIntent);
        }
    });
    flash = (ImageButton) findViewById(R.id.flash);
    flash.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent flashIntent = new Intent(MenuActivity.this, FlashLight.class);
            startActivity(flashIntent);
        }
    });

    notif = (ImageButton) findViewById(R.id.notification_btn);
    notif.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent notificationIntent = new Intent(MenuActivity.this, Notifications.class);
            startActivity(notificationIntent);
        }
    });

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("RescueX ");

    if (mAuth.getCurrentUser() != null) {


        mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
        mUserRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                userName = dataSnapshot.child("name").getValue().toString();


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.e("fist","error");

        return ;

    }


    if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                //get latitude
                double latitude = location.getLatitude();
                //get longitude
                double longitude = location.getLongitude();
                LatLng latLng = new LatLng(latitude, longitude);
                Geocoder geocoder = new Geocoder(getApplicationContext());
                try {
                    List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                    String str = addressList.get(0).getCountryName() + ",";
                    str += addressList.get(0).getLocality();

                    mMap.addMarker(new MarkerOptions().position(latLng).title(str));

                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }


            @Override
            public void onProviderDisabled(String provider) {
                Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
    }

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
                      .addConnectionCallbacks(this)
                      .addOnConnectionFailedListener(this)
                      .addApi(LocationServices.API)
                      .build();
}

private void addEmergencyChat() {


    value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
    value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");
            String current_user_ref="Emergency_Messages/"+mCurrentUserId+"/"+mChatUser;
            String chat_user_ref= "Emergency_Messages/"+mChatUser+"/"+mCurrentUserId;

            DatabaseReference chat_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).
                    child(mChatUser).push();

            String push_key = chat_push_key.getKey();

            Map messageMap = new HashMap();
            messageMap.put("userName", userName);
            messageMap.put("latitude",value_lat);
            messageMap.put("longitude", value_long);
            messageMap.put("from",mCurrentUserId);
            messageMap.put("seen",false);
            messageMap.put("time", ServerValue.TIMESTAMP);

            Map messageUserMap = new HashMap();
            messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
            messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);

            mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                    if(databaseError!=null){
                        Log.d("TAG",databaseError.getMessage().toString());
                    }
                }
            });

    }



private void addEmergencyMessage() {

    mRootRef.child("Emergency_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if(!dataSnapshot.hasChild(mChatUser)){

                Map chatAddMap = new HashMap();
                chatAddMap.put("seen",false);
                chatAddMap.put("timestamp", ServerValue.TIMESTAMP);

                Map chatUserMap = new HashMap();
                chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+mChatUser, chatAddMap);
                chatUserMap.put("Emergency_Chat/"+mChatUser+"/"+mCurrentUserId, chatAddMap);

                mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                        if(databaseError!= null){
                            Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();

                        }
                    }
                });
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}


@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    mGoogleApiClient.connect();
    FirebaseUser currentUser = mAuth.getCurrentUser();

    if(currentUser == null){

        sendToStart();

    } else {

        mUserRef.child("online").setValue("true");

    }

}


@Override
protected void onStop() {
    super.onStop();

    if (mGoogleApiClient.isConnected())
        mGoogleApiClient.disconnect();

    FirebaseUser currentUser = mAuth.getCurrentUser();

    if(currentUser != null) {

        mUserRef.child("online").setValue(ServerValue.TIMESTAMP);

    }

}

private void sendToStart() {

    Intent startIntent = new Intent(MenuActivity.this, Home.class);
    startActivity(startIntent);
    finish();

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;


}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);// Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    if(item.getItemId()== R.id.log_out){
        FirebaseAuth.getInstance().signOut();
        sendToStart();

    }



    //noinspection SimplifiableIfStatement
    if (item.getItemId() == R.id.action_settings) {
        Intent notifIntent= new Intent(MenuActivity.this, Settings.class);
        startActivity(notifIntent);
    }
    if(item.getItemId() == R.id.all_users){

        Intent usersIntent= new Intent(MenuActivity.this, UsersActivity.class);
        startActivity(usersIntent);

    }

    return true;
}


@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_profile_layout) {
        Intent searchIntent = new Intent(MenuActivity.this, Profile.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);

    } else if (id == R.id.nav_users_activity) {
        Intent searchIntent = new Intent(MenuActivity.this, UsersActivity.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    } else if (id == R.id.nav_history_layout) {
        Intent searchIntent = new Intent(MenuActivity.this, History.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    } else if (id == R.id.nav_help_layout) {
        Intent searchIntent = new Intent(MenuActivity.this, Help.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    } else if (id == R.id.nav_feedback_layout) {
        Intent searchIntent = new Intent(MenuActivity.this, Feedback.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    } else if (id == R.id.nav_signout_layout) {
        Intent searchIntent = new Intent(MenuActivity.this, SignOut.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    } else if (id == R.id.nav_friends_layout) {
        Intent searchIntent = new Intent(MenuActivity.this, FriendsActivity.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);

    } else if (id == R.id.nav_share) {
        Intent searchIntent = new Intent(MenuActivity.this, Share.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@SuppressLint("MissingPermission")
@Override
public void onConnected(@Nullable Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null){
        value_lat = String.valueOf(mLastLocation.getLatitude()).replace(".","d");
        value_long = String.valueOf(mLastLocation.getLongitude()).replace(".","d");

    }


}

@Override
public void onConnectionSuspended(int cause) {
  Log.i(TAG,"Connection suspended");
  mGoogleApiClient.connect();

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i(TAG, " Connection Failed "+ connectionResult.getErrorMessage());

}

@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}

}

我想要做的是阅读用户打开包含上述代码的页面时显示的位置,在阅读用户的位置后我想将这些值存储在我的数据库中稍后会在另一个班级中找回。

1 个答案:

答案 0 :(得分:0)

更换。与*没有真正起作用,并且从Cao Minh Vu建议它可能有问题mChatUser指向一个空值,所以我对它进行了排序,并且可能使用纬度和经度:

String lat = String.ValueOf(latitude.getLatitude());
String long = String.valueOf(longitude.getLongitude());

感谢所有对我的帖子发表评论的人,我不会发现问题,因为我的代码中有太多行,很难确定哪一行给我一个问题