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);
}
Related
in firebase I have two tables: itinerary with id, title, hour, minutes, seconds, description, level of difficulty and image while in review I have title, image and rating now I should insert the itinerary id, generated with getNewKey, in review so that one itinerary has several reviews. The created method is:
public void addReview() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
auth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = auth.getCurrentUser();
String titleReview = insertReviews_fragment.getTitleReview();
String descriptionReview = insertReviews_fragment.getDescriptionReview();
String voteItinerary = insertReviews_fragment.getVoteReview();
//String ItineraryId = String.valueOf(explore_fragment.getId());
String itineraryId = referenceDb.child("Itinerary").push().getKey();
ReviewDao reviewDao = new ReviewDao();
String reviewId = reviewDao.getNewKey();
if (images != null) {
StorageReference reviewRef = storageReference.child("review_image/").child(reviewId + ".jpg");
reviewRef.putFile(Uri.parse(String.valueOf(images))).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
reviewRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String uid = auth.getUid();
String email = firebaseUser.getEmail();
HashMap<String, Object> map = new HashMap<>();
map.put("titleReview", titleReview);
map.put("image", uri.toString());
map.put("email", email);
map.put("voteReview", voteItinerary);
map.put("descriptionReview", descriptionReview);
map.put("userId", uid);
map.put("reviewId", reviewId);
map.put("ItineraryId", itineraryId);
referenceDb.child("Reviews").child(reviewId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//APRO SCHERMATA List Review
Toast.makeText(insertReviews_fragment.getActivity(), "Operation successful, thanks for your feedback", Toast.LENGTH_SHORT).show();
openListReviewsFragment();
} else {
//ERRORE
Toast.makeText(insertReviews_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertReviews_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(insertReviews_fragment.getActivity(), "Please add image", Toast.LENGTH_SHORT).show();
}
}
public void getAllItinerary(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference referenceDb = database.getReference("Itinerary");
itineraryList = new ArrayList<>();
Itinerary iter = new Itinerary();
itineraryList.clear();
referenceDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Iterable<DataSnapshot> dataSnapsho1 = snapshot.getChildren();
for(DataSnapshot ds : dataSnapsho1) {
if(ds.child("titleItinerary").getValue() != null){
Itinerary iter = new Itinerary(
(String) ds.child("itineraryId").getValue(),
(String) ds.child("titleItinerary").getValue(),
(String) ds.child("descriptionItinerary").getValue(),
(String) ds.child("difficultyLevel").getValue(),
(String) ds.child("hours").getValue(),
(String) ds.child("minutes").getValue(),
(String) ds.child("seconds").getValue(),
String.valueOf(ds.child("image").getValue()));
iter.setEmail((String)ds.child("email").getValue());
itineraryList.add(iter);
}
}
adapterListItinerary = new AdapterListItinerary(getActivity(), itineraryList);
recyclerView.setAdapter(adapterListItinerary);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
But this way a new id code is associated with the itineraryId attribute in the reviews table. How can I fix?
I want to ask about how to limit retrieve data in Android Firebase. Here is my code:
private void lookingforHelp(){
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations");
dbref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
int limitUser = 0;
ModelUsersLocation mUserLoct = ds.getValue(ModelUsersLocation.class);
LatLng yourLatLng = new LatLng(latitude_user, longitude_user);
LatLng polisiLatLng = new LatLng(mUserLoct.getLatitude(), mUserLoct.getLongitude());
if (mUserLoct.getPengguna().equals("polisi")){
if (SphericalUtil.computeDistanceBetween(yourLatLng, polisiLatLng) < 700) {
if (limitUser <= 5){
if (mUserLoct.getJangkauan().isEmpty()) {
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations").child(mUserLoct.getUser().getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("jangkauan", fuser.getUid());
dbref.updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
writeNewOrder();
}
});
}
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I tried to retrieve data that i want is only less than 5 users, using int limitUser = 0; and it's still not working to retrieve data only less than 5 users.
PROBLEM SOLVED, I try to create markeroptions and make it into invisible, and then add it into arraylist, if (markers.size() <= 5) {do something}
thank u guys for your help btw i really apreciate it :))
public MutableLiveData<ArrayList<Vendor>> getVendorsByLimit(int limit) {
ArrayList<Vendor> arrayList = new ArrayList<>();
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.getChildrenCount() > 0) {
//String value = (String) snapshot.getValue(); //Get all child data
//OR
//String singleValue = (String) snapshot.child("fullName").getValue(); //Get single child data
Vendor model = snapshot.getValue(Vendor.class);
String key = snapshot.getKey();
arrayList.add(model);
}
}
data.setValue(arrayList);
} else {
data.setValue(null);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e(TAG, "" + databaseError.getMessage());
data.setValue(null);
}
});
}
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
You can sort them by using timeStamp like
-----------------------------------------
FirebaseDatabase.getInstance().getReference()
.child("Conversation").child(conversationID)
.limitToLast(100)
.orderByChild("timestamp")
.startAt(dateToStart) // pass timestamp from when you want to start filtering
.endAt(dateToEnd); // pass timestamp till when you want to apply filtering
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.
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!
Here's the Image:
How do I retrieve the contents of custProd? Thanks in advance.
Firebase.setAndroidContext(this);
Firebase ref = new Firebase(YOUR_FIREBASE_URL);
ArrayList custProd= new ArrayList<>();
ref.child("customerrequest/-Ke8u4..../custProd/")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.getValue() != null) {
Map<String, String> value = (Map<String, String>) dataSnapshot.getValue();
for (Map.Entry<String, String> entry : value.entrySet())
{
String _key = entry.getKey();
String _value = entry.getValue();
// TODO add value in list
if (_value.length() > 0 && !custProd.contains(_value))
custProd.add(_value);
Log.e("!__#::>", _key + " " + _value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("!_###_##_GetAllcustProd:>", firebaseError + "");
}
});