I'm trying to store an image with some relevant data regarding that image in Firebase. When I press the save button, the image is saved into my storage folder no problem, but the Database attributes just aren't being saved and I can't figure out why. This is my code:
String Storage_Path = "All_Book_Images";
String Database_Path = "All_Books";
Uri FilePathUri;
StorageReference storageReference;
DatabaseReference databaseReference;
int Image_Request_Code = 71;
ProgressDialog progressDialog;
Button imageButton, saveButton;
EditText title, author, price, category, additionalInfo;
ImageView SelectImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookupload);
SelectImage = (ImageView) findViewById(R.id.book_image);
title = (EditText) findViewById(R.id.title_text);
author = (EditText) findViewById(R.id.author_text);
price = (EditText) findViewById(R.id.price_text);
category = (EditText) findViewById(R.id.category_text);
additionalInfo = (EditText) findViewById(R.id.info_text);
storageReference = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
}
public void imageButton(View view){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"),0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == RESULT_OK){
FilePathUri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
SelectImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getActualImage(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
public void uploadData(View view){
if(FilePathUri != null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference reference = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + getActualImage(FilePathUri));
reference.putFile(FilePathUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String Title = title.getText().toString();
String Author = author.getText().toString();
String Price = price.getText().toString();
String Category = category.getText().toString();
String AdditionalInfo = additionalInfo.getText().toString();
Book book = new Book(taskSnapshot.getDownloadUrl().toString(), Title, Author, Price, Category, AdditionalInfo);
String id = databaseReference.push().getKey();
databaseReference.child(id).setValue(book);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Data uploaded",Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@SuppressWarnings("VisibleForTests")
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double totalProgress = (100*taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded % " + (int)totalProgress);
}
});
} else {
// show message
Toast.makeText(getApplicationContext(),"Please select data first",Toast.LENGTH_LONG).show();
}
}
What's causing this to interact with the Storage aspect of Firebase fine, but not the Database?
Check this snippet from Firebase Official Doc, i have writen some of your requirement inside, but you get the idea
private void writeNewPost(String Title, String Price, String Author) {
String key = databaseReference.push().getKey();
Post post = new Post(Title, Price, Author);
Map<String, Object> postValues = post.toMap();
Map<String, Object> books = new HashMap<>();
books.put(Title, postValues);
books.put(Price, postValues);
books.put(Author, postValues);
mDatabase.child(key).updateChildren(books);
}
for more info : https://firebase.google.com/docs/database/android/read-and-write
PS: you can use updateChildren()
or setValue()
, it depends which one you need.
If you use setValue()
in this way, the data is overwritten at the specified location, including the secondary nodes.
You can make simultaneous updates to multiple locations in the JSON tree with a single call to updateChildren()
.
It turns out that my code was actually working OK, I just had the rules of my Firebase Database set up incorrectly. The code I posted in the question should work for anyone trying to implement this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.