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?
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 am trying to store images into Firebase Storage and then download the URI of those images from Firebase storage and then again upload those URI into the firebase firestore using a foreach loop . Images are successfully uploading into the firebase storage but Uri of only last image is going into firestore first three are failing. I created AN ARRAY LIST OF BITMAPS and then used foreach loop on it.
My Code
private void UploadingImage() {
if (bitmap != null && bitmap2 != null && bitmap3 != null && bitmap4 != null) {
StorageTask arrayUpload;
fuser = FirebaseAuth.getInstance().getCurrentUser();
ProductName = Objects.requireNonNull(Product_Name_EditText.getText()).toString();
CityName = Objects.requireNonNull(CityNameEditText.getText()).toString();
// Bitmap[] bitmaps=new Bitmap[3];
ArrayList<Bitmap> bitmapArrayList = new ArrayList<>();
bitmapArrayList.add(bitmap);
bitmapArrayList.add(bitmap2);
bitmapArrayList.add(bitmap3);
bitmapArrayList.add(bitmap4);
Bitmap bitresized;
for (Bitmap bitUpload : bitmapArrayList)
{
bitresized = Bitmap.createScaledBitmap(bitUpload, 800, 800, true);
ByteArrayOutputStream baosArray = new ByteArrayOutputStream();
bitresized.compress(Bitmap.CompressFormat.JPEG, 70, baosArray);
byte[] uploadbaosarray = baosArray.toByteArray();
i = i + 1;
fileReference = storageReference.child(ProductName).child(i + ProductName + ".jpg");
arrayUpload = fileReference.putBytes(uploadbaosarray);
arrayUpload.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();
} else if (task.isSuccessful()) {
Toast.makeText(Upload_New_Product.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
//mProgressBar.setVisibility(View.INVISIBLE);
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
assert downloadUri != null;
String mUri = downloadUri.toString();
ProductName = Product_Name_EditText.getText().toString();
ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document(ProductName);
HashMap<String, Object> map = new HashMap<>();
map.put("imageURL" + i, mUri);
//reference.updateChildren(map);
ProductRef.set(map, SetOptions.merge());
} else {
Toast.makeText(Upload_New_Product.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload_New_Product.this, e.getMessage(), Toast.LENGTH_SHORT).show();
//pd.dismiss();
}
});
}
}
}
Since uploading (and getting the download URL) are asynchronous operations, the for loop completes almost immediately, and all uploads are happening in parallel after that. This means that by the time your map.put("imageURL" + i, mUri) runs, the i variable is going to be its final value.
To make the code work, you need to capture the variable of i for each iteration over the loop. A simple way to do that, is to move the code that uploads the image and stores its URL into a separate function, and pass the value of i into that function call.
Something like:
public void uploadFileAtIndex(int i) {
fileReference = storageReference.child(ProductName).child(i + ProductName + ".jpg");
arrayUpload = fileReference.putBytes(uploadbaosarray);
arrayUpload.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();
} else if (task.isSuccessful()) {
Toast.makeText(Upload_New_Product.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
assert downloadUri != null;
String mUri = downloadUri.toString();
ProductName = Product_Name_EditText.getText().toString();
ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document(ProductName);
HashMap<String, Object> map = new HashMap<>();
map.put("imageURL" + i, mUri);
ProductRef.set(map, SetOptions.merge());
} else {
Toast.makeText(Upload_New_Product.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload_New_Product.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
And then use it in the loop with:
for (Bitmap bitUpload : bitmapArrayList) {
...
i = i + 1;
uploadFileAtIndex(i);
}
You might need to pass more of your variable to uploadFileAtIndex than I've done here, but its passing i that solves the problem you have right now.
I am storing some data into the firebase firestore and using onComplete listener on the operation. I am Storing the ID which I generated, in a String and using it to perform further operations.
ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document();
ProductID =db.collection("Sellers").document(CityName).collection(Uid).document().getId();
I am then using that generated Id to as a field in Cloud Storage and adding some images inside it and after it using the same ID I am storing the URLs of these images in the firestore but what happening is a different Id is generated in between and details are stored inside one Id and ImageUrls inside another.
My code
private void UploadDetails() {
ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document();
ProductID =db.collection("Sellers").document(CityName).collection(Uid).document().getId();
HashMap<String, Object> map = new HashMap<>();
map.put("City_Name", CityName);
ProductRef.set(map, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
UploadingImage();
UploadingThumbnailImage();
}
});
}
private void UploadingImage() {
resized = Bitmap.createScaledBitmap(bitmap, 800, 800, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 70, baos);
byte[] uploadbaos = baos.toByteArray();
ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document(ProductID);
fileReference = storageReference.child(ProductID).child("1" + ProductID + ".jpg");
uploadTask = fileReference.putBytes(uploadbaos);
uploadTask.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();
} else if (task.isSuccessful()) {
Toast.makeText(Upload_New_Product.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
//mProgressBar.setVisibility(View.INVISIBLE);
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String mUri = downloadUri.toString();
// ProductRef=db.collection("Sellers").document().collection(ProductType);
ProductName = Product_Name_EditText.getText().toString();
// ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document(ProductID);
//reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
HashMap<String, Object> map = new HashMap<>();
map.put("imageURL", mUri);
//reference.updateChildren(map);
ProductRef.set(map, SetOptions.merge());
//pd.dismiss();
} else {
Toast.makeText(Upload_New_Product.this, "Failed!", Toast.LENGTH_SHORT).show();
//pd.dismiss();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload_New_Product.this, e.getMessage(), Toast.LENGTH_SHORT).show();
//pd.dismiss();
}
});
}
Every time you call document() with no parameters, you're going to get a different random document ID. Your code here is calling document() twice:
ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document();
ProductID = db.collection("Sellers").document(CityName).collection(Uid).document().getId();
If you want a single random ID to reuse, just call it once:
ProductRef = db.collection("Sellers").document(CityName).collection(Uid).document();
ProductID = ProductRef.getId();
I'm creating an app like olx, Where if you upload ad , its gets posted in two different collections, namly "My Ads" where ads of every logged in user are posted against his ID, and Explore collection Where ads are posted for all users. So if i want to update or delete ad, It should be deleted from both collections! Image Url :https://imgur.com/a/HCKfGBb
String uid= user.getUid();
SellingDetails.put("uid",uid);
final CollectionReference reference = exploreAdDB.collection("cities/" + city + "/" + category);
final CollectionReference myAdDocRef = myAdDB.collection("users/ads/"+uid);
if (imageUri != null) {
final StorageReference fileReference = mStorage.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
UploadTask uploadTask = fileReference.putFile(imageUri);
Task<Uri> urlTask = uploadTask.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();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if(downloadUri!=null)
SellingDetails.put("imageUrl",downloadUri.toString());
reference.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Service Uploaded in explore db ", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
Intent intent = new Intent(GetLocationActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Toast.makeText(GetLocationActivity.this, "Ad posted Successfully", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Failed adding data into explore db", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
}
});
myAdDocRef.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Data Also added to myAds db", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Data not added into my ads", Toast.LENGTH_SHORT).show();
}
});
} else {
// Handle failures
Toast.makeText(GetLocationActivity.this, "Failed adding data", Toast.LENGTH_SHORT).show();
}
}
});
}
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());
}
}
});
}