If the value in the database already exist (for example I want to add Cheetos to firestore and in the database cheetos already exist) then I want to update the quantity field of that item. I make the code like this but the app still add new item when the value is the same. I think the system doesn't detect my 'if(task.getResult().getDocuments().size()>0'.
this is the firestore data
this is the method code
private void uploadItem() {
merk = etMerk.getText().toString().trim();
type = etType.getText().toString().trim();
typemerk = merk + " - " + type;
qty = etQty.getText().toString().trim();
price = etPrice.getText().toString().trim();
date = datetime.getText().toString();
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("watchlist").whereEqualTo("merk",typemerk)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult().getDocuments().size()>0){
Toast.makeText(AddItemActivity.this, "Barang Sama", Toast.LENGTH_SHORT).show();
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());
String itemid = document.getString("id");
String date = document.getString("date");
String type = document.getString("type");
String Oldqty = document.getString("qty");
String price = document.getString("price");
int sum= Integer.parseInt(Oldqty) + Integer.parseInt(qty);
String newQty = String.valueOf(sum);
Map<String, Object> newstock = new HashMap<>();
newstock.put("qty",newQty);
FirebaseFirestore database = FirebaseFirestore.getInstance();
database.collection("watchlist")
.document(itemid).update(newstock).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(AddItemActivity.this, "Berhasil Menambahkan jumlah barang", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
etMerk.setText("");
etType.setText("");
etQty.setText("");
etPrice.setText("");
etMerk.setFocusable(true);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddItemActivity.this, "Gagal Memasukkan stok, silahkan coba lagi.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
else {
upload();
}
} else {
Log.w(Tag.ITEM, "error getting documents", task.getException());
}
}
});
}
This code works
private void cutStock() {
merk = etMerk.getText().toString().trim();
type = etType.getText().toString().trim();
typemerk = type + " - " + merk;
qty = etQty.getText().toString().trim();
price = etPrice.getText().toString().trim();
date = datetime.getText().toString();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference documentReference = db.collection("watchlist");
final CollectionReference documentSales = db.collection("sales");
documentReference.whereEqualTo("type",typemerk)
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());
String id = document.getString("id");
String oldqty = document.getString("qty");
Integer i = Integer.parseInt(oldqty) - Integer.parseInt(qty);
String newQty = String.valueOf(i);
Map<Object, String> map = new HashMap<>();
map.put("qty",newQty);
db.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());
Map<String, Object> sales = new HashMap<>();
sales.put("date", date);
sales.put("type", typemerk);
sales.put("qty", qty);
sales.put("price", price);
documentSales.add(sales).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(AddItemActivity.this, "Berhasil mencetak transaksi", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
etMerk.setText("");
etType.setText("");
etQty.setText("");
etPrice.setText("");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddItemActivity.this, "Gagal mencetak", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
progressBar.setVisibility(View.GONE);
}
}
else {
progressBar.setVisibility(View.GONE);
Toast.makeText(AddItemActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
Log.w(Tag.ITEM, "error getting documents", task.getException());
}
}
});
}
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'm trying to create new data in the firebase realtime database
I tried to use a HashMap and an object, none of them works.
even when I put the OnComplete/OnSuccess/OnFailure listeners I don't receive any data in the log.
private void registerUser(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser currentUser = mAuth.getCurrentUser();
String uid = currentUser.getUid();
HashMap<String, String> userMap = new HashMap<>();
User user = new User(displayName, "Bonjour!", "par defaut", "def");
userMap.put("name", displayName);
userMap.put("status", "Bonjour!_Je_viens_de_m'inscirire");
userMap.put("image", "par_defaut");
userMap.put("thumb_image", "def");
Log.d(TAG, "onComplete: " + userMap);
Log.d(TAG, "onComplete: " + user);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(uid);
mDatabaseReference.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: ");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
Log.d(TAG, "onComplete: " + mDatabaseReference);
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mRegProgressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, "impossible d'inscrire, veuillez ressayer!", Toast.LENGTH_LONG).show();
}
I tried adding this code and it gives me :" not connected " in the log.
//check if connected
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
Log.d(TAG, "connected");
} else {
Log.d(TAG, "not connected");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.w(TAG, "Listener was cancelled");
}
});
the HashMap contains the actual data but the setValue() method does not work for some reason. When I look in the firebase console there are no changes.
the code responsible for changing the activity from RegisterActivity to MainActivity ran before actually being able to send the data to the database.
to solve the problem I just put the part of the code responsible for changing the activity and all that:
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
inside the OnSuccessListener.
so the final code is:
private void registerUser(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser currentUser = mAuth.getCurrentUser();
String uid = currentUser.getUid();
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", displayName);
userMap.put("status", "Bonjour!_Je_viens_de_m'inscirire");
userMap.put("image", "par_defaut");
userMap.put("thumb_image", "def");
mDatabaseReference = mDatabase.getReference("Users").child(uid);
mDatabaseReference.setValue(userMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: ");
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mRegProgressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, "impossible d'inscrire, veuillez ressayer!", Toast.LENGTH_LONG).show();
}
}
});
thanks for the commenters.
Im trying to make a code for uploading item/stock to firestore. what i want is if the Item is already registered in firestore, then recalculate the quantity. But if the item is not registered yet in firestore, system add new document to firestore.
I already make a code like below, if i try to add item that is already registered it succeed on recalculating the quantity but the problem is when i want to add new item ( that is not registered in database) it doesnt work. Can somebody fix my code.
final FirebaseFirestore db = FirebaseFirestore.getInstance();
merk = etMerk.getText().toString().trim();
type = etType.getText().toString().trim();
typemerk = type + " - " + merk;
qty = etQty.getText().toString().trim();
price = etPrice.getText().toString().trim();
date = datetime.getText().toString();
final Map<String, Object> stock = new HashMap<>();
stock.put("date", date);
stock.put("type", typemerk);
stock.put("qty", qty);
stock.put("price", price);
stock.put("merk", merk);
final FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
final CollectionReference documentReference = rootRef.collection("watchlist");
Query query = documentReference.whereEqualTo("type", typemerk);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());
String id = document.getString("id");
String oldqty = document.getString("qty");
Integer i = Integer.parseInt(oldqty) + Integer.parseInt(qty);
String newQty = String.valueOf(i);
Map<Object, String> map = new HashMap<>();
map.put("qty", newQty);
rootRef.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());
Toast.makeText(AddItemActivity.this, "Berhasil menambah stok", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
} else {
Log.d(Tag.ITEM, "not register in DB", task.getException());
Toast.makeText(AddItemActivity.this, "new item to database", Toast.LENGTH_SHORT).show();
documentReference
.add(stock)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(AddItemActivity.this, "Berhasil Memasukkan Barang ke Stok", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
etMerk.setText("");
etType.setText("");
etQty.setText("");
etPrice.setText("");
etMerk.setFocusable(true);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddItemActivity.this, "Gagal Memasukkan stok, silahkan coba lagi.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
});
}
You should check to make sure that your query returned successfully and that it's not empty. It can return an empty result if the query was processed but there was no matching result.
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("myCollection")
.whereEqualTo("myQuery", myQueryValue)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
boolean documentExists;
if(task.isSuccessful()){
Log.d("QueryResult", "Is query result empty: " + task.getResult().isEmpty());
documentExists = !task.getResult().isEmpty();
}else{
Log.e("QueryResult", "Error getting documents.", task.getException());
documentExists = false;
}
if(documentExists){
Log.d("QueryResult", "The document exists");
// Do whatever you need to do with the document
}else{
Log.d("QueryResult", "The document doesn't exist or there was an error retrieving it");
// Create the document or whatever else you need to do
}
}
});
How my app adds values to realtime database:
private void uploadFile() {
if(imageUri != null){
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
storageTask = fileReference.putFile(imageUri);
Task<Uri> urlTask = storageTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String miUrlOk = downloadUri.toString();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String kisiId = user.getUid().toString().trim();
final String kisiAd = user.getDisplayName().toString().trim();
final String urunIsim = editurunIsim.getText().toString().trim();
final String urunYorum = editUrunYorum.getText().toString();
Map<String,Object> values = new HashMap<String,Object>();
values.put("kisiId", kisiId);
values.put("kisiAd", kisiAd);
values.put("urunAdi", urunIsim);
values.put("yorum", urunYorum);
Kullanici kullanici = new Kullanici(kisiId, kisiAd, urunIsim,urunYorum,miUrlOk);
DatabaseReference dbRef = db.getReference("Kullanici");
String key = dbRef.push().getKey();
DatabaseReference databaseReference = db.getReference("Kullanici/" + key);
databaseReference.setValue(kullanici);
String referansinAnahtari=databaseReference.getKey().toString();
databaseReference.child("urunYorum").child(referansinAnahtari).setValue(values);
Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_LONG).show();
} else {
// Handle failures
// ...
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(getActivity(), "No File selected", Toast.LENGTH_SHORT).show();
}
}
How my app reads values from realtime database (a part):
kullaniciList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Kullanici kullaniciModel = postSnapshot.getValue(Kullanici.class);
kullaniciModel.setKey(postSnapshot.getKey());
kullaniciList.add(kullaniciModel);
}
adapterr.setOnItemClickListener(anasayfaFragment.this);
adapterr.notifyDataSetChanged();
progressCircle.setVisibility(View.INVISIBLE);
my debug is closed when I run it with debug. I think it's a logic error. How do I capture data from a realtime database?
I am using Cloud Firestore as my database to save all users as documents in 'users' collection. I want to display all the users in 'users' collection into my RecyclerView except the current user who is currently using the app. I searched a lot to find a solution all over the internet but could not find any. So please help me out guys and thanks in advance. I'm a beginner, so really need your help. And thanks again.
This is my Firestore adapter:
mQuery = FirebaseFirestore.getInstance().collection("users");
FirestoreRecyclerOptions<NearbyUserRecyclerModel> options = new FirestoreRecyclerOptions.Builder<NearbyUserRecyclerModel>()
.setQuery(mQuery,NearbyUserRecyclerModel.class)
.setLifecycleOwner(getActivity())
.build();
FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<NearbyUserRecyclerModel,NearbyProfilesViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final NearbyProfilesViewHolder holder, int position, #NonNull final NearbyUserRecyclerModel model) {
holder.itemBuddyState.setText("0");
Glide.with(getActivity()).load(model.getThumb_pictures()).into(holder.itemImage);
holder.itemDisplayName.setText(model.getFirst_name());
holder.itemOnline.setVisibility(View.VISIBLE);
DocumentSnapshot snapshot = getSnapshots().getSnapshot(position);
if (snapshot.contains("online")){
Boolean onlineState = snapshot.getBoolean("online");
if (onlineState == true){
holder.itemOnline.setVisibility(View.VISIBLE);
}
else {
holder.itemOnline.setVisibility(View.INVISIBLE);
}
}
final String user_id = snapshot.getId();
mChatRequestCollection.document(current_user_id).collection("request_received")
.document(user_id).get().addOnCompleteListener(getActivity(),
new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.contains("received_time")){
holder.itemBuddyState.setText("3");
}else {
Log.d("REQUEST RECEIVED", "onComplete: received field doest exist, "+task.getException());
}
}else {
Log.d("REQUEST RECEIVED", "onComplete: Document doesn't exist, "+ task.getException());
}
}
});
mChatRequestCollection.document(current_user_id).collection("request_sent")
.document(user_id).get().addOnCompleteListener(getActivity(),
new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.contains("sent_time")){
holder.itemBuddyState.setText("2");
}else {
Log.d("REQUEST SENT", "onComplete: sent field doesn't exist, "+ task.getException());
}
}else {
Log.d("REQUEST SENT", "onComplete: Document doesn't exist,");
}
}
});
mChatHolderCollection.document(current_user_id+"/user_chats/"+user_id)
.get().addOnCompleteListener(getActivity(),
new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.contains("timestamp")){
holder.itemBuddyState.setText("1");
}else {
Log.d("CHAT_HOLDERDOC", "onComplete: timeStamp field doesn't exist, "+task.getException());
}
}else {
Log.d("CHAT_HOLDERDOC", "onComplete: chat buddy doesn't exist, "+task.getException());
}
}
});
holder.itemImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userPopupDialog(model, user_id);
// popupIntent(user_id);
}
});
holder.itemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
String message = holder.itemEditText.getText().toString();
if (holder.itemBuddyState.getText().equals("0")){
if (!TextUtils.isEmpty(message)) {
WriteBatch request_batch = mRootStore.batch();
Map<String, Object> sentMap = new HashMap<>();
sentMap.put("sent_time", FieldValue.serverTimestamp());
sentMap.put("message", message);
Map<String, Object> receivedMap = new HashMap<>();
receivedMap.put("received_time", FieldValue.serverTimestamp());
receivedMap.put("message", message);
Map<String, Object> notificationMap = new HashMap<>();
notificationMap.put("from", current_user_id);
notificationMap.put("type", "request");
DocumentReference sentRef = mRootStore.collection("chat_requests").document(current_user_id + "/request_sent/" + user_id);
request_batch.set(sentRef, sentMap, SetOptions.merge());
DocumentReference receivedRef = mRootStore.collection("chat_requests").document(user_id + "/request_received/" + current_user_id);
request_batch.set(receivedRef, receivedMap, SetOptions.merge());
DocumentReference notificationRef = mRootStore.collection("users/" + user_id + "/notifications").document();
request_batch.set(notificationRef, notificationMap, SetOptions.merge());
request_batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//------------Request Sent------------//
holder.itemEditText.setText("");
holder.itemBuddyState.setText("2");
Log.d("REQUEST_LOG", "onComplete: Request sent Successfully");
Log.d("REQUEST_LOG", "onComplete: Notification sent Successfully");
Snackbar.make(v, "Request sent Successfully", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(v, "Failed Sending Request", Snackbar.LENGTH_LONG).show();
Log.d("REQUEST_LOG", "onComplete: Failed sending request" + task.getException());
}
}
});
}
}
if (holder.itemBuddyState.getText().equals("3")){
holder.itemEditText.setText("");
Snackbar.make(v, "Request already received by user", Snackbar.LENGTH_LONG).show();
}
if (holder.itemBuddyState.getText().equals("2")){
holder.itemEditText.setText("");
Snackbar.make(v, "Request already sent", Snackbar.LENGTH_LONG).show();
}
if (holder.itemBuddyState.getText().equals("1")){
holder.itemEditText.setText("");
Snackbar.make(v,"User already chat buddy", Snackbar.LENGTH_LONG).show();
}
}
});
}
#NonNull
#Override
public NearbyProfilesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nearby_profiles_recycler_items, parent, false);
final AppCompatImageButton button_send = view.findViewById(R.id.itemSendButton_id);
final AppCompatEditText editText_message = view.findViewById(R.id.itemEditText_id);
Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabUnselected));
button_send.setImageDrawable(drawable);
button_send.setEnabled(false);
editText_message.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String message = editText_message.getText().toString();
if (TextUtils.isEmpty(message)){
Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabUnselected));
button_send.setImageDrawable(drawable);
button_send.setEnabled(false);
}
else {
Drawable drawable = getResources().getDrawable(R.drawable.ic_send_new);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.colorTabSelected));
button_send.setImageDrawable(drawable);
button_send.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
return new NearbyProfilesViewHolder(view);
}
};
nearbyRecycler.setAdapter(adapter);
Change the IF condition in the below method
public void getUserData(){
db.collection("users")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
if(document.getData().get("userID").equals(userID)){
// User user = (User)document.getData();
// Log.e(TAG, "onComplete: "+user.getUserName()+ user.getDescription() + user.isGender());
Map<String, Object> user = new HashMap<>();
user.put("name", document.getData().get("name"));
user.put("userID", document.getData().get("userID"));
user.put("email", document.getData().get("email"));
user.put("companyName",document.getData().get("companyName"));
user.put("officeAddress", document.getData().get("officeAddress"));
user.put("phoneNumber", document.getData().get("phoneNumber"));
user.put("gender",document.getData().get("gender"));
user.put("isProfileComplete",document.getData().get("isProfileComplete"));
user.put("profilePicUrl", document.getData().get("profilePicUrl"));
user.put("description", document.getData().get("description"));
/* if(document.getData().get("isProfileComplete")){
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToHome();
}else{
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToHome();
}*/
boolean check = (Boolean) document.getData().get("isProfileComplete");
if(check){
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToHome();
}else{
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToOnBoarding();
}
Log.e(TAG, "onComplete:GET DADA "+ user.get("isProfileComplete"));
}else{
Log.e(TAG, "onComplete:ID "+document.getData().get("userID") );
LoginActivity loginActivity = (LoginActivity)mContext;
loginActivity.navigateToOnBoarding();
}
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
}
There is no way in which you can query a Firestore database using != (not equal to operator). So the following line of code does not exist:
Query query = db.collection("users").whereNotEqualTo("userID", userID);
In this case, you need to create your own logic for that. To solve this, you need to query your database for all users but the adapter should receive all of them except one, the current user. So you need to create an if statement to check if the current user is different than the others.