How to Subtract two different node child values in Firebase Realtime Databse? - java

I'm creating a Food ordering app.for that I'm saving the food names into the Food unique ID. So I created Item Details as a node, in this node has shopuniqueID as a child node, in this node has food uniqueID
this ID contains food details such as discount,itemname,price,discount If the User book the foods, which will be saved as below format
, If the customer confirms the food order after that user-selected quantity wants to delete from total item quantity, How can I delete two different values which are in the two different nodes?
This is my tried coding
btnorder=findViewById(R.id.qrbillid);
databaseReference= FirebaseDatabase.getInstance().getReference("User Booking").child(UserID).child(shopid);
dbrefcheck=FirebaseDatabase.getInstance().getReference("Item Details").child(shopid);
btnorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
SelectedItems ui=dataSnapshot1.getValue(SelectedItems.class);
final String itemid=ui.getItemid();
final String Stritemselectedqty=ui.getItemid();
final String name=ui.getItemname();
///////////////////----find the user selection----////////////////////
dbrefcheck.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot2:dataSnapshot.getChildren())
{
UploadItem uploadItem=dataSnapshot2.getValue(UploadItem.class);
String uploadItemID=uploadItem.getKey();
String StrTotalqty=uploadItem.getQuantity();
if(itemid.equals(uploadItemID))
{
// do the mathematical operation
int totalqty=Integer.valueOf(StrTotalqty);
int selectedqty=Integer.valueOf(Stritemselectedqty);
int finalquality=totalqty-selectedqty;
Toast.makeText(MyBookedItems.this, ""+name+" ", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
///////////////////----find the user selection----////////////////////
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});

If We want to do mathematical operations between two node child values, We can't directly do that in Firebase Realtime Database.
Retrieve the value from the Firebase
after that do the modification and again upload it.
private void updateQuantity(final String itemid, final String selecteditem) {
Query query4 = dbrefcheck
.orderByChild("key") //key
.equalTo(itemid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String qty=ds.child("quantity").getValue(String.class);
int total=Integer.valueOf(qty);
int sub=Integer.valueOf(selecteditem);
int fv=total-sub;
String sfv=String.valueOf(fv);
Map<String, Object> map = new HashMap<>();
map.put("quantity", sfv);
dbrefcheck.child(itemid).updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
query4.addListenerForSingleValueEvent(valueEventListener);
}
private void moveSelectedItemstoOrder(final DatabaseReference fromPath, final DatabaseReference toPath) {
final String th=toPath.push().getKey();
fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
toPath.child(th).setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
if (firebaseError != null) {
Toast.makeText(MyBookedItems.this, "Try again", Toast.LENGTH_SHORT).show();
} else {
StoreBookingDetails(th);
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void DeleteValuefromSelectedItems() {
databaseReference.setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
private void StoreBookingDetails(final String keytostore) {
//////////////////------------retrive data-------------//////////////////////////////some these methods are unnecessary but i remove some code
savedata(keytostore);
//////////////////------------retrive data-------------//////////////////////////////
}
private void savedata(String keytostore) {
String status="Order Request";
// shopid ---->
BookingDetails bd=new BookingDetails(keytostore,currentdate,UserID,subtotal,status,f1,f2,f3,currentTime);
dbbookingDetails.child(keytostore).setValue(bd).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
DeleteValuefromSelectedItems();
}else
{
Toast.makeText(MyBookedItems.this, "Check the intenet connection", Toast.LENGTH_SHORT).show();
}
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
/////////////////////////////--------------------/////////////////////////////////
UserBookingDetails ubd=new UserBookingDetails(shopname,shopid,shopphnno,keytostore,UserID,subtotal,currentdate,currentTime,"Order Sent","","");
dbbookingdetailsUser.child(keytostore).setValue(ubd).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
AlertDialog.Builder adb = new AlertDialog.Builder(MyBookedItems.this);
adb.setTitle("Booking Successful");
adb.setPositiveButton("View History", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(MyBookedItems.this,OrderHistory.class));
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
adb.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});

Related

Selecting in RecyclerView and delete from firebase in java

I want to delete my document from firebase. But first I need to determine the document id. I tried to get document id:
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
Then, I just wanted to delete my document. But firebase works async so code doesnt work in 'if' statement. When we first click the button, docId variable is null or it takes the docId which was clicked before till the async code part done.
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
}
}
});
System.out.println(docId);
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
notifyDataSetChanged();
}
});
You should structure your code so that any logic that depends on your asynchronous operation is executed or triggered within the response callback.
You can do something like this:
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
// The asynchronous operation has successfully completed
// and returned a value to our 'onSuccess()' callback.
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
System.out.println(docId);
// We can now use the value of docId.
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
// (1)
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
// I'm not sure how your RecyclerView is set up
// but I'm guessing you might want to move this call
// to 'notifyDataSetChanged()' to the section marked (1)
notifyDataSetChanged();
}
}
});
}
});
}

