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

时间:2017-12-31 17:30:06

标签: android firebase-realtime-database

我想在数据库中存储值,当我尝试运行应用程序时,它给了我一个错误。我是android studio的新手。

这是我的班级,点击了一个按钮:

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


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 FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;

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

    mRootRef = FirebaseDatabase.getInstance().getReference();
    mAuth = FirebaseAuth.getInstance();
    mCurrentUserId =  mAuth.getCurrentUser().getUid();
    user_id = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUserId);
    mChatUser = user_id.getRef().toString();


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

}

private void addEmergencyChat() {
    locationTrack = new LocationTrack(MenuActivity.this);


    if (locationTrack.canGetLocation()) {


        double longitude = locationTrack.getLongitude();
        double latitude = locationTrack.getLatitude();



            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",latitude);
            messageMap.put("longitude", longitude);
            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());
                    }
                }
            });

    } else {

        locationTrack.showSettingsAlert();
    }

}

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.
    FirebaseUser currentUser = mAuth.getCurrentUser();

    if(currentUser == null){

        sendToStart();

    } else {

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

    }

}


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

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

}

这是我的logcat

12-31 19:20:52.340 4357-4357/? E/Zygote: no v2
12-31 19:20:52.350 4357-4357/? E/SELinux: [DEBUG] get_category: variable 
seinfo: default sensitivity: NULL, cateogry: NULL
12-31 19:20:56.044 4357-4357/com.rescuex_za.rescuex E/AndroidRuntime: FATAL 
EXCEPTION: main
                                                                  Process: 
 com.rescuex_za.rescuex, PID: 4357

 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:232)
                                                                      at 
com.rescuex_za.rescuex.MenuActivity.access$100(MenuActivity.java:50)
                                                                      at 
com.rescuex_za.rescuex.MenuActivity$1.onClick(MenuActivity.java:92)
                                                                      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   )                                                                           在    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

2 个答案:

答案 0 :(得分:0)

检查您是否在firebase数据库中存储'.', '#', '$', '[', or ']'值。 firebase数据库不支持存储这些字符。

答案 1 :(得分:0)

双值包含'。'无法存储在firebase中的符号

这些行导致错误

double longitude = locationTrack.getLongitude();
double latitude = locationTrack.getLatitude();

        messageMap.put("latitude",latitude);
        messageMap.put("longitude", longitude);

[编辑]

您可以使用String.valueOf(longitude).replace(".", "*");存储此类值 后来在检索期间String.valueOf(longitude).replace("*", ".");

[编辑2]

很抱歉语法错误....

longitude = String.valueOf(longitude).replace(".", "*");

存储此类值以及稍后检索

longitude = String.valueOf(longitude).replace("*", ".");