0
votes

I'm trying to give a database reference to upload some data to my Firebase real-time database. I already have some data in the database and I'm retrieving it. I have a spinner in which the User can select a specific user to whom he wants to send the message. So I want to upload the data into the selected user's UID.

I tried retrieving the UID of the selected user directly but it didn't work, so I created a child called UID during the registration process. Now I'm able to retrieve the UID of the selected User and I'm storing it in String 'key'. I want to use 'key' as a child reference in database reference, so that I can upload my data under the selected user. I have checked the value of 'key' and it is the correct UID i.e., the UID of the selected user, but when I use this String in database reference, my app crashes.

public void onItemSelected(AdapterView<?> adapterView, View view,
                                           int position, long id) {
                    Object item = adapterView.getItemAtPosition(position);
                    NameSelected = item.toString();
                    pris = NameSelected;
                    ref = FirebaseDatabase.getInstance().getReference().child("Faculty_Database");
                    ref.orderByChild("Name").equalTo(pris).addValueEventListener(new ValueEventListener(){
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            for(DataSnapshot datas: dataSnapshot.getChildren()){
                                key = datas.child("UID").getValue(String.class);
                            }
                        }
//

SubmitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (NameEditText.getText().toString().equals("") || PhoneNumberEditText.getText().toString().equals("") || CompanyEditText.getText().toString().equals("") || EmailEditText.getText().toString().equals("") || AppointmentEditText.getText().toString().equals("") || image.equals(null)) {
                Toast.makeText(getApplicationContext(), "Please fill all details", Toast.LENGTH_LONG).show();
            } else {
                final StudentDetails studentDetails = new StudentDetails();
                GetDataFromEditText();
                studentDetails.setName(NameHolder);
                studentDetails.setPhoneNumber(NumberHolder);
                studentDetails.setemail(EmailHolder);
                studentDetails.setCompanyName(CompanyHolder);
                studentDetails.setAppointment(AppointmentHolder);
                studentDetails.setNameSelected(NameSelected);

                // Getting the ID from firebase database.
                final String StudentRecordIDFromServer = databaseReference.push().getKey();

                filePath = FirebaseStorage.getInstance().getReference().child("Visitors");
                ByteArrayOutputStream baos =  new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] dataToUpload = baos.toByteArray();
                UploadTask uploadTask = filePath.putBytes(dataToUpload);

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                        if (!task.isSuccessful()) {
                            throw task.getException();
                        }

                        // Continue with the task to get the download URL
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            downloadUri= task.getResult();
                                databaseReference = FirebaseDatabase.getInstance().getReference().child("Faculty_Database").child(key).child("Received");
                                Map<String, Object> mapToUpload = new HashMap<>();
                                mapToUpload.put("imageUrl", downloadUri.toString());
                                mapToUpload.put("Data", studentDetails);
                                databaseReference.child(StudentRecordIDFromServer).setValue(mapToUpload);
                        } else {
                            // Handle failures
                            // ...
                        }
                    }
                });
            }
            // Showing Toast message after successfully data submit.
            Toast.makeText(SecurityActivity.this, "Request Sent Successfully!", Toast.LENGTH_LONG).show();
        }
    });

This is my database

Please let me know how I can create a child called "Receieved" under the selected User's UID to upload my data?

1
I tried achieving the same thing in one of my project, your approach is somewhat right of creating the child reference. In my approach I made too child reference but instead of letting firebase makeing the default key by itself, I made the key as UID and later on I was able to fetch data using that UID. So I would suggest instead of making new key as 'UID' make firebase key itlsef as UID - shikhar
Yes, Firebase key itself is the UID here. I am creating a User with the UID provided by Firebase at authentication. I'm just uploading the same Firebase UID in the UID child of each user and retrieving the UID of the user selected and storing it in 'key'. - Vignesh N H
can you please show the error you are recieving - shikhar
My app just crashes. - Vignesh N H

1 Answers

0
votes

Add the code that sets data inside the onDataChange method, since onDataChange is asynchronous meaning that the code where you are setting the data is getting executed before retrieving the key.

 ref.orderByChild("Name").equalTo(pris).addValueEventListener(new ValueEventListener(){
    @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot datas: dataSnapshot.getChildren()){

       key = datas.child("UID").getValue(String.class);
      databaseReference = FirebaseDatabase.getInstance().getReference().child("Faculty_Database").child(key).child("Received");
      Map<String, Object> mapToUpload = new HashMap<>();
      mapToUpload.put("imageUrl", downloadUri.toString());
      mapToUpload.put("Data", studentDetails);
      databaseReference.child(StudentRecordIDFromServer).setValue(mapToUpload);
          }
    }