I tryed to show up text on the TextView which i'm saved with the saveQuote methode on Firestore, but just recieve null. I'm also had some problems by doing this with the "normal" database from Firebase. I definded the OnClick mthode for the buttons on the xml. Can someone maybe tell me how to fix that problem ? My logcat say "E/memtrack: Couldn't load memtrack module", "GCM_HB_ALARM release without a matched acquire!" and " Not supplying enough data to HAL, expected position".
public class MainActivity extends AppCompatActivity {
private static final String TAG = "InspiringQuote";
public static final String AUTHOR_KEY = "author";
public static final String QUOTE_KEY = "quote";
private TextView textViewData;
private DocumentReference mDocRef = FirebaseFirestore.getInstance().document("sampleData/inspiration");
TextView mQuoteTextView;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference noteRef = db.collection("inspiration");
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mQuoteTextView = (TextView) findViewById(R.id.text_view_data);
textViewData = (TextView) findViewById(R.id.text_view_data);
//Toolbar Options
//toolbar = (Toolbar) findViewById(R.id.testToolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setTitle("HomePage");
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
}
public void saveQuote(View view){
EditText quoteView = (EditText) findViewById(R.id.editTextQuote);
EditText authorVIew = (EditText) findViewById(R.id.editTextAuthor);
String quoteText = quoteView.getText().toString();
String authorText = authorVIew.getText().toString();
if (quoteText.isEmpty() || authorText.isEmpty()){return;}
Map<String, Object> dataToSave = new HashMap<String, Object>();
dataToSave.put("QUOTE_KEY", quoteText);
dataToSave.put("AUTHOR_KEY", authorText);
mDocRef.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Document was not saved", e);
}
});
}
public void loadNote(View v){
mDocRef.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
String title = documentSnapshot.getString(QUOTE_KEY);
String description = documentSnapshot.getString(AUTHOR_KEY);
//Map<String, Object> note = documentSnapshot.getData();
textViewData.setText("Title" + title + "\n" + "Description: " + description);
}else{
Toast.makeText(MainActivity.this, "Document does not exits", Toast.LENGTH_SHORT);
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
}
In the imgae you can see that im recieving "null"
As per my comment
String title = documentSnapshot.getString("QUOTE_KEY");
String description = documentSnapshot.getString("AUTHOR_KEY");
In your code, when you are adding the values, you are declaring a string value. However, when you are retrieving the values, you have declared string variable with different value. Therefore, it can't find what you are looking for.
Related
I am new in android, I am trying to develop a simple system in android and using the cloud firestore beta as the database. I have already done the registration part which is writing the data(email & password) in the database. but I do not know the process for the login as i want the system to read the data from the database and match with the emails and passwords from the database. Can anyone help me? Thanks in advance.
The registration activity is given below:
public class RegisterActivity extends AppCompatActivity {
private Button btnRegister;
private EditText edtxtEmail;
private EditText edtxtTpnumber;
private EditText edtxtDepartment;
private EditText edtxtPassword;
private EditText edtxtConfirmpassword;
private FirebaseFirestore rFireStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
rFireStore = FirebaseFirestore.getInstance();
btnRegister = (Button) findViewById(R.id.btnregister);
edtxtEmail = (EditText) findViewById(R.id.edtxtemail);
edtxtTpnumber = (EditText) findViewById(R.id.edtxttpnumber);
edtxtDepartment = (EditText) findViewById(R.id.edtxtdepartment);
edtxtPassword = (EditText) findViewById(R.id.edtxtpassword);
edtxtConfirmpassword = (EditText) findViewById(R.id.edtxtconfirmPassword);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = edtxtEmail.getText().toString();
String TPnumber = edtxtTpnumber.getText().toString();
String Department = edtxtDepartment.getText().toString();
String Password = edtxtPassword.getText().toString();
String ConfirmPassword = edtxtConfirmpassword.getText().toString();
Map<String, String> userMap = new HashMap<>();
userMap.put("Email Address", Email);
userMap.put("TP Number", TPnumber);
userMap.put("Department", Department);
userMap.put("Password", Password);
userMap.put("Confirm Pass", ConfirmPassword);
rFireStore.collection("Users").document("Students").set(userMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegisterActivity.this, "Data Saved!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "Data Failed!!", Toast.LENGTH_SHORT).show();
}
});
/*rFireStore.collection("Users").add(userMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(RegisterActivity.this, "Data Saved!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "Data Failed!!", Toast.LENGTH_SHORT).show();
}
});*/
}
});
}
}
For login you can use this:
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
if (task.isSuccessful()) {
//task result = 1
}
}
if (task.getResult().size() == 0) {
//task result = 0
}
The goal of the following code is to save data in Cloud Firestore from a android device(api 24)
public class MainActivity extends AppCompatActivity {
public static final String NUM_KEY="num";
public static final String SMS_KEY="sms";
private static final String TAG = "MainActivity";
private DocumentReference mDocRef = FirebaseFirestore.getInstance().document("android/websms");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void saveSMS(View view){
EditText num = (EditText) findViewById(R.id.num);
EditText sms = (EditText) findViewById(R.id.msg);
String quotenum = num.getText().toString();
String quotesms = sms.getText().toString();
Button button = (Button) findViewById(R.id.button);
Map<String,Object> dataToSave = new HashMap<String, Object>();
dataToSave.put(NUM_KEY,quotenum);
dataToSave.put(SMS_KEY,quotesms);
mDocRef.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG,"Document was not saved",e);
}
});
}
I'm following some Firestore tutorials on youtube and it seems to be a little bit outdated because when I'm running it on my android device I get the following error on the console
04-17 02:09:50.718 2600-2712/com.example.joao.websms1 E/art: The String#value field is not present on Android versions >= 6.0
Thank you in advance to anyone willing to help.
¿Have u tried using the method push?
mDocRef.push(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG,"Document was not saved",e);
}
});
public class Post extends AppCompatActivity {
private static final String TAG = null;
private TextView titleView;
private Button create_post_button;
private EditText post_title,post_description;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private FirebaseFirestore db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth=FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
progressBar = (ProgressBar) findViewById(R.id.progressBar2);
titleView=(TextView) findViewById(R.id.titleView);
post_title=(EditText) findViewById(R.id.post_title);
post_description=(EditText) findViewById(R.id.post_description);
create_post_button=(Button)findViewById(R.id.create_post_button);
create_post_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
createPost();
}
});
}
public void createPost() {
String title_val = post_title.getText().toString().trim();
String post_description_val = post_description.getText().toString().trim();
String user_id=mAuth.getCurrentUser().getUid();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(post_description_val)) {
progressBar.setVisibility(View.VISIBLE);
Map<String, String> posts = new HashMap<>();
posts.put("description",post_description_val);
posts.put("title", title_val);
posts.put("user_id", user_id);
progressBar.setVisibility(View.GONE);
db.collection("posts")
.add(posts)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText( Post.this,"Success", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w( TAG,"Error adding document", e);
}});}}}
Its not being inserted into db,neither it gives any error.I don't understand where the error is!I don't know what is wrong since everything is from android main page.If it is some logic error please let me know!
Some help would be appreciated! Thanks in advance!
The problem is because you're accessing the variables wrong when checking for empty title and description, here:
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(description_val)) {
it should be:
public void createPost() {
String title_val = title.getText().toString().trim();
String post_description_val = description.getText().toString().trim();
String user_id=mAuth.getCurrentUser().getUid();
if (!title_val.isEmpty() && !post_description_val.isEmpty()) {
progressBar.setVisibility(View.VISIBLE);
Map<String, String> posts = new HashMap<>();
posts.put("description",description_val);
posts.put("title", title);
posts.put("user_id", user_id);
progressBar.setVisibility(View.GONE);
db.collection("posts")
.add(posts)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText( Post.this,"Success", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w( TAG,"Error adding document", e);
}
});
}
}
EDIT:
For testing purposes your rules should look like this, later you need to update them to make them more secure:
I am using firebase database, but I am newbie with it. I am following this tutorial,
Now, my question is how can I check the email if it is already exist in the database? If email is already there data should not be add to db.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView txtDetails;
private EditText inputName, inputEmail;
private Button btnSave;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Displaying toolbar icon
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
txtDetails = (TextView) findViewById(R.id.txt_user);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
btnSave = (Button) findViewById(R.id.btn_save);
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
// store app title to 'app_title' node
mFirebaseInstance.getReference("app_title").setValue("Realtime");
// app_title change listener
mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "App title updated");
String appTitle = dataSnapshot.getValue(String.class);
// update toolbar title
getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
// Save / update the user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = inputName.getText().toString();
final String email = inputEmail.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email);
} else {
updateUser(name, email);
}
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Your Logic here
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
User mModel = eventSnapshot.getValue(User.class);
// Log.e("DATA" ,""+ mModel.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
toggleButton();
}
// Changing button text
private void toggleButton() {
if (TextUtils.isEmpty(userId)) {
btnSave.setText("Save");
} else {
btnSave.setText("Update");
}
}
private void filter()
{
}
/**
* Creating new user node under 'users'
*/
private void createUser(String name, String email) {
// TODO
// In real apps this userId should be fetched
// by implementing firebase auth
if (TextUtils.isEmpty(userId)) {
userId = mFirebaseDatabase.push().getKey();
}
User user = new User(name, email);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
/**
* User data change listener
*/
private void addUserChangeListener() {
// User data change listener
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(!dataSnapshot.child("users").child("email").exists())
{
Log.e(TAG, "User not exists");
}
else
{
Log.e(TAG, "User exists");
}
// Check for null
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);
// Display newly updated name and email
txtDetails.setText(user.name + ", " + user.email);
// clear edit text
inputEmail.setText("");
inputName.setText("");
toggleButton();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read user", error.toException());
}
});
}
private void updateUser(String name, String email) {
// updating the user via child nodes
if (!TextUtils.isEmpty(name))
mFirebaseDatabase.child(userId).child("name").setValue(name);
if (!TextUtils.isEmpty(email))
mFirebaseDatabase.child(userId).child("email").setValue(email);
}
}
Inside ValueEventListener() check email address is exist or not
Try this
if(!dataSnapshot.child("users").child("email").exist)
then insert new value
If you are trying to create a rule for block user have 2 accounts with same email, you can use the rules inside firebase. There are rules ready for this.
Authentication -> Method -> botton functions.
I am writing an app to test out firebase where a user can list a product with images.
I'm having issues with the upload as although the pictures are stored, they are not linked to the product (images array not being passed?) and LeakCanary signals an outofmemory error.
All help and input appreciated.
Here's my Product Model
#IgnoreExtraProperties
public class Product {
public String uid;
public String seller;
public String name;
public String description;
public String city;
public double price = 0.0;
public List<Uri> images = new ArrayList<>();
public Product () {
}
public Product(String uid, String seller, String name, String description, String city, double price, List<Uri> images) {
this.uid = uid;
this.seller = seller;
this.name = name;
this.description = description;
this.city = city;
this.price = price;
this.images = images;
}
// [START post_to_map]
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("seller", seller);
result.put("name", name);
result.put("description", description);
result.put("city", city);
result.put("price", price);
result.put("images", images);
return result;
}
}
And here are is my AddProductActivity
public class AddProductActivity extends BaseActivity implements AddProductContract.View, View.OnClickListener {
private AddProductContract.Presenter mPresenter;
private Bitmap mBitmap;
private byte[] mByteArray;
private List<String> mPhotos;
private Button mPublishBtn;
private EditText mProductNameField;
private EditText mProductDescriptionField;
private EditText mProductPriceField;
private DatabaseReference mFirebaseDatabase;
private StorageReference mFirebaseStorage;
private StorageTask mUploadTask;
private List<Uri> uploadedImages = new ArrayList<>();
private LinearLayout mLinearLayout;
private ImageButton mImageButton;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
showEmptyImageError();
} else {
mPhotos = (List<String>) data.getSerializableExtra(GalleryActivity.PHOTOS);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_product_2);
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference();
mFirebaseStorage = FirebaseStorage.getInstance().getReference();
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mToolbar.setTitle(R.string.addItemTextview);
mLinearLayout = (LinearLayout) findViewById(R.id.activity_add_product);
mLinearLayout.setOnClickListener(this);
mImageButton = (ImageButton) findViewById(R.id.imageButton);
mImageButton.setOnClickListener(this);
mPublishBtn = (Button) findViewById(R.id.publishItemBtn);
mPublishBtn.setOnClickListener(this);
mProductNameField = (EditText) findViewById(R.id.productNameField);
mProductDescriptionField = (EditText) findViewById(R.id.productDescriptionField);
mProductPriceField = (EditText) findViewById(R.id.priceField);
// mPresenter = new AddProductPresenter(this);
}
#Override
public void onClick(View view) {
if ((view == mLinearLayout)) {
hideKeyboard();
} else if (view == mImageButton) {
GalleryConfig config = new GalleryConfig.Build()
.limitPickPhoto(8)
.singlePhoto(false)
.hintOfPick("You can pick up to 8 pictures.")
.filterMimeTypes(new String[]{"image/*"})
.build();
GalleryActivity.openActivity(AddProductActivity.this, 2, config);
} else if (view == mPublishBtn) {
final String name = mProductNameField.getText().toString();
final String description = mProductDescriptionField.getText().toString();
final double price = Double.parseDouble(mProductPriceField.getText().toString());
setPublishingEnabled(false);
showErrorToast(getResources().getString(R.string.publishing));
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mFirebaseDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
showErrorToast(getResources().getString(R.string.empty_user));
} else {
publishProduct(userId, user.getUsername(), name, description,
user.getCity(), price, mPhotos);
}
setPublishingEnabled(true);
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("AddProductActivity", "getUser:onCancelled", databaseError.toException());
setPublishingEnabled(true);
}
}
);
}
}
private void setPublishingEnabled(boolean enabled) {
if (enabled) {
mPublishBtn.setVisibility(View.VISIBLE);
} else {
mPublishBtn.setVisibility(View.GONE);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void showEmptyImageError() {
Toast.makeText(getApplicationContext(), R.string.empty_image_error, Toast.LENGTH_SHORT).show();
}
private void publishProduct(String userId, String seller, String name, String description,
String city, double price, List<String> images) {
for (String photo : images) {
Uri file = Uri.fromFile(new File(photo));
StorageReference photoRef = mFirebaseStorage.child("images/" + file.getLastPathSegment());
mUploadTask = photoRef.putFile(file);
mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
uploadedImages.add(downloadUrl);
}
});
}
String key = mFirebaseDatabase.child("products").push().getKey();
Product product = new Product(userId, seller, name, description, city, price, uploadedImages);
Map<String, Object> productValues = product.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/products/" + key, productValues);
childUpdates.put("/user-products/" + userId + "/" + key, productValues);
mFirebaseDatabase.updateChildren(childUpdates);
}
//
// private List<Uri> uploadPhotos(List<String> input) {
// images = new ArrayList<>();
// Observable.just(input)
// .map(this::doInBackground)
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .doOnSubscribe(this::onPreExecute)
// .subscribe(this::onPostExecute);
// return images;
// }
//
// private void onPreExecute() {
// Log.i("Start time", "SET");
// Toast.makeText(this, R.string.image_formatting_toast, Toast.LENGTH_SHORT).show();
// }
//
// private List<Uri> doInBackground(List<String> photos) {
// for (String photo : mPhotos) {
// Uri file = Uri.fromFile(new File(photo));
// StorageReference photoRef = mFirebaseStorage.child("images/" + file.getLastPathSegment());
// mUploadTask = photoRef.putFile(file);
//
// mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
// .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
// #Override
// public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Uri downloadUrl = taskSnapshot.getDownloadUrl();
// images.add(downloadUrl);
// }
// });
// }
// return images;
// }
//
// private void onPostExecute(List<Uri> uriSet) {
// Toast.makeText(this, R.string.product_visibility_toast, Toast.LENGTH_SHORT).show();
// Log.i("End time", "SET");
// }
}
Trying to understand your code flow, I can see one thing:
inside your publishProduct method you should put the code (to update the childeren in Firebase) into the addOnSuccessListener, like this:
private void publishProduct(String userId, String seller, String name, String description,
String city, double price, List<String> images) {
String key = mFirebaseDatabase.child("products").push().getKey();
for (String photo : images) {
Uri file = Uri.fromFile(new File(photo));
StorageReference photoRef = mFirebaseStorage.child("images/" + file.getLastPathSegment());
mUploadTask = photoRef.putFile(file);
mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
uploadedImages.add(downloadUrl);
Product product = new Product(userId, seller, name, description, city, price, uploadedImages);
Map<String, Object> productValues = product.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/products/" + key, productValues);
childUpdates.put("/user-products/" + userId + "/" + key, productValues);
mFirebaseDatabase.updateChildren(childUpdates);
}
});
}
}
And, if you want to know if the updateChildren operation is completed or not, add the onComplete and onFailure listeners, like this:
mFirebaseDatabase.updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Update
I think you can try to change your database structure, removing the list of images from the product's nodes, adding instead a node in your database that will store only the list of images associated with each product:
"/product-images/" + yourKey + "/" + imageKey
contains the list of his images. imageKey is different from one image the another (it could be for example the image name). yourKey could be the userId or the key associated with each product, it depends on how the database is structured. Then, you can try to use setValue instead of updateChildren into your OnSuccessListener, something like this:
mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
mFirebaseDatabase.child("product-images").child(yourKey).child(imageKey).setValue(downloadUrl.toString());
}
});
Hope this helps!