recyclerview中未显示图像

问题描述 投票:1回答:2

我正在尝试制作一个用户可以注册帐户并可以上传图片的应用。我得到了上载部分的压缩包,但我想在其个人资料页面上将这些图像检索给用户,但我不知道该怎么做。有人可以告诉我如何检索那些我想使用回收站视图的图像。提前致谢。下面是我的代码

//上传图片类

public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener {

    int PICK_IMAGE_REQUEST=234;
    private Button upload,button2;
    private ImageView imageView;
    private Uri filepath;
    FirebaseAuth firebaseAuth;
    FirebaseUser firebaseUser;
    FirebaseDatabase firebaseDatabase;
    TextView next;

    FirebaseStorage firebaseStorage;
    StorageReference storageReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_ad);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);


        firebaseStorage=FirebaseStorage.getInstance();
        storageReference=firebaseStorage.getReference();
        next=findViewById(R.id.next0);

        firebaseUser= firebaseAuth.getInstance().getCurrentUser();
        firebaseDatabase.getInstance().getReference();



        upload=findViewById(R.id.button_upload);
        button2=findViewById(R.id.submit);
        imageView=findViewById(R.id.view_image);

        upload.setOnClickListener(this);


    }

    private void showFileChooser(){
        Intent intent=new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Choose an image"),PICK_IMAGE_REQUEST);

    }

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

        if(requestCode== PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                && data != null
                && data.getData() != null){
            next.setTextColor(Color.parseColor("#FF4500"));
            next.setEnabled(true);



            filepath=data.getData();




            try {
                // Bitmap bitmap=new Compressor(this).setMaxHeight(200) //Set height and width
                // .setMaxWidth(200)
                //.setQuality(100) // Set Quality
                //.compressToBitmap(file);
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
                imageView.setImageBitmap(bitmap);
                // build alert dialog


            } catch (IOException e) {
                e.printStackTrace();
            }







        }


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

                if(filepath != null) {



                    final ProgressDialog progressDialog=new ProgressDialog(UploadAdActivity.this);
                    progressDialog.setTitle("Uploading");
                    progressDialog.show();


                    int aNumber = (int) (20 * Math.random()) + 1;


                    //StorageReference riversRef=storageReference.child(firebaseUser.getUid()+"/"+"image.png");
                    // StorageReference=firebaseStorage.getInstance().getReferenceFromUrl()
                    StorageReference riversRef = storageReference.child(System.currentTimeMillis()+"."+getExtension(filepath));

                    //final String url=riversRef.getDownloadUrl().getResult().toString();
                    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
                    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Users");
                    final DatabaseReference update = rootRef.child(uid).child("images");





                    riversRef.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            progressDialog.dismiss();
                            Toast.makeText(UploadAdActivity.this,"Uploaded successfully",Toast.LENGTH_LONG).show();
                            storageReference.getDownloadUrl();
                            taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    String download_url=uri.toString();
                                    update.child("images").setValue(download_url);

                                }
                            });
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            progressDialog.dismiss();
                            Toast.makeText(UploadAdActivity.this,"Failed to upload",Toast.LENGTH_LONG).show();
                        }
                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                                    .getTotalByteCount());
                            progressDialog.setMessage("Uploaded "+(int)progress+"%");                }
                    });




                }


            }


        });

    }

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

    };


    @Override
    public void onClick(View v) {

        if(v==upload){
            showFileChooser();
            //uploadImage();
            next.setTextColor(Color.parseColor("#FF4500"));



            /*
            Intent i = new Intent(UploadAdActivity.this, ActionActivity.class);
            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(i);

             */

        }



    }






}

//Users profile
 public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {

   private RecyclerView recyclerView;
   private ImageAdapter mAdapter;

   private DatabaseReference databaseReference;
   private List<Upload> mUploads;
   FirebaseAuth firebaseAuth;
   FirebaseUser firebaseUser;
    int PICK_IMAGE_REQUEST=234;
    private Button upload,button2;
    private ImageView imageView;
    private Uri filepath;
    FirebaseDatabase firebaseDatabase;
    FirebaseStorage firebaseStorage;
    StorageReference storageReference;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        overridePendingTransition(R.anim.slide_right, R.anim.slide_left);

        mUploads=new ArrayList<>();

        mAdapter=new ImageAdapter(ProfileActivity.this, mUploads);


        recyclerView=findViewById(R.id.recyclerView);
        //recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);

        firebaseStorage=FirebaseStorage.getInstance();
        storageReference=firebaseStorage.getReference();

        firebaseUser= firebaseAuth.getInstance().getCurrentUser();
        firebaseDatabase.getInstance().getReference();



        upload=findViewById(R.id.button_upload);
        button2=findViewById(R.id.submit);
        imageView=findViewById(R.id.view_image);
        upload.setOnClickListener(this);



        String uid=FirebaseAuth.getInstance().getCurrentUser().getUid();




        databaseReference=FirebaseDatabase.getInstance().getReference();
        //databaseReference.child("images");

        databaseReference.orderByChild(uid).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot postsnapshot:dataSnapshot.getChildren()){

                    Upload upload=postsnapshot.getValue(Upload.class);
                    mUploads.add(upload);


                }

                mAdapter.notifyDataSetChanged();




            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();

            }
        });




        recyclerView.setAdapter(mAdapter); //Again set adapter to recyclerview




    }

   //Adapter class
   public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>{

    private Context mContext;
    private List<Upload> mUploads;

    public ImageAdapter(Context context,List<Upload> uploads){
        mContext = context;
        mUploads = uploads;

    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View V = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
        return new ImageViewHolder(V);


    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        Upload uploadCurrent=mUploads.get(position);
        Picasso.get().load(uploadCurrent.getmImageUrl()).fit().centerCrop().into(holder.imageView);

    }

    @Override
    public int getItemCount() {
        return mUploads.size();

    }

    public class ImageViewHolder extends RecyclerView.ViewHolder{
        public ImageView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);

            imageView=itemView.findViewById(R.id.imageview);
        }
    }
}

   //Upload class

  public class Upload {
    private String images;

    public Upload(){
        //Empty constructor needed
    }

    public Upload (String imageUrl){
        images=imageUrl;

    }

    public String getmImageUrl() {
        return images;
    }

    public void setmImageUrl(String images) {
        this.images = images;
    }
}

Updated Database Structure

Firebase storage

java android firebase firebase-realtime-database firebase-storage
2个回答
1
投票

放入recyclerView.setAdapter(mAdapter);

之后

databaseReference.orderByChild(uid).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot postsnapshot:dataSnapshot.getChildren()){

                    Upload upload=postsnapshot.getValue(Upload.class);
                    mUploads.add(upload);

                }

                mAdapter.notifyDataSetChanged();



            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();

            }
        });

0
投票

在适配器中创建刷新功能

public void refresh(List<Upload> uploads){
    this.uploads=uploads;
    notifyDataSetChanged();
 }

调用此目录,您可以使用这样的适配器从服务器或Firebase获取数据

mAdapter.refresh(mUploads);
© www.soinside.com 2019 - 2024. All rights reserved.