如何从Android上的Firebase存储下载图像?

时间:2017-08-16 01:45:47

标签: android firebase firebase-storage

我使用Firebase存储来存储图片。我无法在Android上下载这些内容。我想下载文件夹的所有图像但是现在我只想下载一个,因为我还不知道如何将所有图像下载到列表中。 我正在尝试这个

public static final String TAG = "AtividadesFragment";
    ImageView imageView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_atividades,container,false);
        Log.i(TAG,"onCreateView()");
        imageView = (ImageView) v.findViewById(R.id.image);
        return v;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference ref = storage.getReference().child("ImagensExercicios/abdominal_1.bmp");

        Glide.with(getActivity()).using(new FirebaseImageLoader()).load(ref).into(imageView);
    }

XML:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

但没有任何反应。

enter image description here

2 个答案:

答案 0 :(得分:2)

您正尝试将StorageReference加载到带有Glide的ImageView中:

StorageReference ref = storage.getReference().child("ImagensExercicios/abdominal_1.bmp");
Glide.with(getActivity()).using(new FirebaseImageLoader()).load(ref).into(imageView);

这不是StorageReference对象的工作方式。 StorageReference只是指向存储桶中文件的指针。如果要下载其内容,则需要fetch a download URL from it first,等待该任务异步完成,然后使用该URL加载到ImageView中。

答案 1 :(得分:2)

我使用以下代码从Firebase存储中获取jpg图像。 为了得到bmp图像,我认为区别在于File.createTempFile(“Images”,“jpg”)//或bmp的参数。 我希望它对你也有用。

private Bitmap my_image;
StorageReference ref = storage.getReference().child("ImagensExercicios/abdominal_1.bmp");
try {
      final File localFile = File.createTempFile("Images", "bmp");
      ref.getFile(localFile).addOnSuccessListener(new OnSuccessListener< FileDownloadTask.TaskSnapshot >() {
          @Override
          public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
              my_image = BitmapFactory.decodeFile(localFile.getAbsolutePath());
          }
      }).addOnFailureListener(new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
              Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
          }
      });
} catch (IOException e) {
      e.printStackTrace();
}

还有一点需要注意,我在AsyncTask类中使用此代码来实现异步任务行为。

相关问题