Database not update the value - android

I am trying to make a social app .. and I want when the user clicks the edit category database should be updated to the new value .. but it is like static not changing to new value .. I don't know the problem in logic or in the code ..
private void showCategoryUpdateDialog(String Key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("تغيير " + Key);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(15, 10, 15, 10);
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("علمي علوم");
RadioButton radioButton2 = new RadioButton(getActivity());
radioButton2.setText("علمي رياضة");
RadioButton radioButton3 = new RadioButton(getActivity());
radioButton3.setText("أدبي");
linearLayout.addView(radioButton);
linearLayout.addView(radioButton2);
linearLayout.addView(radioButton3);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value = radioButton.getText().toString().trim();
String value2 = radioButton2.getText().toString().trim();
String value3 = radioButton3.getText().toString().trim();
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(Key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
if (!TextUtils.isEmpty(value2)) {
pd.show();
HashMap<String, Object> result2 = new HashMap<>();
result2.put(Key, value2);
databaseReference.child(user.getUid()).updateChildren(result2)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
if (!TextUtils.isEmpty(value3)) {
pd.show();
HashMap<String, Object> result3 = new HashMap<>();
result3.put(Key, value3);
databaseReference.child(user.getUid()).updateChildren(result3)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
In this picture have more details
Emulator
And this GIF from my Database
https://media.giphy.com/media/ZY36QuzJsdXIhIQh7k/giphy.gif

first: make sure that the new value is stored in the database (from the console)
second: after the update is completed onCompleteListener get the data again.
you can listen for this field changes in real-time which could be better than getting the data after every update.

Related

Unable to Refresh the RecyclerView after deleteing an Item

I am successfully deleting an Item from the recyclerView. The Items gets deleted successfully, but the recyclerView is not refreshed after the delete operation.
This is my Adapter code :
holder.removeProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences myPrefs = context.getSharedPreferences("loginToken", Context.MODE_PRIVATE);
getToken = myPrefs.getString("token", null);
new AlertDialog.Builder(context)
.setTitle("Remove from Cart")
.setMessage("Are you sure you want to remove this Item from cart ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteDialog = ProgressDialog.show(context, "",
"Please Wait...", true);
final RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST,
REMOVE_CART_URL + "?token=" + getToken + "&product_id=" + cartModel.getProductid()
, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("success");
if (message.equals("true")) {
Toast.makeText(context, "Item Deleted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Delete error", e.getLocalizedMessage());
}
deleteDialog.dismiss();
notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
deleteDialog.dismiss();
}
});
requestQueue.add(request);
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_delete)
.show();
}
});
The Item after deletion stays there until I close the App and reopen. How do I fix this , so I dont have to reopen app everytime.
Instead of notifyDataSetChanged() write this code:
if (yourAdapterList.size() > 0) {
ourAdapterList.remove(position);
notifyItemRemoved(position);
}

Android Studıo E/AndroidRuntime: FATAL EXCEPTION: main

My error;
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.melikerdemkoc.myvetapp/com.melikerdemkoc.myvetapp.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a
null object reference
My code;
import javax.annotation.Nullable;
public class MainActivity extends AppCompatActivity {
private static final int GALLERY_INTENT_CODE = 1023 ;
TextView fullName,email,phone,verifyMsg;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String userId;
Button resendCode;
Button resetPassLocal,changeProfileImage;
FirebaseUser user;
ImageView profileImage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.profilePhone);
fullName = findViewById(R.id.profileName);
email = findViewById(R.id.profileEmail);
resetPassLocal = findViewById(R.id.resetPasswordLocal);
profileImage = findViewById(R.id.profileImage);
changeProfileImage = findViewById(R.id.changeProfile);
FirebaseApp.initializeApp(this);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 6 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(), com.melikerdemkoc.myvetapp.EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
//
}
});
}
.
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(), com.melikerdemkoc.myvetapp.Login.class));
finish();
}
}
I wanna start my app using the firebase database but ı cant do that when ı start the app; my app is crashing.
don't read;
I'm writing because I can't post my questionI'm writing because I can't post my question
Problem
Seems your trying to access a current user does not exist.
Possible Solution
Try checking if user is signed in else should not run the code which needs the current user confirmation.
Here is your refined code.
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.profilePhone);
....
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
if (fAuth.getCurrentUser() != null) {
verifyUser();
}
else {
Log.d("tag", "The user is not authenticated");
}
}
verifyUser Method
public void verifyUser()
{
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 6 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(), com.melikerdemkoc.myvetapp.EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
}
});
}
Hope it solves the problem.

Parse objects are not deleting

