我在做一个博客应用程序。 我想让编辑器喜欢quora,这样我就可以从用户那里获取文本和图像,并将其保存到firebase,然后将其检索回来显示在文本视图中,供其他用户通过feed点击它。 如何使此文本查看和编辑文本?
像这样
假设您的问题是关于先将文本和图像上传到firebase的Firestore中,您需要将图像上传到firebase存储并获取下载URI
// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
Uri file = Uri.fromFile(new File(IMAGE PATH));
final StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = ref.putFile(file);
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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
// TODO NEXT PART
} else {
// Handle failures
// ...
}
}
});
在获得下载uri之后,将uri和textView都上传到Firestore,如下所示
Map<String, String> post = new HashMap<>();
user.put("text", myPostEditText.getText().toString());
user.put("image", downloadUri);
FirebaseFirestore db = FirebaseFirestore.getInstance();
// Add a new document with a generated ID
db.collection("posts")
.add(post)
所以保存上传的最后代码应该是这样的
// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
Uri file = Uri.fromFile(new File(IMAGE PATH));
final StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = ref.putFile(file);
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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Map<String, String> post = new HashMap<>();
user.put("text", myPostEditText.getText().toString());
user.put("image", downloadUri);
FirebaseFirestore db = FirebaseFirestore.getInstance();
// Add a new document with a generated ID
db.collection("posts")
.add(post).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(MainActivity.this, "Uploaded successfully", Toast.LENGTH_SHORT).show();
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
} else {
// Handle failures
// ...
}
}
});