Firebase .removeValue() adds deleted element automatically

So I'm new to firebase and i have a problem with the method .removeValue(), everytime that method is executed the addOnCompleteListener does not throw any exceptions and execute the .removeValue() method correctly by removing the element but the element keeps adding by itself after the deletion,
I'm trying to do a friend's list where i check the condition if there is a friend request or is the 2 users are actually friends, So i wrote this code on the onStart method to assign the stats variable a value according to these conditions:
#Override
protected void onStart() {
super.onStart();
if(profileUid.equals(userId)){
sendAccept.setVisibility(View.INVISIBLE);
}else {
friendDatabaseReference.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String status = dataSnapshot.child("Status").getValue().toString();
if (status.equals("recieved")) {
sendAccept.setVisibility(View.VISIBLE);
sendAccept.setText("Accept Request");
cancelRequest.setText("Cancel friend Request");
cancelRequest.setVisibility(View.VISIBLE);
stats = "recieved";
} else if (status.equals("sent")) {
stats = "sent";
sendAccept.setText("Cancel Friend Request");
}
} else {
friendDatabaseReference1.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
stats = "friends";
sendAccept.setText("UnFriend");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Everything runs well there and the values are assigned correctly. After that depending of the value of stats these conditions can happen(These sendAccept.setOnClickistener()) is on the onCreate() method:
sendAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (stats.equals("none")) {
friendDatabaseReference.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
friendDatabaseReference.child(userId).child(profileUid).child("Status").setValue("sent").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
friendDatabaseReference.child(profileUid).child(userId).child("Status").setValue("recieved").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
stats = "sent";
sendAccept.setText("Cancel Friend Request");
}
}
});
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else if(stats.equals("recieved")){
friendDatabaseReference1.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
friendDatabaseReference1.child(userId).child(profileUid).child("friends").setValue("yes")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference1.child(profileUid).child(userId).child("friends").setValue("yes")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
stats = "friends";
sendAccept.setText("Unfriend");
cancelRequest.setVisibility(View.INVISIBLE);
friendDatabaseReference.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
friendDatabaseReference.child(profileUid).child(userId)
.removeValue().addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
}
});
}
}
});
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else if(stats.equals("sent")){
friendDatabaseReference.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference.child(profileUid).child(userId).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
stats = "none";
sendAccept.setText("Send Friend Request");
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Asi que prende", Toast.LENGTH_LONG).show();
}
}
});
}
}
});
}else{
friendDatabaseReference1.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference1.child(profileUid).child(userId).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
sendAccept.setText("Send Friend Request");
stats = "none";
}
});
}
}
});
}
}
});
These are my declared instances of FirebaseDatabase where i point out where the data will be or will be removed(these are also on the onCreate() method:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
friendDatabaseReference = FirebaseDatabase.getInstance().getReference().child("friend_req");
friendDatabaseReference1 = FirebaseDatabase.getInstance().getReference().child("Friends");
The conditions don't throw any errors nor exceptions, and all the assigns are working well and finally the firebase deletes the record, but add it again after the deletion

Get data from firebase from a specific position

Hy, I'm writing an application that has to get specific data from firebase using the position of the item in the listView. My problem is that I have no idea how to take it this item on firebase.
For all child of Torneo I have to control all the nameCreator.
I have tried this:
public Boolean RegisterUser(Data data, final int position, final Context c){
boolean registration;
final ArrayList<String> Creator = new ArrayList<>();
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(data.child("nameCreator").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
return registration;
}
Data is a class with some getter and setter that I have created.
position is the position of the element on the list view.
Thanks for answers.
Change the following:
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
into this:
databaseReference.child("Tornei").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(datas.child("nameCreator").getValue().toString());
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Then you will be able to loop and retrieve the value of nameCreator
It's easy.
【Step 1 | Get Snapshot Data and Save in Global Variable】
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference fruitsReference = rootReference.child("fruits");
DataSnapshot fruitsData;
#Override
protected void onStart() {
super.onStart();
fruitsReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshots) {
fruitsData = dataSnapshots;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
【Step 2 | Find Your Target Position through the Loop】
public void onClick(View view) {
int index = 0;
for (DataSnapshot childSnapshot : fruitsData.getChildren()) {
if (index == 1) { //your target position
DatabaseReference currentFruitReference = childSnapshot.getRef();
currentFruitReference.setValue("peach"); //do whatever you want
}
index++;
}
}

How to retrieve the values of "Total"

This is my firebase database structure.
I want to fetch the values of "Total" of all children of "Bill". I have tried to fetch the data but my code is not working. Here is my code.
DatabaseReference billReference = FirebaseDatabase.getInstance().getReference().child("Bill");
billReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
fetchCount++;
Toast.makeText(getApplicationContext(),""+keys[i],Toast.LENGTH_LONG).show();
String temp = ds.child(keys[i]).child("Breakfast").child("11-2018").child("Total").getValue().toString();
breakfastBills.add(names[i] + " : " + temp);
i++;
}
if (fetchCount == 4) {
AlertDialog.Builder builder = new AlertDialog.Builder(bill_details_manager.this);
builder.setTitle("Bill Details for Breakfast");
builder.setItems(breakfastBills.toArray(new String[breakfastBills.size()]), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
progressDialog.dismiss();
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
What is wrong with this code ?
DatabaseReference billRef = FirebaseDatabase.getInstance().getReference();
billRef.child("Bill").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot allValueSnap) {
for (DataSnapshot snapshot: allValueSnap.getChildren()){
String key = snapshot.getKey();
if (key != null) {
billRef.child("Bill").child(key).child("Breakfast").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot keySnapshot) {
for (DataSnapshot dateSnapshot:keySnapshot.getChildren()){
String keyDate = dateSnapshot.getKey();
long totalValue =(long) keySnapshot.child(keyDate).child("Total").getValue();
Log.i("totalBreakFast","STotal: "+String.valueOf(totalValue));
breakfastBills.add(totalValue);
}
if(!keySnapshot.exists()){
Log.i("totalBreakFast","NoData: ");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This code is getting all values of "Total".

can't get to second activity after spots dialog "keep's on loading"

can't get to second activity after spots dialog "keep's on loading" on my main activity and can load for hours without error i use facebook acount kit i dont see the error out here is the main activity source code
main activity java :
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1000;
Button btnContinue;
RelativeLayout rootLayout;
FirebaseAuth auth;
FirebaseDatabase db;
DatabaseReference users;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//bf4 set context view
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
printKeyHash();
//Init Firebase
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
users = db.getReference(Common.user_driver_tbl);
//init view
btnContinue = (Button)findViewById(R.id.btnContinue);
rootLayout =(RelativeLayout)findViewById(R.id.rootLayout);
//Event
btnContinue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signInwithPhone();
}
});
//auto login to facebook act kit for second time
if (AccountKit.getCurrentAccessToken() != null)
{
//create dialog
final AlertDialog waitingDialog = new SpotsDialog(this);
waitingDialog.show();
waitingDialog.setMessage("Please waiting....");
waitingDialog.setCancelable(false);
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
//copy from exiting user
users.child(account.getId())//fixed
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
Intent homeIntent = new Intent(MainActivity.this,DriverHome.class);
startActivity(homeIntent);
//Dismiss dialog
waitingDialog.dismiss();
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
}
private void signInwithPhone() {
Intent intent = new Intent(MainActivity.this, AccountKitActivity.class);
AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
new AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
AccountKitActivity.ResponseType.TOKEN);
intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,configurationBuilder.build());
startActivityForResult(intent,REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE)
{
AccountKitLoginResult result = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
if (result.getError() !=null)
{
Toast.makeText(this, ""+result.getError().getErrorType().getMessage(), Toast.LENGTH_SHORT).show();
return;
}
else if (result.wasCancelled())
{
Toast.makeText(this, "Cancel login", Toast.LENGTH_SHORT).show();
return;
}
else{
if (result.getAccessToken() !=null)
{
//Show dialog
final AlertDialog waitingDialog = new SpotsDialog(this);
waitingDialog.show();
waitingDialog.setMessage("Please waiting....");
waitingDialog.setCancelable(false);
//get current phone
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(final Account account) {
final String userId = account.getId();
//check if exist on firebase
users.orderByKey().equalTo(account.getId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(account.getId()).exists())//if not exits
{
//will we create new user login
final User user = new User();
user.setPhone(account.getPhoneNumber().toString());
user.setName(account.getPhoneNumber().toString());
user.setAvatarUrl("");
user.setRates("0.0");
//Register to Firebase
users.child(account.getId())
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//Login
users.child(account.getId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
Intent homeIntent = new Intent(MainActivity.this,DriverHome.class);
startActivity(homeIntent);
//Dismiss dialog
waitingDialog.dismiss();
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else //if user existing ,login
{
users.child(account.getId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
Intent homeIntent = new Intent(MainActivity.this,DriverHome.class);
startActivity(homeIntent);
//Dismiss dialog
waitingDialog.dismiss();
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
Toast.makeText(MainActivity.this, ""+accountKitError.getErrorType().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
private void printKeyHash() {
try{
PackageInfo info = getPackageManager().getPackageInfo("com.example.rd.androidapp",
PackageManager.GET_SIGNATURES);
for (Signature signature:info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KEYHASH", Base64.encodeToString(md.digest(),Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
if more is needed !!! or is there something lacking also i am still new in android programing so ...
Try to uses dismiss the dialog in onCancel and onError method and print error for discretion.

Categories