从Firebase Storage

时间:2016-09-26 12:01:37

标签: android firebase firebase-storage

我正在尝试使用Firebase存储和检索图像。存储图像时可以,但我无法在ImageView中显示它。它不会出错,所以我无法理解错误在哪里。

public class MainActivity extends AppCompatActivity {

private Button btnSelectImage;
private ImageView mImageView;

private StorageReference mStorage;

private static final int CAMERA_REQUEST_CODE = 1 ;

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

    btnSelectImage = (Button) findViewById(R.id.btn_image);
    mImageView = (ImageView) findViewById(R.id.imageView);

    //Get instance
    mStorage = FirebaseStorage.getInstance().getReference();

    btnSelectImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_REQUEST_CODE);

        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==CAMERA_REQUEST_CODE && resultCode==RESULT_OK){

        Uri uri = data.getData();

        StorageReference filePath = mStorage.child("CameraPhotos").child(uri.getLastPathSegment());
        filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                //Show image
                Uri downloadUri = taskSnapshot.getDownloadUrl();
                Picasso.with(MainActivity.this).load(downloadUri).into(mImageView);

                Toast.makeText(MainActivity.this,"Upload Done",Toast.LENGTH_SHORT).show();
                Log.v("Test","image load");

            }
        });


    }
}
}

还提供权限

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

以下是我的Firebase存储规则

service firebase.storage {
  match /b/fir-app-ce89f.appspot.com/o {
    match /{allPaths=**} {
      allow read, write: if true;
    }
  }
}

这是我的活动布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.yusuf.firebaseapp.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Image"
        android:id="@+id/btn_image"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="400dp"
        android:layout_height="350dp"
        android:id="@+id/imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

3 个答案:

答案 0 :(得分:7)

我建议您查看FirebaseUI 0.6,其中包含一个Glide插件,可以从Firebase存储中下载图片,简单如下:

// Reference to an image file in Firebase Storage
StorageReference storageReference = ...;

// ImageView in your Activity
ImageView imageView = ...;

// Load the image using Glide
Glide.with(this /* context */)
        .using(new FirebaseImageLoader())
        .load(storageReference)
        .into(imageView);

答案 1 :(得分:1)

我认为使用这种方式会更容易

StorageReference mImageRef = 
FirebaseStorage.getInstance().getReference("image/test.jpg");
    final long ONE_MEGABYTE = 1024 * 1024;
    mImageRef.getBytes(ONE_MEGABYTE)
    .addOnSuccessListener(new onSuccessListener<byte[]>() {
        @Override
        public void onSuccess(byte[] bytes) {
            Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);

            imageView.setMinimumHeight(dm.heightPixels);
            imageView.setMinimumWidth(dm.widthPixels);
            imageView.setImageBitmap(bm);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
        }
    });

答案 2 :(得分:0)

    private List<Upload> uploads;
    Upload upload = uploads.get(position);
    Glide.with(context).load(upload.getUrl()).into(holder.imageView);