Home > database >  My app is gets back to previous page without updating data to database. (Using Android studio Fire
My app is gets back to previous page without updating data to database. (Using Android studio Fire

Time:03-20

My app is gets back to previous page without updating data to database. (Using Android studio Firebase) This is the java code for the activity

 package com.example.hospital_management_system;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.HashMap;
import java.util.UUID;

import de.hdodenhof.circleimageview.CircleImageView;

public class DoctorRegistrationActivity extends AppCompatActivity {
private TextView backToLogin;
private TextInputEditText dregistrationFullName, dregistrationIdNumber,             
dregistrationPhoneNumber, doctorRegMailId, doctorRegPassword;
private CircleImageView dprofileImage;
private Spinner availabilitySpinner,departmentSpinner,specializationSpinner;
private Button regButton;
public Uri resultUri;
private FirebaseAuth mAuth;
private FirebaseStorage Storage;
private StorageReference storageReference;
private DatabaseReference userDatabaseRef;

private ProgressDialog loader;

@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_doctor_registration);
    backToLogin = findViewById(R.id.backToLogin);
    backToLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(DoctorRegistrationActivity.this,                   
LoginActivity.class);
            startActivity(intent);
        }
    });
    dregistrationFullName = findViewById(R.id.dregistrationFullName);
    dregistrationPhoneNumber = findViewById(R.id.dregistrationPhoneNumber);
    dregistrationIdNumber = findViewById(R.id.dregistrationIdNumber);
    doctorRegMailId = findViewById(R.id.doctorRegMailId);
    doctorRegPassword = findViewById(R.id.doctorRegPassword);
    regButton = findViewById(R.id.regButton);
    dprofileImage = findViewById(R.id.dprofileImage);
    departmentSpinner = (Spinner)findViewById(R.id.departmentSpinner);
    specializationSpinner =(Spinner)findViewById(R.id.specializationSpinner);
    availabilitySpinner =(Spinner)findViewById(R.id.availabilitySpinner);

    loader = new ProgressDialog(this);
    mAuth = FirebaseAuth.getInstance();

    dprofileImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            choosePicture();
        }
    });


    regButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("yoyoyoyoyoyoyo", "reg just  clicked ");
            final String email = doctorRegMailId.getText().toString().trim();
            final String password = doctorRegPassword.getText().toString().trim();
            final String fullName = dregistrationFullName.getText().toString().trim();
            final String idNumber = dregistrationIdNumber.getText().toString().trim();
            final String phoneNumber = 
dregistrationPhoneNumber.getText().toString().trim();
            Log.d("yoyoyoyoyoyoyo", "reached to spinner ");
            final String department = 
departmentSpinner.getSelectedItem().toString().trim();
            final String specialization = 
specializationSpinner.getSelectedItem().toString().trim();
            final String availability = 
