I can't read data from Transactions - android

When send user data to firestore and login again the system not read this code , he join already to (if) after add data but return failed because I think firestore accept write only is there any solution?
if (snapshot.exists()) {
return snapshot.getString("ID");
}
Code
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
DocumentReference documentReference = firebaseFirestore.collection("Players").document(saveSystem.LoadStringData("LoginType").equals("Facebook") ? "F" + saveSystem.LoadStringData("ID") : "G" + saveSystem.LoadStringData("ID"));
firebaseFirestore.runTransaction(new Transaction.Function<Object>() {
#Override
public Object apply(Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(documentReference);
if (snapshot.exists()) {
return snapshot.getString("ID");
} else {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("ID", saveSystem.LoadStringData("ID"));
return hashMap;
}
}
}).addOnSuccessListener(new OnSuccessListener<Object>() {
#Override
public void onSuccess(Object aObject) {
Toast.makeText(Test.this, "" + aObject, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Sorry for simple English language.

Related

firestore keep updating in infinite loop

I just want to update the count table one time but it keeps updating in the infinite loop can someone help me with this.
referral_code=referral_editText.getText().toString();
db.collection(REFERRAL_CODE_KEY).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
assert queryDocumentSnapshots != null;
for(DocumentSnapshot documentSnapshots:queryDocumentSnapshots){
if(referral_code.equals(documentSnapshots.get(REFERRAL_CODE).toString()))
{
count = parseInt(String.valueOf(documentSnapshots.get(REFERRAL_COUNT)))+1;
Map<String, Object> referralCountDocData = new HashMap<>();
referralCountDocData.put(REFERRAL_COUNT,count);
klog.d("### referral",count+"");
db.collection(REFERRAL_CODE_KEY)
.document(documentSnapshots.getId())
.update(referralCountDocData).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
finish();
}
});
}
}
}
});
Maybe, you could do something like this not everythng is perfect but it gives you a nice idea.
oldCount-> you can read it from document.getData()
var docRef = db.collection(REFERRAL_CODE_KEY).doc(referral_code);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
//read oldCount here from document.getData()
Map<String, Object> docData= new HashMap<>();
docData.put(REFERRAL_COUNT, oldcount + 1);
docRef.set(docData)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
You can detach your listener, so that callback stop getting called.
As per official document https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener You need to use remove method to detach listener
Query query = db.collection("cities");
ListenerRegistration registration = query.addSnapshotListener(
new EventListener<QuerySnapshot>() {
// ...
});
// ...
// Stop listening to changes
registration.remove();

SignOut is making not possible to save in firestore

I'm making a signup activity for an app and something weird is happening can you help me?
this is the code for signup some on and it works if I comment the signOut function but I need it to signout after saving the data in the FirebaseAuth and the Firestore.
I don't get even the logs.
public void registUser() {
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(user.getEmail(), user.getPassword()).addOnCompleteListener(SignUpUserActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpUserActivity.this, "Sucesso", Toast.LENGTH_SHORT).show();
// Sign in success, update UI with the signed-in user's information
//FirebaseUser user = mAuth.getCurrentUser();
user.setId(task.getResult().getUser().getUid());
user.save();
mAuth.signOut();
finish();
} else {
String erro = "";
try {
throw task.getException();
} catch (FirebaseAuthWeakPasswordException e) {
erro = "Digite uma senha mais forte";
} catch (FirebaseAuthInvalidCredentialsException e) {
erro = "Email invalido";
} catch (FirebaseAuthUserCollisionException e) {
erro = "Email Registado";
} catch (Exception e) {
erro = "Erro generico";
e.printStackTrace();
}
Toast.makeText(SignUpUserActivity.this, erro, Toast.LENGTH_SHORT).show();
}
}
});
}
I think its because it takes to long to save things in the database.
I have no problems with the Auth part.
Thank you.
this is the save function.
public void save(){
DocumentReference reference = FirebaseFirestore.getInstance().document("/Clinicas/" + clinic + "/Profissionais/" + id + "/");
Map<String, Object> dataToSave = new HashMap<String, Object>();
dataToSave.put("Name", name);
dataToSave.put("email", email);
dataToSave.put("clinic", clinic);
dataToSave.put("Job", job);
reference.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("artur", "Saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("artur", "Not Saved",e);
}
});
}
To sovle this, please use the following code:
user.setId(task.getResult().getUser().getUid());
userRef.set(user).addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
mAuth.signOut();
}
});
When you sign-out, you need to be sure that your write operation is done and this can only be achieved using addOnSuccessListener.
public void save(){
DocumentReference reference = FirebaseFirestore.getInstance().document("/Clinicas/" + clinic + "/Profissionais/" + id + "/");
Map<String, Object> dataToSave = new HashMap<String, Object>();
dataToSave.put("Name", name);
dataToSave.put("email", email);
dataToSave.put("clinic", clinic);
dataToSave.put("Job", job);
reference.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("artur", "Saved");
mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("artur", "Not Saved",e);
}
});
}

Firebase get error when data is null from database

FirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
name = snapshot.child("username").getValue().toString();
String myUrl = snapshot.child("photoURL").getValue().toString();
txtFullName.setText(name);
txtWelcome.setText("Hoşgeldin " + name);
if(myUrl.isEmpty()) {
changePhotoWithName(name);
}
else {
changePhoto(myUrl);
}
}
}
Here my code, with FirebaseRef listennig database and retrive data , but the problem is that sametimes my data is null and getting error.
FirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if(snapshot.exists()){
name = snapshot.child("username").getValue().toString();
String myUrl = snapshot.child("photoURL").getValue().toString();
txtFullName.setText(name);
txtWelcome.setText("Hoşgeldin " + name);
if(myUrl.isEmpty()){
changePhotoWithName(name);
}
else {
changePhoto(myUrl);
}
}
}
try this..
if(myUrl.length()>0){
if(myUrl.isEmpty()){
changePhotoWithName(name);
}
else {
changePhoto(myUrl);
}
}

How do I read the Data from a value from my Firebase?

So reading from my Firebase database seen here by using the following code I have managed to get a 'data snapshot' of the first item in my database:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("messages");
myRef.orderByPriority().limitToFirst(1).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e("data:", ""+dataSnapshot.getChildren());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "The read failed: " );
}
});
This returns:
datasnapshot: "DataSnapshot {key = message, value = {ygmailcom100={name=tom, message=kys, email=y#gmail.com}} }"
My question is now what...how do I access these different bits of data(name, msg, email(also the parent of these three bits of data, the 'ygmailcom100 'bit)) and put their data into strings. Also once i have read the data to strings how do i go about deleting that value from the message key.
I apologise for my ignorance as i am new to software development but any insight will be much appreciated.
You can create a Model class and map the value to your model class.
You can refer this code.
Model Class: User.Java
public class User {
private String username;
private int accessLevel;
private boolean adminApproved;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(int accessLevel) {
this.accessLevel = accessLevel;
}
public boolean isAdminApproved() {
return adminApproved;
}
public void setAdminApproved(boolean adminApproved) {
this.adminApproved = adminApproved;
}
}
Mapping DataSnapshot value to POJO
mRef = new Firebase("<<FIREBASE_URI>>").child("<<CHILD_NODE_NAME>>");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
User expense = ds.getValue(User.class);
users.add(expense.getUsername());
}
adapter.notifyDataSetChanged();
}catch(Exception e){
Log.e("MODEL_ERROR","Error Occurred while mapping to model");
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("FIREBASE",firebaseError.getMessage());
}
});
Firebase DB User Data
"users" : {
"-KY0ZdsNNE1eDOTXdzaF" : {
"accessLevel" : 0,
"adminApproved" : false,
"username" : "dummyUser2"
}
}
Note: It is not a good practice to store User information in DB. Use this only as a reference.
Android firebase query with multiple orderBy
To get Parent
databasereference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<Map<String, HashMap<String, HashMap<String, String>>>> genericTypeIndicator = new GenericTypeIndicator<Map<String, HashMap<String, HashMap<String, String>>>>() {
};
Map<String, HashMap<String, HashMap<String, String>>> maps = dataSnapshot.getValue(genericTypeIndicator);
Object[] str = maps.keySet().toArray();
for (Object aStr : str) {
}
//adapter.notifyDataSetChanged();
//L.tmlong(getActivity(), Arrays.toString(maps.values().toArray()));
}
To get child, from parent get aStr and use child('messages/'+aStr)
databasereference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<Map<String, HashMap<String, String>>> genericTypeIndicator =
new GenericTypeIndicator<Map<String, HashMap<String, String>>>() {
};
Map<String, HashMap<String, String>> maps = dataSnapshot.getValue(genericTypeIndicator);
Object[] str = maps.keySet().toArray();
for (Object aStr : str) {
}
}
//adapter.notifyDataSetChanged();
//L.tmlong(getActivity(), Arrays.toString(maps.values().toArray()));
}

updateChildren not updating the children?

So I am checking whether the username exists or not during the sign up procedure. The only problem is that my childupdates2 is not being added to the Usernames folder? The first childUpdate is added properly but the second childUpdate2 doesn't. It just doesnt update my Usernames folder?
final DatabaseReference Userref = FirebaseDatabase.getInstance().getReference();
username_check_query = Userref.child("Usernames").orderByChild("username").equalTo(mUsernameView.getText().toString());
usernameChildEvent = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() == null){
ScoreClass scoreClass = new ScoreClass(10000, mUsernameView.getText().toString());
Map<String, Object> scoredata = scoreClass.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("Users/" + user.getUid(), scoredata);
Userref.updateChildren(childUpdates);
Username username = new Username(mUsernameView.getText().toString());
Map<String, Object> userdata = username.toMap();
Map<String, Object> childUpdates2 = new HashMap<>();
childUpdates2.put("/Usernames/" + user.getUid(), userdata);
Userref.updateChildren(childUpdates2);
}
else {
// other code
}
username_check_query.removeEventListener(this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
username_check_query.addListenerForSingleValueEvent(usernameChildEvent);
Here is the database structure.
What am I doing wrong?
I can't reproduce your results. Add a completion listener to see what the status of the update is:
Userref.updateChildren(childUpdates2, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Log.i(TAG, "onComplete: success");
} else {
Log.w(TAG, "onComplete: fail", databaseError.toException());
}
}
});
Also verify that username.toMap() produces a non-empty map:
Map<String, Object> userdata = username.toMap();
if (userdata.isEmpty()) {
Log.e(TAG, "Oops! No data");
} else {
Log.i(TAG, "userdata=" + userdata);
}

Categories

Resources