I am using parse as baas , I was using below code to delete objects .But tommorow i came to know that this piece of code is not working .
#Override
public void onClick(View view) {
new AlertDialog.Builder(context).setIcon(R.drawable.main).setTitle("Delete this product ?")
.setMessage("Are you sure you want to Delete this product ?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("VendorInv");
query.whereEqualTo("objectId", details.getObjectId());
query.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
try {
object.delete(); // fixed part
object.saveInBackground(new SaveCallback() { // fixed part
#Override
public void done(ParseException e) {
if (e == null) {
vendorDetailsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, vendorDetailsList.size());
count.setText(String.valueOf(vendorDetailsList.size()) + "/" + totalNo + " items are Online");
Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
}
}
});
} catch (ParseException e1) {
Log.i("sand", e1.toString());
}
}
});
}
}).setNegativeButton("No", null).show();
}
});
}
Then as a contributor of parse android said than i fixed this part of code below
holder.cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(context).setIcon(R.drawable.main).setTitle("Delete this product ?")
.setMessage("Are you sure you want to Delete this product ?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("VendorInv");
query.whereEqualTo("objectId", vendorDetailsList.get(position).getObjectId());
query.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
/* this part is changed */ object.deleteInBackground(new DeleteCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("sand", vendorDetailsList.get(position).getObjectId());
vendorDetailsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, vendorDetailsList.size());
count.setText(String.valueOf(vendorDetailsList.size()) + "/" + totalNo + " items are Online");
Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Not Deleted please check your network connection", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}).setNegativeButton("No", null).show();
}
});
Toast is printing deleted but still object is not deleted in database.
I dont know where i am going wrong, but this is not helping me in deleting an object
Any help would be greatly appreciated
Config your class VendorInv on the server to be "Public Read and Write enabled"
and use next code:
ParseQuery<ParseObject> query = ParseQuery.getQuery("VendorInv");
query.getInBackground(vendorDetailsList.get(position).getObjectId(), new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (object != null) {
object.deleteInBackground(new DeleteCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("sand", vendorDetailsList.get(position).getObjectId());
vendorDetailsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, vendorDetailsList.size());
count.setText(String.valueOf(vendorDetailsList.size()) + "/" + totalNo + " items are Online");
Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Not Deleted please check your network connection", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});

Function addListenerForSingleValueEvent from firebase

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);
.
.
});
}

Items Update on second click

I am working on a project in which we enter an email and that is checked with the emails present in different tables of the database. Depending upon tables in which the entered email is present I want to display a list of check boxes in a dialog box on clicking a button. My problem is the names of check boxes get updated only on the second click and on further clicks the order of names change. I am not able to figure out this and spent many hours in same. Please help!
MainActivity.java
public class MainActivity extends AppCompatActivity {
public EditText et;
public Main2Activity act;
private String s;
private String[] st = {"","",""};
private int i,j;
private Boolean x;
private String url1 = "http://192.168.56.1:80/axis/results.json";
private String url2 = "http://192.168.56.1:80/hdfc/results.json";
private String url3 = "http://192.168.56.1:80/sbi/results.json";
private ProgressDialog pDialog;
private static String TAG = MainActivity.class.getSimpleName();
private String[] items= {"","",""};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//mail entered into the edittext
et = (EditText)findViewById(R.id.editText);
j=0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// on click
public void makeJsonArrayRequest(View view) {
j=0;
s=et.getText().toString();//email to string
JsonArrayRequest req1 = new JsonArrayRequest(url1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("Axis");
//if present in the table add to list
addItem("AXIS");
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
JsonArrayRequest req2 = new JsonArrayRequest(url2,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)) {
System.out.println("HDFC");
addItem("HDFC");
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
JsonArrayRequest req3 = new JsonArrayRequest(url3,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("SBI");
addItem("SBI");}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(req1);
AppController.getInstance().addToRequestQueue(req2);
AppController.getInstance().addToRequestQueue(req3);
dialogadd();
}
public void addItem(String s)
{
items[j]=s;
j++;
}
public void dialogadd()
{
Dialog dialog;
final ArrayList itemsSelected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select banks you want to connect to: ");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
})
.setPositiveButton("Done!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Your logic when OK button is clicked
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();}
}
here is the log cat
logcat
on first click
on second click
on third click
AppController.getInstance().addToRequestQueue(req1); // this will take some time get data
AppController.getInstance().addToRequestQueue(req2); // even this will take some time get data
AppController.getInstance().addToRequestQueue(req3); //last this also will take some time get data
dialogadd(); // but this is an instant call. which will show the dialog, since previous all three call are pending your data get shown unless they complete.
solution : use below call to show the dialog
JsonArrayRequest req3 = new JsonArrayRequest(url3,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("SBI");
addItem("SBI");}
// use this last call show dialog
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Advice
use Future request in volley, i think wt you need is synchronous call one after another

Categories

Resources