0

我正在尝试将图像从 firebase 获取到 StaggeredGridLayout 中,这是一个片段,但出现了一些我无法解决的错误

错误:不兼容的类型:无法推断 ArrayList<> postItem = new ArrayList<>() 的类型参数;^ 原因:不存在类型变量 E 的实例,因此 ArrayList 符合 PostItem ,其中 E 是类型变量:E 扩展在类 ArrayList 中声明的 Object

从 android studio 得到一些建议后,我实现了一些方法,然后我得到了错误,但在我的片段中看不到应该显示的图像

这是JAVA文件

Home_Fragment.java // 发生错误的地方

public class Home_Fragment extends Fragment {
    private DatabaseReference databaseReference;
    private PostItem postItem;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
        postItem = new PostItem();

        RecyclerView postRecyclerView = view.findViewById(R.id.postRecyclerView);
        postRecyclerView.setLayoutManager(
                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        );
        //this 1st error
        postItem = new ArrayList<>();
        //this 2nd error
        PostAdapter postsAdapter = new PostAdapter(postItem);
        //end


        postRecyclerView.setAdapter(postsAdapter);

        //This are images that i tried manually and it worked fine 

//        List<PostItem> postItems = new ArrayList<>();
//        postItems.add(new PostItem(R.drawable.image1));
//        postItems.add(new PostItem(R.drawable.image2));
//        postItems.add(new PostItem(R.drawable.image3));
//        postItems.add(new PostItem(R.drawable.image4));
//        postItems.add(new PostItem(R.drawable.image5));
//        postItems.add(new PostItem(R.drawable.image7));
//        postItems.add(new PostItem(R.drawable.image9));
//        postItems.add(new PostItem(R.drawable.image10));
//        postItems.add(new PostItem(R.drawable.image11));
//        postItems.add(new PostItem(R.drawable.image13));
//        postItems.add(new PostItem(R.drawable.image14));
//        postItems.add(new PostItem(R.drawable.image15));
//        postItems.add(new PostItem(R.drawable.image16));
//        postItems.add(new PostItem(R.drawable.image17));
//        postItems.add(new PostItem(R.drawable.image18));
//        postItems.add(new PostItem(R.drawable.image20));
//        postItems.add(new PostItem(R.drawable.image21));
//        postItems.add(new PostItem(R.drawable.image22));
//        postItems.add(new PostItem(R.drawable.image23));
//        postItems.add(new PostItem(R.drawable.image24));
//        postItems.add(new PostItem(R.drawable.image25));
//        postItems.add(new PostItem(R.drawable.image26));
//        postItems.add(new PostItem(R.drawable.image27));
//        postItems.add(new PostItem(R.drawable.image29));
//        postItems.add(new PostItem(R.drawable.image30));
//        postItems.add(new PostItem(R.drawable.image31));
//        postItems.add(new PostItem(R.drawable.image32));
//        postItems.add(new PostItem(R.drawable.image33));
//        postItems.add(new PostItem(R.drawable.image34));
//        postItems.add(new PostItem(R.drawable.image35));
//        postItems.add(new PostItem(R.drawable.image36));
//        postItems.add(new PostItem(R.drawable.image37));
//        postItems.add(new PostItem(R.drawable.image38));
//        postItems.add(new PostItem(R.drawable.image39));
//        postItems.add(new PostItem(R.drawable.image42));
//        postItems.add(new PostItem(R.drawable.harry1));
//        postItems.add(new PostItem(R.drawable.harry2));
//        postItems.add(new PostItem(R.drawable.harry3));
//        postItems.add(new PostItem(R.drawable.harry4));
//        postItems.add(new PostItem(R.drawable.harry5));
//        postItems.add(new PostItem(R.drawable.harry6));
//        postItems.add(new PostItem(R.drawable.harry7));
//        postItems.add(new PostItem(R.drawable.harry8));
//        postItems.add(new PostItem(R.drawable.harry9));
//        postItems.add(new PostItem(R.drawable.harry10));
//        postItems.add(new PostItem(R.drawable.harry11));
//        postItems.add(new PostItem(R.drawable.harry12));
//        postItems.add(new PostItem(R.drawable.harry13));
//        postItems.add(new PostItem(R.drawable.harry14));
//        postItems.add(new PostItem(R.drawable.harry15));

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    PostItem postItem = dataSnapshot.getValue(PostItem.class);
                    postItem.getImage();
                }

                //notify the adapter
                postsAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
        return view;
    }

}

