I have a code:
#Override
protected void onCreate(Bundle savedInstanceState) {
.........
listViewMyAccountSettings = (ListView) findViewById(R.id.listViewMyAccountSettings);
arrayList = new ArrayList();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
listViewMyAccountSettings.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
listViewMyAccountSettings.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
showAlertUsername();
} else if (position == 1){
showAlertAge();
}
......................
}
});
.................
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("userdata").child(myEmail).child("username");
myRef.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
username = dataSnapshot.getValue(String.class);
arrayList.add("Your username: " + username);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG", "Failed to read value.", error.toException());
}
});
There is showAlertUsername method:
private void showAlertUsername() {
alertDialogBuilder = new AlertDialog.Builder(
MyAccountSettings.this);
input = new EditText(MyAccountSettings.this);
lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialogBuilder.setView(input);
alertDialogBuilder.setPositiveButton("Discard",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "No changes were made",
Toast.LENGTH_SHORT).show();
}
});
alertDialogBuilder
.setTitle("USERNAME")
.setMessage("Enter new username")
.setCancelable(false)
.setNegativeButton("Change",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (!input.getText().toString().isEmpty()) {
mDatabase.child("userdata").child(myEmail).child("username").setValue(input.getText().toString());
Toast.makeText(getApplicationContext(), "Your username was changed successfully",
Toast.LENGTH_LONG).show();
listViewMyAccountSettings.invalidateViews();
} else {
Toast.makeText(getApplicationContext(), "Username can't be empty. No changes were made",
Toast.LENGTH_LONG).show();
}
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
And I want to update particular field in list view when I change value(and set it into database). Problem is that when I change value in database it adds a new item to list view with new value? Is there a way to update the old one without restarting an activity? Thanks.
Every time the firebase data is changed you add a new item to the list:
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
username = dataSnapshot.getValue(String.class);
arrayList.add("Your username: " + username);
}
Clear the list if before that if you want to have a single entry.
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
arrayList.clear();
username = dataSnapshot.getValue(String.class);
arrayList.add("Your username: " + username);
arrayAdapter.notifyDataSetChanged();
}
You would change the data if your current ArrayList contains otherwise just add the new one:
public void onDataChange(DataSnapshot dataSnapshot) {
username = dataSnapshot.getValue(String.class);
String item = "Your username: " + username;
if(arrayList.contains(item)) {
//if current arrayList contains the item just change it
arrayList.set(arrayList.indexOf(item), item);
} else {
//otherwise add the new one
arrayList.add(item);
}
//assuming your data is mutable
arrayAdapter.notifyDataSetChanged();
}
Use ChildEventListener instead of ValueEventListener.ChildEventListener gives the following over methods,
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// here in dataSnapshot you will the detail for which the value is changed,using this you can update the list.
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
#Priya thanks a used a piece of your answer, the code now looks this way and it is doing what it should.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("userdata").child(myEmail);
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
if (dataSnapshot.getKey().equals("username")) {
username = (String) dataSnapshot.getValue();
arrayList.add("Username: " + username);
} else if (dataSnapshot.getKey().equals("age")) {
age = (String) dataSnapshot.getValue();
arrayList.add("Age: " + age);
} else if (dataSnapshot.getKey().equals("gender")) {
gender = (String) dataSnapshot.getValue();
arrayList.add("Gender: " + gender);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
if (dataSnapshot.getKey().equals("username")) {
username = (String) dataSnapshot.getValue();
arrayList.set(2, "Username: " + username);
} else if (dataSnapshot.getKey().equals("age")) {
age = (String) dataSnapshot.getValue();
arrayList.set(0, "Age: " + age);
} else if (dataSnapshot.getKey().equals("gender")) {
gender = (String) dataSnapshot.getValue();
arrayList.set(1, "Gender: " + gender);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Related
I have a chat application which is implemented using Firebase Realtime database entities only. No specific messaging components.
I'm adding a listener for the chat entity (or table) where the messages are stored. The listener is added by addChildEventListener which should call the onChildAdded method to bring all the children from chat entity in the moment it's attached and whenever a message is added.
The problem is that when I create the table, send the first message and attach the listener, I can see the table and message being created on the Firebase console, but the onChildAdded method is not called but a lot of time later. Then, as soon as it is called, sometimes more than 5 minutes later, I'm able to send and receive the messages as expected.
What could be causing this long delay?
I already tried to set the listener right after creating the table it listens to, but didn't work.
Creating the chat entity (table)
final DatabaseReference chat = dbReference.child("chat");
final DatabaseReference user = dbReference.child("user");
chatId = chat.push().getKey();
Log.d("mymessages", "createChat(), chatId = " + chatId);
HashMap newChatMap = new HashMap();
newChatMap.put("id", chatId);
newChatMap.put("users/" + currentUserId, true);
newChatMap.put("users/" + userId, true);
// Creating chats table
chat.child(chatId)
.child("info")
.updateChildren(newChatMap);
Log.d("mymessages", "Chat table created.");
Creating the message and inserting it in the chat entity
DatabaseReference newMessageDb = dbReference.child("chat").child(chatId).push();
Log.d("mymessages", "message created.");
Map newMessageMap = new HashMap<>();
newMessageMap.put("text", editTextMessage);
newMessageMap.put("creator", currentUserId);
newMessageDb.updateChildren(newMessageMap);
Log.d("mymessages", "message's text and creator added.");
Adding the listener
dbReference.child("chat").child(chatId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()) {
\\Fetch the messages...
} else {
Log.d("mymessages", "fetchChatMessages(), dataSnapshot does not exists.");
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Entire code that runs inside the button that sends the message
String editTextMessage = messageBodyEditText.getText().toString();
if (!editTextMessage.isEmpty()) {
if (!chatExists) {
final DatabaseReference chat = dbReference.child("chat");
final DatabaseReference user = dbReference.child("user");
chatId = chat.push().getKey();
HashMap newChatMap = new HashMap();
newChatMap.put("id", chatId);
newChatMap.put("users/" + currentUserId, true);
newChatMap.put("users/" + userId, true);
// Creating chats table
chat.child(chatId)
.child("info")
.updateChildren(newChatMap);
//Inserting the contact's id in the current user's chat table
HashMap newUserChatMap = new HashMap();
newUserChatMap.put(chatId + "/contact", userId);
user.child(currentUserId)
.child("chat")
.updateChildren(newUserChatMap);
//Inserting the current user's id in the contact's chat table
HashMap newContactChatMap = new HashMap();
newContactChatMap.put(chatId + "/contact", currentUserId);
user.child(userId)
.child("chat")
.updateChildren(newContactChatMap);
chatExists = true;
newChatCreated = true;
}
if (chatId != null) {
DatabaseReference newMessageDb = dbReference.child("chat").child(chatId).push();
Map newMessageMap = new HashMap<>();
newMessageMap.put("text", editTextMessage);
newMessageMap.put("creator", currentUserId);
newMessageDb.updateChildren(newMessageMap);
messageBodyEditText.setText("");
if (messageList.isEmpty()) {
if (chatExists) {
if (ConnectivityHelper.isConnectedToNetwork(this)) {
dbReference.child("chat").child(chatId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
loadingMessages.setVisibility(View.VISIBLE);
loadingWarning.setVisibility(View.VISIBLE);
loadingWarning.setText("Loading messages...");
if (dataSnapshot.exists() && !dataSnapshot.getKey().equals("info")) {
loadingWarning.setText("Loading messages...");
String text = "";
String creatorId = "";
Object newText = dataSnapshot.child("text").getValue();
Object newCreatorId = dataSnapshot.child("creator").getValue();
if (newText != null) {
text = newText.toString();
}
if (newCreatorId != null) {
creatorId = newCreatorId.toString();
}
String creatorName = "";
if (!creatorId.equals(currentUserId))
creatorName = userName;
else
creatorName = creatorId;
Message message = new Message(dataSnapshot.getKey(), creatorName, text);
messageList.add(message);
messagesAdapter.notifyDataSetChanged();
recyclerView.smoothScrollToPosition(messagesAdapter.getItemCount() - 1);
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setVisibility(View.INVISIBLE);
sendButton.setVisibility(View.VISIBLE);
} else {
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setText("Messages not found. \nCould not load your messages :/");
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists())
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setText("Loading cancelled. \nCould not load your messages :/");
Log.d("mymessages", "fetchChatMessages(), onCancelled called.");
}
});
} else {
lyNoConnection.setVisibility(View.VISIBLE);
Log.d("mymessages", "Not connected to network.");
}
} else {
loadingMessages.setVisibility(View.INVISIBLE);
loadingWarning.setVisibility(View.INVISIBLE);
sendButton.setVisibility(View.VISIBLE);
}
}
} else {
Log.d("mymessages", "chatId = null");
}
}
I want to connect the user id with the same key in Users, then show the key to FirebaseRecyclerAdapter. I get the key in Friend child already but don't know how to match this to Users.
And my code:
mFriendList = FirebaseDatabase.getInstance().getReference().child("Friends").child(current_id);
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mFriendList.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String sd = snapshot.getKey(); //key from Friends
final FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder>(
Users_Friends.class,
R.layout.users_single_friend_layout,
UsersFriendViewHolder.class,
filter
) {
#Override
protected void populateViewHolder(UsersFriendViewHolder viewHolder, Users_Friends users, int position) {
viewHolder.setDisplayName(users.getName());
viewHolder.setStatusUsers(users.getStatus());
viewHolder.setUserImage(users.getImage(), getContext().getApplicationContext());
final String user_id = getRef(position).getKey();
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
}
};
mReqList.setAdapter(firebaseRecyclerAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You only need to use exists() method directly on the dataSnapshot object like this:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(current_id).exists()) {
Log.d("TAG", "User exists");
} else {
Log.d("TAG", "User does not exist");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mFriendDatabase.addListenerForSingleValueEvent(eventListener);
I have a function which write data into database
private void startCommenting() {
final String comment_val = meditComment.getText().toString().trim();
meditComment.setText("");
if (!TextUtils.isEmpty(comment_val)) {
mProgress.show();
final DatabaseReference newPost = mComment.child(post_key).push();
final String commentkey = newPost.getKey();
mUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String,Object> checkoutData=new HashMap<>();
checkoutData.put("time",ServerValue.TIMESTAMP);
newPost.setValue(checkoutData);
newPost.child("comment").setValue(comment_val);
newPost.child("uid").setValue(dataSnapshot.child("id").getValue());
newPost.child("blogpost").setValue(dataSnapshot.child("blogkey").getValue());
newPost.child("userimage").setValue(dataSnapshot.child("image").getValue());
newPost.child("username").setValue(dataSnapshot.child("name").getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
After this function was called, a Query was made to get the data which contains the right post_key in the child ("blogpost").
mpostComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startCommenting();
mQueryCurrentComment = mComment.child(post_key).orderByChild("blogpost").equalTo(post_key);
mQueryCurrentComment.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String currentuserid;
String lastuserid = "";
String currentcommentuid;
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
currentuserid = dsp.child("uid").getValue().toString();
Log.d(TAG, "user newid: " + currentuserid);
Log.d(TAG, "user oldid: " + lastuserid);
if (currentuserid.equals(lastuserid)) {
} else {
final DatabaseReference newCommentLike = mComment.child(currentuserid).push();
Map<String, Object> checkTime = new HashMap<>();
checkTime.put("time", ServerValue.TIMESTAMP);
newCommentLike.setValue(checkTime);
newCommentLike.child("location").setValue(location_key);
newCommentLike.child("category").setValue(category_key);
newCommentLike.child("pressed").setValue("false");
newCommentLike.child("message").setValue(" has also commented your post. ");
newCommentLike.child("blogpost").setValue(post_key);
newCommentLike.child(post_key).setValue(true);
}
lastuserid = currentuserid;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
However, the Query was triggered twice, one before the new item was added, another after new item was added, which looks like below:
How can I only perform the actions inside Query after the newest item was added and not twice? Any help is appreciated!
My Firebase Database is look like as bellow:
I want to show an error message when email val is not available in firebase database.
And my code is
mRef.orderByChild("email").equalTo(val).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
textView.setText("Welcome " + user.name );
System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
textView.setText("Welcome " + user.name );
System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
A ChildEventListener can only detect the presence of a certain child node or when a child node is changed/removed. It cannot detect the absence of a child. To detect that there is no value, you need a ValueEventListener:
mRef.orderByChild("email").equalTo(val).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() == 0) {
System.out.println("No user with email "+val);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
throw firebaseError.toException(); // don't ignore onCancelled!
}
});
mQuery = databaseReference.limitToLast(1).orderByChild("email").equalTo(category);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "onDataChange: "+dataSnapshot.toString());
GenericTypeIndicator<Map<String,UserModel>> t=new GenericTypeIndicator<Map<String,UserModel>>(){};
try{
Map<String,UserModel> userList=dataSnapshot.getValue(t);
}catch(Exception exception){
//Error UserInfo not present in firebase
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Error wile accessing database
}
});
Using Firebase Database.
I have a database which stores the registration information for patients.
While registering a new patient, i'm checking whether the person is already registered or not.
The function below checks if a registration for that person is already made or not.
I'm checking this by going to "Users/Phone_no/Patient_name".
If the DataSnapshot is not null registration is already there.
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];
}
From saveInDatabase i'm calling the above function
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);
.
.
}
What i want to do- Check if a registration based on phone_no/Patient_name is already made or not, if not save the details.
Problem - When a new registration is made it is added to the database, but after that the message "..Already registered", from checkAlreadyRegistered() ->onDataChange is displayed.
Why is that message coming, and how solve it?
All data reading in Firebase happens asynchronously, so I recommend you change your code to something that looks like this:
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();
}
});
}
And your save method:
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);
.
.
}
You have to wait for the response from Firebase. You can add a Callback to run the rest of your code once it's been retrieved. Do something like this:
Create an interface called ServerCallback:
public interface ServerCallback
{
void onSuccess(boolean result);
}
In your checkAlreadyRegistered() method, add the callback so it runs once the data is retrieved from 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();
}
});
}
Then in your saveInDatabase(), wait for the callback, then run the rest of your code:
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);
.
.
});
}