使用Firebase-UI,Firestore作为数据库和Picasso,图像不会出现在RecyclerView中

时间:2018-07-24 13:48:06

标签: android firebase google-cloud-firestore firebase-storage firebaseui

我正在使用 Firebase-UI Firestore Firebase Storage URL字符串加载图像,并显示在 RecyclerView 中>使用毕加索

我在数据库中有2个变量:名称和图像url,名称出现在recyclerview中,但是图像不是什么原因,导致图像不出现。

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:id="@+id/text_view_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text="Name"
        android:textColor="@android:color/black"
        android:textSize="20sp" />
    <ImageView
        android:id="@+id/image_view_upload"
        android:layout_width="match_parent"
        android:layout_height="200dp" />
</LinearLayout>

 public class Upload {
 private String mName;
 private String mImageUrl;

 public Upload() {
 //empty constructor needed
 }

 public Upload(String name, String imageUrl) {
 if (name.trim().equals("")) {
      name = "No Name";
 }

 mName = name;
 mImageUrl = imageUrl;
 }

 public String getName() {
 return mName;
 }

 public void setName(String name) {
 mName = name;
 }

 public String getImageUrl() {
 return mImageUrl;
 }

 public void setImageUrl(String imageUrl) {
 mImageUrl = imageUrl;
 }
   }

打包com.example.amr.firebasestorage;

 public class ImageActivity extends AppCompatActivity {
 private RecyclerView recyclerView;

 private FirebaseFirestore firebaseFirestor;
 private FirestoreRecyclerAdapter<Upload, ImageActivity.ImageViewHolder> 
 Adapter;

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

 //=========firebase==============
 firebaseFirestor = FirebaseFirestore.getInstance();
 //===============================
 //==========Recycler Items========
 recyclerView = findViewById(R.id.recycler_view);
 recyclerView.setHasFixedSize(true);
 recyclerView.setLayoutManager(new LinearLayoutManager(this));

 Query query = firebaseFirestor.collection("uploads")
    ;
 FirestoreRecyclerOptions<Upload> options = new FirestoreRecyclerOptions.Builder<Upload>()
     .setQuery(query, Upload.class)
     .build();
 Adapter = new FirestoreRecyclerAdapter<Upload, ImageViewHolder>(options) {
      @Override
      protected void onBindViewHolder(@NonNull ImageViewHolder holder, int 
      position, @NonNull Upload model) {


      holder.setName(model.getName());

                holder.setImageUrl(model.getImageUrl());


      }

      @NonNull
      @Override
      public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, 
      int viewType) {
      View view = LayoutInflater.from(parent.getContext())
          .inflate(R.layout.image_item, parent, false);

      return new ImageViewHolder(view);
      }
 };
 recyclerView.setAdapter(Adapter);


 }

 public class ImageViewHolder extends RecyclerView.ViewHolder {
 public TextView textViewName;
 public ImageView imageView;
 View mView;

 public ImageViewHolder(View itemView) {
      super(itemView);
      mView=itemView;
      imageView = mView.findViewById(R.id.image_view_upload);

 }

 public void setName(String name) {
      textViewName = mView.findViewById(R.id.text_view_name);
      textViewName.setText(name);
 }
    public void setImageUrl(String imageUrl) {
         imageView = mView.findViewById(R.id.image_view_upload);

         Picasso.get()
                 .load(imageUrl)
                 .fit()
                 .into(imageView);
     }


 }

 @Override
 public void onStart() {
 super.onStart();
 Adapter.startListening();
 }

 @Override
 public void onStop() {
 super.onStop();
 if ( Adapter != null ) {
      Adapter.stopListening();
 }
 }
     }

//主要活动

public class MainActivity extends AppCompatActivity {
 private static final int PICK_IMAGE_REQUEST = 1;

 private Button mButtonChooseImage;
 private Button mButtonUpload;
 private TextView mTextViewShowUploads;
 private EditText mEditTextFileName;
 private ImageView mImageView;
 private ProgressBar mProgressBar;

