我正在Android Studio中制作一个应用程序,并且正在使用Firebase Storage将用户信息存储在单独的文本文件中,然后再上传到该应用程序的用户仪表板中。我已经编写了所有代码来执行此操作,并且尽我所能遵循了Firebase文档。当我运行我的应用程序(在我的摩托罗拉moto e5手机上经过测试)时,一切运行正常,然后创建了包含用户信息的文件。然后应该将其上载到Firebase存储部分,然后将其销毁。我知道第一件事和最后一件事情都发生了。
问题
但是,当我进入Firebase检查文件是否存在时。因此,我去检查Android Studio是否返回了任何错误,并且没有看到任何错误,并且一切运行顺利,但是 我没有看到Firebase中应该上传的文件 。因此,我在Internet上四处寻找,四分之一地看,一遍又一本的文档,我都尝试了。如果您发现某些对我没有帮助的信息,请共享链接。另外,如果您知道问题出在哪里,请分享。
故障排除方法
更具体地说,这些是我尝试过的一些事情:
build.gradle
文件中的依赖项中更改SDK版本,并确保它们都是最新的并尝试使用旧版本。file.delete();
行代码
此方法在被调用时应通过将其输入保存在名为0.txt
,1.txt
,2.txt
等的文件中来创建用户想要完成的“目标”。然后,该方法应将文件上传到Firebase Storage,这就是问题所在。它不会出现在数据库中。
private void createGoal(String activity, String timeframe, String number, String unit) throws IOException {
//creates an instance of the Main Dashboard class inorder to access the variable counterString.
MainDashboard dBoard = new MainDashboard();
//Names the 0.txt, 1.txt, 2.txt, and so on
file = new File(dBoard.counterString + ".txt");
//Creates the actual file
file.createNewFile();
//Creates the writer object that will write to the file
FileWriter writer = new FileWriter(file);
//Writes to the text file
writer.write(activity + " : " + "0 / "+ number + " " + unit + " in " + timeframe);
//Closes the Writer
writer.close();
//Creates a Uri from the file to be uploaded
upload = Uri.fromFile(new File(activity + ".txt"));
//Uploads the file exactly as the documentation says, but it doesn't work
UploadTask uploadTask = storageRef.putFile(upload);
//Deletes the file from the local system
file.delete();
}
任何想法都得到赞赏。
答案 0 :(得分:0)
调用putFile
Firebase时,开始在后台上传数据,以便您的用户可以继续使用该应用。但是您的代码此后会立即在本地文件上调用delete
,这意味着您要在Firebase完成(甚至可能开始)上传之前删除本地文件。
诀窍是如Firebase文档中所示monitor the upload progress,并且仅在上传完成后才删除本地文件。
基于该文档中的示例:
// Listen for state changes, errors, and completion of the upload.
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
System.out.println("Upload is " + progress + "% done");
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
@Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
// ...
//Deletes the file from the local system
file.delete();
}
});