错误:找不到com.google.firebase.storage.UploadTask.TaskSnapshot类型的符号方法getDownloadUrl()

时间:2018-05-27 17:06:30

标签: android firebase firebase-storage

在gradle更新之前,一切正常,但稍后会弹出此错误。我已经提到了官方文档,它提供了相同的代码。 Not accepting the getDownloadUrl() method

我添加了最新的正确依赖项,并且gradle sync成功。 app/build.gradle

这是firebase文档中提供的示例代码,与我的相同。 Firebase Assistant

即使所有必需的东西都存在,我也无法理解可能出现的问题。坚持这2天,请帮忙!

7 个答案:

答案 0 :(得分:9)

Doug指出,UploadTask.getDownloadUrl()已被弃用,因此请使用StorageReference.getDownloadUrl()

但StorageReference.getDownloadUrl()返回任务,必须异步处理, 执行Uri downloadUrl = photoRef.getDownloadUrl().getResult();否则您将获得java.lang.IllegalStateException: Task is not yet complete

因此,像这样异步处理它

 photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        Uri downloadUrl = uri;
                        Toast.makeText(getBaseContext(), "Upload success! URL - " + downloadUrl.toString() , Toast.LENGTH_SHORT).show();
                    }
                });

答案 1 :(得分:4)

如果您有'image_uri'并将其放入firebase存储空间,则此代码可以为您提供帮助。

private StorageReference storageReference= FirebaseStorage.getInstance().getReference();

 final StorageReference ref = storageReference.child("picture.jpg");
    ref.putFile(image_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    final Uri downloadUrl = uri;


                }
            });

答案 2 :(得分:4)

getDownloadUrl不再存在。

所以新方法是:

final StorageReference ref = storageRef.child("images/mountains.jpg");
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();
        } else {
            // Handle failures
            // ...
        }
    }
});

Firebase doc

答案 3 :(得分:3)

UploadTask.getDownloadUrl()已弃用。请改用StorageReference.getDownloadUrl()

答案 4 :(得分:2)

对于Kotlin

val uploadTask = fileReference.putFile(Uri.fromFile(primaryFile), metadata)

        uploadTask
                .addOnProgressListener { taskSnapshot ->

                }

                .addOnPausedListener { 

                }

                .addOnSuccessListener { taskSnapshot ->
                }
                .continueWithTask { task ->
                    if (!task.isSuccessful) {
                        throw task.exception!!
                    }
                 fileReference.downloadUrl
                }

                .addOnCompleteListener { task ->

                    if (task.isSuccessful) {
                        val downloadUrl: Uri = task.result

                    } else {
                        // Handle failures
                    }
                }

                .addOnFailureListener { e ->

                }

val downloadUrl是您上载的URL。

答案 5 :(得分:0)

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Map newImage = new HashMap();
            newImage.put("profileImageUrl", uri.toString());
            mDriverDatabase.updateChildren(newImage);

            finish();
            return;
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            finish();
            return;
        }
    });
}

}); **我们可以通过这种方式使用获取下载网址,因为firebase进行了一些更改**

答案 6 :(得分:0)

尝试此代码。

public class MainActivity extends AppCompatActivity {

String LOG_TAG = MainActivity.class.getSimpleName();

Button buttonUpload, buttonDownload;
RadioGroup radioGroup;
ImageView imageviewResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonUpload = findViewById(R.id.upload_button);
    buttonDownload = findViewById(R.id.download_button);
    radioGroup = findViewById(R.id.radio_group);
    imageviewResult = findViewById(R.id.resultant_imageview);

    buttonUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadImage();
        }
    });

    buttonDownload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            downloadImage();
        }
    });
}

private void uploadImage() {
    // Start by getting our StorageReference
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference rootRef = storage.getReference();
    StorageReference bearRef = rootRef.child("images/bear.jpg");
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Uploading");
    progressDialog.show();

    // Get the data from the image as bytes
    ImageView bearImage = getSelectedBearImage();
    bearImage.setDrawingCacheEnabled(true);
    bearImage.buildDrawingCache();
    Bitmap bitmap = bearImage.getDrawingCache();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();

    // Upload it to our reference
    UploadTask uploadTask = bearRef.putBytes(data);
    buttonDownload.setEnabled(false);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            progressDialog.dismiss();

            Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            progressDialog.dismiss();

            Log.d(LOG_TAG, "Download Url: " + downloadUrl);
            buttonDownload.setEnabled(true);
        }
    });
}

private void downloadImage() {
    // Start by getting a reference to the same location we uploaded to
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference rootRef = storage.getReference();
    StorageReference bearRef = rootRef.child("images/bear.jpg");
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Uploading");
    progressDialog.show();

    // Download our data with a max allocation of 1MB
    final long ONE_MEGABYTE = 1024 * 1024;
    bearRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
        @Override
        public void onSuccess(byte[] bytes) {
            // Convert bytes to bitmap and call setImageBitmap
            progressDialog.dismiss();
            Log.d(LOG_TAG, "Download successful");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            imageviewResult.setImageBitmap(bitmap);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
            progressDialog.dismiss();

            Log.w(LOG_TAG, "Download failed: " + exception.getMessage());
        }
    });
}

private ImageView getSelectedBearImage() {
    switch (radioGroup.getCheckedRadioButtonId()) {
        case R.id.radio1:
            return findViewById(R.id.image_bear1);
        case R.id.radio2:
            return findViewById(R.id.image_bear2);
        case R.id.radio3:
            return findViewById(R.id.image_bear3);
        case R.id.radio4:
            return findViewById(R.id.image_bear4);
        default:
            return findViewById(R.id.image_bear1);
    }
}

}

activity.xml ..

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.adruser.firebasestorageapp.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="96dp"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/image_bear1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/a"/>
    <ImageView
        android:id="@+id/image_bear2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/tiger"/>
    <ImageView
        android:layout_width="0dp"
        android:id="@+id/image_bear3"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/download"/>
    <ImageView
        android:layout_width="0dp"
        android:id="@+id/image_bear4"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/add"/>
</LinearLayout>

<RadioGroup
    android:id="@+id/radio_group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:checked="true"
        android:layout_height="wrap_content" />
    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <RadioButton
        android:id="@+id/radio3"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <RadioButton
        android:id="@+id/radio4"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
</RadioGroup>

<TextView
    android:layout_marginTop="16dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Downloaded Image"/>

<ImageView
    android:id="@+id/resultant_imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"/>

<Button
    android:id="@+id/upload_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp"
    android:text="Upload"/>

<Button
    android:id="@+id/download_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:layout_marginTop="8dp"
    android:text="Download"/>

</LinearLayout>

我希望您将Firebase存储与之联系并给予Internet许可。.

    <uses-permission android:name="android.permission.INTERNET"/>

更多信息,请参见此链接。 https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934

相关问题