 private Uri mImageUri;


 //_________
 private StorageTask storageTask;
 private StorageReference storageReference;
 private DocumentReference firebaseFirestore;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 mButtonChooseImage = findViewById(R.id.button_choose_image);
 mButtonUpload = findViewById(R.id.button_upload);
 mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
 mEditTextFileName = findViewById(R.id.edit_text_file_name);
 mImageView = findViewById(R.id.image_view);
 mProgressBar = findViewById(R.id.progress_bar);
 //________
 storageReference = FirebaseStorage.getInstance().getReference("uploads");
 firebaseFirestore = FirebaseFirestore.getInstance().collection("uploads").document();
 mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      openFileChooser();
      }
 });

 mButtonUpload.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      if ( storageTask != null && storageTask.isInProgress() ) {
           Toast.makeText(MainActivity.this, "wait", Toast.LENGTH_SHORT).show();
      } else {
           uploadFiles();

      }
      }
 });

 mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      openImagesActivity();
      }
 });
 }

 private void openImagesActivity() {
 Intent inten = new Intent(this, ImageActivity.class);
 startActivity(inten);

 }

 private String getFileExtension(Uri uri) {
 ContentResolver contentResolver = getContentResolver();
 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
 return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));

 }

 private void uploadFiles() {
 if ( mImageUri != null ) {
      StorageReference fileRef = storageReference
     //
     .child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
      //.child("Photos").child(mImageUri.getLastPathSegment());
      storageTask = fileRef.putFile(mImageUri)


     .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
          @Override
          public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
          Handler handler = new Handler();
          handler.postDelayed(new Runnable() {
               @Override
               public void run() {
               mProgressBar.setProgress(0);
               }
          }, 500);
          Toast.makeText(MainActivity.this, "Upload succesful", Toast.LENGTH_SHORT).show();
          Uri downloadUri = taskSnapshot.getUploadSessionUri();

          assert downloadUri != null;
          Upload upload = new Upload(mEditTextFileName
              .getText().toString().trim()
              , downloadUri.toString());

          firebaseFirestore.set(upload);
          }
     })


     .addOnFailureListener(new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
          Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
          }
     })


     .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
          @Override
          public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
          double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
          mProgressBar.setProgress((int) progress);
          }
     });
 } else {
      Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
 }

 }

 public void openFileChooser() {
 Intent intent = new Intent();
 intent.setType("image/*");
 intent.setAction(Intent.ACTION_GET_CONTENT);
 startActivityForResult(intent, PICK_IMAGE_REQUEST);
 }

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

 if ( requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
     && data != null && data.getData() != null ) {
      mImageUri = data.getData();//something back
      Picasso.get().load(mImageUri).into(mImageView);
 }
 }

}

my database

my mobile pic

2 个答案:

答案 0 :(得分:0)

问题在于,您的模型类中的mName字段的getter不正确。当您将getName()用作吸气剂时,Firebase会像现在的代码一样,照管一个名为name not mName的字段。看到不同?正确的模型类应如下所示:

public class Upload {
    private String name;
    private String imageUrl;

    public Upload() {}

    public Upload(String name, String imageUrl) {
        this.name = name;
        this.imageUrl = imageUrl;
    }

    public String getName() { return name; }

    public String getImageUrl() { return imageUrl; }
}

设置程序不是必需的,它们始终是可选的,因为如果JSON属性没有设置程序,Firebase客户端将直接在字段上设置值。但是,如果您想使用设置器,则适用于您字段的正确设置器是:

public void setName(String name) { this.name = name; }

public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }

答案 1 :(得分:0)

我修好了 问题不在setter和getter中,而在这里

          Uri downloadUri = taskSnapshot.getUploadSessionUri();

这不是显示我已被其替换的正确链接

              Uri downloadUri = taskSnapshot.getDownloadUrl();

工作完美