Firebase数据库:创建新节点时应用程序崩溃

时间:2018-03-12 13:28:26

标签: java firebase firebase-realtime-database

My Home Activity将监听器附加到特定于给定userID的firebase数据库用户节点。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LayoutInflater inflater = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View contentView = inflater.inflate(R.layout.activity_home, null, false);
    drawer.addView(contentView, 0);

    mAuth = FirebaseAuth.getInstance();
    myRef = FirebaseDatabase.getInstance().getReference();
    final FirebaseUser currentUser = mAuth.getCurrentUser();

    fnEditText = (EditText) findViewById(R.id.fnEditTextHome);
    ......
    ratingBar = (RatingBar) findViewById(R.id.ratingBar);

    final String userID = currentUser.getUid();

    ValueEventListener postListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot,userID);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        }
    };

    myRef.addValueEventListener(postListener);
}

private void showData(DataSnapshot dataSnapshot, String userID) {
    for(DataSnapshot ds : dataSnapshot.getChildren()){
        UserInformation uInfo = new UserInformation();
        uInfo.setFirstName(ds.child(userID).getValue(UserInformation.class).getFirstName()); //set the name
        uInfo.setLastName(ds.child(userID).getValue(UserInformation.class).getLastName()); //set the name
        uInfo.setAddress(ds.child(userID).getValue(UserInformation.class).getAddress()); //set the name
        uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail()); //set the email
        uInfo.setPhoneNo(ds.child(userID).getValue(UserInformation.class).getPhoneNo()); //set the phone_num
        uInfo.setRating(ds.child(userID).getValue(UserInformation.class).getRating()); //set the rating

        fnEditText.setText(uInfo.getFirstName());
        lnEditText.setText(uInfo.getLastName());
        phoneEditText.setText(uInfo.getPhoneNo());
        addressEditText.setText(uInfo.getAddress());
        String d = uInfo.getRating();
        Float rating = Float.parseFloat(d);
        ratingBar.setRating(rating);
        //display all the information
        Log.d(TAG, "showData: name: " + uInfo.getFirstName());
        Log.d(TAG, "showData: email: " + uInfo.getEmail());
    }
}

上面的代码没有任何错误。当我在Firebase数据库控制台上更改值时,它会成功更新到EditText。

This is how the database looks.

现在,在Post Activity上,我有这段代码。

private void executeUploadTask(){
    Toast.makeText(PostActivity.this, "uploading image", Toast.LENGTH_SHORT).show();

    final String postId = FirebaseDatabase.getInstance().getReference().push().getKey();

    final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
            .child("posts/users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() +
                    "/" + postId + "/post_image");

    UploadTask uploadTask = storageReference.putBytes(mUploadBytes);
    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Toast.makeText(PostActivity.this, "Post Success", Toast.LENGTH_SHORT).show();

            //insert the download url into the firebase database
            @SuppressWarnings("VisibleForTests")
            Uri firebaseUri = taskSnapshot.getDownloadUrl();

            Log.d(TAG, "onSuccess: firebase download url: " + firebaseUri.toString());
            DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

            Post post = new Post();
            post.setImage(firebaseUri.toString());
            post.setContact_email(mContactEmail.getText().toString());
            post.setContact_number(mContactNumber.getText().toString());
            post.setDescription(mDescription.getText().toString());
            post.setPost_id(postId);
            post.setPrice(mPrice.getText().toString());
            post.setTitle(mTitle.getText().toString());
            post.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());

            reference.child(getString(R.string.node_posts))
                    .child(postId)
                    .setValue(post);

            resetFields();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(PostActivity.this, "could not upload photo", Toast.LENGTH_SHORT).show();
        }
    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
            @SuppressWarnings("VisibleForTests") double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
            if( currentProgress > (mProgress + 15)){
                mProgress = currentProgress;
                Log.d(TAG, "onProgress: upload is " + mProgress + "& done");
                Toast.makeText(PostActivity.this, mProgress + "%", Toast.LENGTH_SHORT).show();
            }
        }
    });
}
在新节点上发布项目后,

This is now how the database looks如果我回到第一个活动,它现在会崩溃。删除帖子节点可以阻止应用程序崩溃。

这是发生崩溃的地方。

error1

error2

1 个答案:

答案 0 :(得分:1)

要解决此问题,请更改以下代码行:

myRef = FirebaseDatabase.getInstance().getReference();

myRef = FirebaseDatabase.getInstance().getReference().child("users");

请同时更改此行代码:

UserInformation uInfo = new UserInformation();

UserInformation uInfo = ds.getValue(UserInformation.class);

并评论所有这些代码:

uInfo.setFirstName(ds.child(userID).getValue(UserInformation.class).getFirstName()); //set the name
uInfo.setLastName(ds.child(userID).getValue(UserInformation.class).getLastName()); //set the name
uInfo.setAddress(ds.child(userID).getValue(UserInformation.class).getAddress()); //set the name
uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail()); //set the email
uInfo.setPhoneNo(ds.child(userID).getValue(UserInformation.class).getPhoneNo()); //set the phone_num
uInfo.setRating(ds.child(userID).getValue(UserInformation.class).getRating()); //set the rating

您不需要创建新对象,您已经从数据库中获取它。