PostAdapter.java

 public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
        public final List<PostItem> postItems;
    
        public PostAdapter(List<PostItem> postItems) {
            this.postItems = postItems;
        }
    
    
        @NonNull
        @Override
        public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new PostViewHolder(
                    LayoutInflater.from(parent.getContext()).inflate(
                            R.layout.post_item_container,
                            parent,
                            false
                    )
            );
        }
    
        @Override
        public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
            holder.setPostImage(postItems.get(position));
    
        }
    
        @Override
        public int getItemCount() {
            return postItems.size();
        }
    
        static class PostViewHolder extends RecyclerView.ViewHolder {
            RoundedImageView postImageView;
    
            PostViewHolder(@NonNull View itemView) {
                super(itemView);
                postImageView = itemView.findViewById(R.id.imagePost);
            }
    
            void setPostImage(PostItem postItem) {
                postImageView.setImageResource(postItem.getImage());
    
            }
        }
    }


PostItems.java

    public class PostItem {
        private int image = 0;
    
        public PostItem(int image) {
            this.image = image;
        }
    
        public PostItem() {
            return;
    
        }
    
        public int getImage() {
            return image;
        }
    
        public int getPit() {
            return getPit();
        }
    }

Upload_Fragment.java //这个Fragment我用来上传图片到firebase

 public class Upload_Fragment extends Fragment {
        private static final int PICK_IMAGE_REQUEST = 10;
        private Button choseImageButton;
        private Button uploadImageButton;
        private ImageView uploadImageView;
        private Uri imageUri;
        private FirebaseStorage storage;
        private StorageReference storageReference;
        private DatabaseReference databaseReference;
        private StorageTask mUploadTask;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_upload, container, false);
            Button chooseImageButton = view.findViewById(R.id.upload_image_button);
            Button uploadImageButton = view.findViewById(R.id.done_button);
            uploadImageView = view.findViewById(R.id.upload_image_view);
            storage = FirebaseStorage.getInstance();
            storageReference = storage.getReference("uploads");
            databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
            chooseImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openFileChooser();
    
                }
            });
            uploadImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mUploadTask != null && mUploadTask.isInProgress()) {
                        Toast.makeText(getActivity(), "Upload in Progress", Toast.LENGTH_SHORT).show();
    
                    } else {
                        uploadToFirebase();
                    }
    
    
                }
            });
    
            return view;
        }
    
        private void openFileChooser() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
        }
    
        @Override
        public 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) {
                imageUri = data.getData();
                Glide.with(this).load(imageUri).into(uploadImageView);
    
            }
        }
    
        private String getFileExtension(Uri uri) {
    
            ContentResolver contentResolver = getActivity().getContentResolver();
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            return mime.getExtensionFromMimeType(contentResolver.getType(uri));
        }
    
        private void uploadToFirebase() {
            if (imageUri != null) {
                final ProgressDialog progressDialog = new ProgressDialog(getActivity());
                progressDialog.setTitle("Uploading...");
                progressDialog.show();
    
                StorageReference ref = storageReference.child(System.currentTimeMillis()
                        + "." + getFileExtension(imageUri));
                mUploadTask = ref.putFile(imageUri)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                progressDialog.dismiss();
                                Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
                                Upload_Image upload_image = new Upload_Image(ref.getDownloadUrl().toString());
                                String uploadId = databaseReference.push().getKey();
                                databaseReference.child(uploadId).setValue(upload_image);
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                progressDialog.dismiss();
                                Toast.makeText(getActivity(), "Error Ocurred" + 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());
                                progressDialog.setMessage("Uploaded " + (int) progress + "%");
                            }
                        });
            }
        }
    
    }

Upload_Image.java

公共类 Upload_Image { 私有字符串 mimageUrl;

public Upload_Image() {

}

public Upload_Image(String imageUrl) {
    mimageUrl = imageUrl;
}

public String getimageUrl() {
    return mimageUrl;
}

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

}

4

2 回答 2

0

在您的家庭片段中。

private ArrayList<PostItem> itemsList;

itemsList= new ArrayList<>();
PostAdapter postsAdapter = new PostAdapter(itemsList);

在你的事件监听器中,

    for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
            PostItem postItem = dataSnapshot.getValue(PostItem.class);
            itemsList.add(postItem.getImage());
          }

您没有将任何图像添加到列表中,因此您没有得到任何东西。

于 2022-02-27T07:00:24.743 回答
0

postItem变量的引用类型是PostItem但您正在分配ArrayList<>()对象。您应该将引用类型更改为列表类型。请参阅以下代码以供参考。

Home_Fragment.java

private List<PostItem> postItem;

postItem = new ArrayList<>();
PostAdapter postsAdapter = new PostAdapter(postItem);
于 2021-04-03T16:34:53.403 回答