来自firebase的函数addListenerForSingleValueEvent

时间:2017-01-23 17:21:02

标签: android firebase firebase-realtime-database

使用Firebase数据库。 我有一个存储患者注册信息的数据库。 在注册新患者时,我要检查该人是否已经注册。

以下功能检查是否已经注册了该人。 我通过转到" Users / Phone_no / Patient_name"来检查这个。 如果DataSnapshot不是空注册已经存在。

private boolean checkAlreadyRegistered(){

    final boolean[] alreadyRegistered = {false};
    /*Get the reference*/
    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users/" + childDetails.getPhone() + "/" + childDetails.getPatientName());
    mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(TAG, "onDataChange: " + dataSnapshot);
            if (dataSnapshot.getValue() != null) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("Record Already Exists");
                builder.setMessage("The current patient is already registered");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        alreadyRegistered[0] = true;
                    }
                });
                builder.create();
                builder.show();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_LONG).show();
        }
    });
    return  alreadyRegistered[0];
}

从saveInDatabase我调用上述功能

void saveInDatabase(Long patient_id) {


    boolean alreadyRegistered = checkAlreadyRegistered();
    if (alreadyRegistered) {
        resetRegisterFields();
        return;
    }
    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Current_registered_users");
    mDatabaseReference.setValue(patient_id + 1);
    childDetails.setPatient_id(patient_id);
    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users");
    Log.d(TAG, "saveInDatabase: "+mDatabaseReference);
    mDatabaseReference.child(childDetails.getPhone()).child(childDetails.getPatientName()).child("Registration Details").setValue(childDetails);
    Button bt = (Button) getView().findViewById(R.id.buttonRegister);
    resetRegisterFields();
    progressDialog.dismiss();
    displayPid(patient_id);
    bt.setEnabled(true);
    .
    .
}

我想做什么 - 检查是否已经根据phone_no / Patient_name进行了注册,如果没有保存详细信息。

问题 - 当进行新注册时,它会被添加到数据库中,但之后会显示消息" ..已经注册",来自checkAlreadyRegistered() - > onDataChange。

为什么会出现这个消息,以及如何解决它?

2 个答案:

答案 0 :(得分:0)

Firebase中的所有数据读取都是异步发生的,因此我建议您将代码更改为如下所示:

private void checkAlreadyRegistered(){

    /*Get the reference*/
    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users/" + childDetails.getPhone() + "/" + childDetails.getPatientName());
    mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(TAG, "onDataChange: " + dataSnapshot);
            if (dataSnapshot.getValue() != null) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("Record Already Exists");
                builder.setMessage("The current patient is already registered");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        resetRegisterFields();
                    }
                });
                builder.create();
                builder.show();
            }
            else
            {
                saveInDatabase(patient_id); //TODO change this accordingly
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_LONG).show();
        }
    });
}

你的保存方法:

void saveInDatabase(Long patient_id) {
    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Current_registered_users");
    mDatabaseReference.setValue(patient_id + 1);
    childDetails.setPatient_id(patient_id);
    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users");
    Log.d(TAG, "saveInDatabase: "+mDatabaseReference);
    mDatabaseReference.child(childDetails.getPhone()).child(childDetails.getPatientName()).child("Registration Details").setValue(childDetails);
    Button bt = (Button) getView().findViewById(R.id.buttonRegister);
    resetRegisterFields();
    progressDialog.dismiss();
    displayPid(patient_id);
    bt.setEnabled(true);
    .
    .
}

答案 1 :(得分:0)

您必须等待Firebase的回复。您可以添加回调以在检索到代码后运行其余代码。做这样的事情:

创建一个名为ServerCallback的界面:

public interface ServerCallback
{
    void onSuccess(boolean result);
}

在您的checkAlreadyRegistered()方法中,添加回调,以便在从Firebase检索数据后运行回调:

private void checkAlreadyRegistered(final ServerCallback callback){
    final boolean[] alreadyRegistered = {false};
    /*Get the reference*/
    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users/" + childDetails.getPhone() + "/" + childDetails.getPatientName());
    mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(TAG, "onDataChange: " + dataSnapshot);
            if (dataSnapshot.getValue() != null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("Record Already Exists");
                builder.setMessage("The current patient is already registered");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        alreadyRegistered[0] = true;
                        callback.onSuccess(alreadyRegistered[0]);
                    }
                });
                builder.create();
                builder.show();
            }
            else
               callback.onSuccess(alreadyRegistered[0]);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_LONG).show();
        }
    });
}

然后在saveInDatabase()中,等待回调,然后运行其余代码:

void saveInDatabase(Long patient_id) {
    boolean alreadyRegistered = checkAlreadyRegistered(new ServerCallback() {
        @Override
        public void onSuccess(boolean result)
        {
            if (alreadyRegistered) {
                resetRegisterFields();
                return;
            }
            mDatabaseReference = FirebaseDatabase.getInstance().getReference("Current_registered_users");
            mDatabaseReference.setValue(patient_id + 1);
            childDetails.setPatient_id(patient_id);
            mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users");
            Log.d(TAG, "saveInDatabase: "+mDatabaseReference);
            mDatabaseReference.child(childDetails.getPhone()).child(childDetails.getPatientName()).child("Registration Details").setValue(childDetails);
            Button bt = (Button) getView().findViewById(R.id.buttonRegister);
            resetRegisterFields();
            progressDialog.dismiss();
            displayPid(patient_id);
            bt.setEnabled(true);
            .
            .
        });
 }