availabilitySpinner.getSelectedItem().toString().trim();


            if (TextUtils.isEmpty(email)) {
                doctorRegMailId.setError("Email is Required!");
                return;
            }
            if (TextUtils.isEmpty(password)) {
                doctorRegPassword.setError("Password is Required!");
                return;
            }
            if (TextUtils.isEmpty(fullName)) {
                dregistrationFullName.setError("Name is Required!");
                return;
            }
            if (TextUtils.isEmpty(idNumber)) {
                dregistrationIdNumber.setError("IdNumber is Required!");
                return;
            }
            if (TextUtils.isEmpty(phoneNumber)) {
                dregistrationPhoneNumber.setError("PhoneNumber is Required!");
                return;
            }

            if(resultUri==null){
                Toast.makeText(DoctorRegistrationActivity.this, "profile is required", 
Toast.LENGTH_SHORT).show();
            }
            else{
                Log.d("yoyoyoyoyoyoyo", "else ");
                loader.setMessage("Registration in progress...");
                loader.setCanceledOnTouchOutside(false);
                loader.show();
                Log.d("yoyoyoyoyoyoyo", "reached to mauth ");
                
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new 
OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if(task.isSuccessful()){
                            Log.d("yoyoyoyoyoyoyo", "task is successful ");
                            String currentUserId = mAuth.getCurrentUser().getUid();
                            userDatabaseRef = 
FirebaseDatabase.getInstance().getReference().child("users").child(currentUserId);
//                                userDatabaseRef.setValue("name",fullName);
//                                userDatabaseRef.setValue("email",email);
//                                userDatabaseRef.setValue("idnumber",idNumber);
//                                userDatabaseRef.setValue("phonenumber",phoneNumber);
//                                userDatabaseRef.setValue("department",department);
//                                
userDatabaseRef.setValue("specialization",specialization);
//                                userDatabaseRef.setValue("availability",availability);
                            HashMap doctorInfo = new HashMap();
                            Log.d("yoyoyoyoyoyoyo", "after hasmap");
                            doctorInfo.put("name",fullName);
                            doctorInfo.put("email",email);
                            doctorInfo.put("idnumber",idNumber);
                            doctorInfo.put("phonenumber",phoneNumber);
                            Log.d("yoyoyoyoyoyoyo", "after phone number ");
                            doctorInfo.put("department",department);
                            doctorInfo.put("specialization",specialization);
                            Log.d("yoyoyoyoyoyoyo", "after specialization ");
                            doctorInfo.put("availability",availability);
                            doctorInfo.put("type","doctor");
                            Log.d("yoyoyoyoyoyoyo", "after doctor ");

                            
userDatabaseRef.updateChildren(doctorInfo).addOnCompleteListener(new 
OnCompleteListener() {

                                @Override
                                public void onComplete(@NonNull Task task) {
                                    Log.d("yoyoyoyoyoyoyo", "before details set 
successfully ");
                                    if(task.isSuccessful()){
                                        Toast.makeText(DoctorRegistrationActivity.this, 
"Details set successfully", Toast.LENGTH_SHORT).show();
                                    }
                                    else{
                                        
Toast.makeText(DoctorRegistrationActivity.this,task.getException().toString() , 
Toast.LENGTH_SHORT).show();
                                    }
                                    finish();
                                    loader.dismiss();
                                }
                            });

                            if(resultUri!=null){

                                uploadImage();
                            }
                            Intent intent = new Intent(DoctorRegistrationActivity.this, 
LoginActivity.class);
                            startActivity(intent);
                            finish();
                            loader.dismiss();
                        }
                        else{
                            Log.d("yoyoyoyoyoyoyo", "else ");
                            String error = task.getException().toString();
                            Toast.makeText(DoctorRegistrationActivity.this, "Error 
Occurred: " error, Toast.LENGTH_SHORT).show();}
                    }

                });
            }
        }
    });


}



private void choosePicture() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startForResult.launch(intent);
}
ActivityResultLauncher<Intent> startForResult = registerForActivityResult(new 
ActivityResultContracts.StartActivityForResult(), new 
ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if(result!=null&&result.getResultCode()==RESULT_OK){
            if(result.getData()!=null ){
                Intent data = result.getData();
                resultUri = data.getData();
                dprofileImage.setImageURI(resultUri);

            }
        }
    }
});

private void uploadImage(){

    final String randomKey = UUID.randomUUID().toString();
    // Create a reference to "mountains.jpg"
    StorageReference mountainsRef = storageReference.child("image/" randomKey);

    mountainsRef.putFile(resultUri).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Toast.makeText(DoctorRegistrationActivity.this, "Failed to Upload Image", 
Toast.LENGTH_SHORT).show();
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override

        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            Toast.makeText(DoctorRegistrationActivity.this, "Successfully Uploaded 
Image", Toast.LENGTH_SHORT).show();
        }
    });
}
}

This is the log at that time, I had already tried to debug but couldn't get any solution.........................................................................................

   D/yoyoyoyoyoyoyo: task is successful 
   D/yoyoyoyoyoyoyo: after hasmap
   D/yoyoyoyoyoyoyo: after phone number 
   D/yoyoyoyoyoyoyo: after specialization 
   D/yoyoyoyoyoyoyo: after doctor 
   D/AndroidRuntime: Shutting down VM
   E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.hospital_management_system, PID: 12296
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.storage.StorageReference com.google.firebase.storage.StorageReference.child(java.lang.String)' on a null object reference
    at com.example.hospital_management_system.DoctorRegistrationActivity.uploadImage(DoctorRegistrationActivity.java:231)
    at com.example.hospital_management_system.DoctorRegistrationActivity.access$1200(DoctorRegistrationActivity.java:42)
    at com.example.hospital_management_system.DoctorRegistrationActivity$3$1.onComplete(DoctorRegistrationActivity.java:184)
    at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:236)
    at android.app.ActivityThread.main(ActivityThread.java:8061)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
I/Process: Sending signal. PID: 12296 SIG: 9
Disconnected from the target VM, address: 'localhost:54389', transport: 'socket'

CodePudding user response:

You should initialize your storage reference before you call its child, so inside your uploadImage(), add 2 lines at the begining:

final String randomKey = UUID.randomUUID().toString();
// Create a reference to "mountains.jpg"
FirebaseStorage storage = FirebaseStorage.getInstance(); // add this
storageReference = storage.getReference(); // and this
StorageReference mountainsRef = storageReference.child("image/" randomKey);
  • Related