从 firebase(数据库)下载 url 失败

fail get download url from firebase(database)

我用 simple 示例将文件上传到 firebase。下载后,我将下载的 sting 文件推送到数据库。当我从 debagger all fine.When 执行此操作时,我只是启动应用程序文件将被上传,但我的数据库中没有下载 url。

onClick 中启动下载方法并推送到数据库后:

  public void button_click(){
    auth = FirebaseAuth.getInstance();
    FirebaseUser user = auth.getCurrentUser();
    if (user != null) {
        // User is signed in
        String temp = upload(user);
        //temp = FirebaseStorage.getInstance().getReference().child("User: "+user.getUid()+"/"+"img.jpg").getDownloadUrl().toString();

        GPSTracker gps = new GPSTracker(this);
        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        database =  FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference(user.getUid());
        Map<String, User> users = new HashMap<String, User>();
        users.put("User data: " , new User(String.valueOf(latitude)+"/"+String.valueOf(longitude),temp));
        myRef.setValue(users);

       // Intent i = new Intent(CameraFoto.this, pc.dd.sex_startup.LogIn.Maps.Map.class);
       // startActivity(i);
       // finish();
    } else {
        // No user is signed in
    }
}

上传方式(见onSuccess):

 public String upload (FirebaseUser user){
    final String[] dwndurl = new String[1];
    // File or Blob
    Uri file = Uri.fromFile(new File("/storage/emulated/0/VK/img.jpg"));// Create the file metadata
    StorageMetadata  metadata = new StorageMetadata.Builder()
            .setContentType("image/jpeg")
            .build();
    //get storage
    FirebaseStorage storage = FirebaseStorage.getInstance();// Create a storage reference from our app
    StorageReference storageRef = storage.getReferenceFromUrl("gs://sexstartup-e3a65.appspot.com");// Upload file and metadata to the path 'images/mountains.jpg'
    UploadTask  uploadTask = storageRef.child("User: "+user.getUid()+"/"+file.getLastPathSegment()).putFile(file, metadata);// Listen for state changes, errors, and completion of the upload.
    uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
            int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
            ProgressBar progressBar = (ProgressBar) findViewById(R.id.upload_progress);
            progressBar.setProgress(progress);
            System.out.println("Upload is " + progress + "% done");
            Log.d("---","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
            Log.d("---","Upload false " + exception.getMessage());

        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // Handle successful uploads on complete
            Uri downloadUrl = null;
            do{
                downloadUrl = taskSnapshot.getDownloadUrl();
                dwndurl[0] = downloadUrl.toString();
                    }
            while (dwndurl[0]==null);
            Toast.makeText(getApplicationContext(),"Upload done",Toast.LENGTH_SHORT).show();

        }
    });

    return dwndurl[0];
}}

Json 在 dubbug 应用程序时在 Firebase 数据库中:

{
"2Yrkr7YWqHYm1Yzg9NHpDcXDz2N2" : {
"User data: " : {
  "lat" : "47.8405892/35.1428222",
  "url" : "https://firebasestorage.googleapis.com/v0/b/sexstartup-e3a65.appspot.com/o/User%3A+2Yrkr7YWqHYm1Yzg9NHpDcXDz2N2%2Fimg.jpg?alt=media&token=dfefa9cd-89e7-4cf2-980c-c45bad3d39a5"
} },

Json 刚启动应用时在 Firebase 数据库中:

{
"2Yrkr7YWqHYm1Yzg9NHpDcXDz2N2" : {
"User data: " : {
  "lat" : "47.8405892/35.1428222",
} },

怎么了?

知道了..

您期待的是:

{
"2Yrkr7YWqHYm1Yzg9NHpDcXDz2N2" : {
"User data: " : {
  "lat" : "47.8405892/35.1428222",
  "url" : "https://firebasestorage.googleapis.com/v0/b/sexstartup-e3a65.appspot.com/o/User%3A+2Yrkr7YWqHYm1Yzg9NHpDcXDz2N2%2Fimg.jpg?alt=media&token=dfefa9cd-89e7-4cf2-980c-c45bad3d39a5"
} },

但是得到这个:

{
"2Yrkr7YWqHYm1Yzg9NHpDcXDz2N2" : {
"User data: " : {
  "lat" : "47.8405892/35.1428222",
} },

原因:您的上传任务是异步的。您的上传任务开始,代码执行移至下一条语句。即 return dwndurl[0];。结果,它将 return null.

因此,您在 String temp = upload(user); 的温度将为 null。从您面临的问题,可以确认 null 值从未被存储。甚至,他们的键也不存在于数据库结构中。

这是我理解的。

我也遇到过这个问题所以你要做的是:

转到 Firebase 数据库,然后 select 显示在顶部的规则选项卡,然后将读写设置为 true。

{

"rules":{

".read": "true",
".write": "true"

}

}

希望对你有所帮助:)