我得到了E / RecyclerView:未连接适配器;跳过布局我的错误是什么?

时间:2019-05-07 18:23:28

标签: android android-fragments android-recyclerview android-adapter

我遇到了错误E/RecyclerView: No adapter attached; skipping layout,但我不知道是什么原因,因为我刚刚研究了这个片段。

我已经对此进行了搜索,并按照步骤进行操作,但是仍然出现错误。

这是我的适配器:

public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder>  {

    public List<BlogPost> blog_list;
    public List<User> user_list;
    public Context context;
    private FirebaseFirestore firebaseFirestore;
    private FirebaseAuth firebaseAuth;

    public BlogRecyclerAdapter(List<BlogPost> blog_list,List<User> user_list){
        this.blog_list = blog_list;
        this.user_list = user_list;    
    }

    @NonNull
    @Override
    public BlogRecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_list_view, parent, false);
        context = parent.getContext();
        firebaseFirestore = FirebaseFirestore.getInstance();
        firebaseAuth = FirebaseAuth.getInstance();
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        holder.setIsRecyclable(false);

        final String blogPostId = blog_list.get(position).BlogPostId;
        final String currentUserId = firebaseAuth.getCurrentUser().getUid();

        String desc_data = blog_list.get(position).getDesc();
        holder.setDescText(desc_data);

        String image_url = blog_list.get(position).getImage_url();
        String thumbUri = blog_list.get(position).getThumbnail();
        holder.setBlogImage(image_url, thumbUri);

        String blog_user_id = blog_list.get(position).getUser_id();
        holder.blogDeletebtn.setEnabled(true);
        holder.blogDeletebtn.setVisibility(View.VISIBLE);

        firebaseFirestore.collection("Users").document(blog_user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if(task.isSuccessful()){
                    String userName = task.getResult().getString("name");
                    String userImage = task.getResult().getString("image");

                    holder.setUserData(userName, userImage);
                }
                else{
                    //error
                }
            }
        });

        try {
            long millisecond = blog_list.get(position).getTimestamp().getTime();
            String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
            holder.setTime(dateString);
        } catch (Exception e) {
            Toast.makeText(context, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        //new query para sa counter ng like
        firebaseFirestore.collection("Posts")
                .document(blogPostId)
                .collection("Likes").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                if(!queryDocumentSnapshots.isEmpty()){    
                    int count = queryDocumentSnapshots.size();
                    holder.updatesLikeCount(count);
                }
                else
                {
                    holder.updatesLikeCount(0);
                }
            }
        });

        //new query sa likes

        firebaseFirestore.collection("Posts")
                .document(blogPostId)
                .collection("Likes")
                .document(currentUserId).addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                if(documentSnapshot.exists()){
                    holder.blogLikebtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
                }
                else
                    {
                        holder.blogLikebtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
                }
            }
        });

        //dito gagana yung likes

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

                firebaseFirestore.collection("Posts")
                        .document(blogPostId)
                        .collection("Likes")
                        .document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if(!task.getResult().exists()){
                            Map<String, Object> likesMap = new HashMap<>();
                            likesMap.put("timestamp", FieldValue.serverTimestamp());

                            firebaseFirestore.collection("Posts")
                                    .document(blogPostId)
                                    .collection("Likes")
                                    .document(currentUserId)
                                    .set(likesMap);
                        }
                        else{
                            firebaseFirestore.collection("Posts")
                                    .document(blogPostId)
                                    .collection("Likes")
                                    .document(currentUserId)
                                    .delete();
                        }
                    }
                });
            }
        });

        holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent commentIntent = new Intent(context, CommentsActivity.class);
                commentIntent.putExtra("blog_post_id", blogPostId);
                context.startActivity(commentIntent);
            }
        });

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

                firebaseFirestore.collection("Posts").document(blogPostId).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        blog_list.remove(position);
                        user_list.remove(position);
                    }
                });

            }
        });


    }

    @Override
    public int getItemCount() {

        return blog_list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private View mView;

        private TextView descView,blogDate,blogUserName,blogLikeCount;
        private ImageView blogImageView,blogLikebtn,blogCommentBtn;
        private CircleImageView blogUserImage;
        private Button blogDeletebtn;


        public ViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

            blogLikebtn = mView.findViewById(R.id.blog_like_btn);
            blogCommentBtn = mView.findViewById(R.id.blog_comment_btn);
            blogDeletebtn = mView.findViewById(R.id.blog_delete_btn);
        }
        private void setDescText(String descText){

            descView = mView.findViewById(R.id.blog_desc);
            descView.setText(descText);
        }

        private void setBlogImage(String downloadUri, String thumbUri){

            blogImageView = mView.findViewById(R.id.blog_image);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.header1);
            Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).thumbnail
                    (Glide.with(context).load(thumbUri)).into(blogImageView);


        }

        private void setTime(String date){

            blogDate = mView.findViewById(R.id.blog_date);
            blogDate.setText(date);


        }

        private void setUserData(String name, String image){

            blogUserImage = mView.findViewById(R.id.blog_user_image);
            blogUserName = mView.findViewById(R.id.blog_username);

            blogUserName.setText(name);

            RequestOptions placeholderOptions = new RequestOptions();
            placeholderOptions.placeholder(R.drawable.messenger_button_send_round_shadow);

            Glide.with(context).applyDefaultRequestOptions(placeholderOptions).load(image).into(blogUserImage);

        }

        public void updatesLikeCount(int count){

            blogLikeCount = mView.findViewById(R.id.blog_like_count);
            blogLikeCount.setText(count + "Likes");

        }

    }
}

这是我的片段:

public class HomeFragment extends Fragment {

    private RecyclerView blog_list_view;
    private List<BlogPost> blog_list;
    private List<User> user_list;
    private FirebaseFirestore firebaseFirestore;
    private FirebaseAuth firebaseAuth;
    private BlogRecyclerAdapter blogRecyclerAdapter;
    private DocumentSnapshot lastVisible;
    private boolean isFirstPageFirstLoad = true;



    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);

        blog_list = new ArrayList<>();
        user_list = new ArrayList<>();
        blog_list_view = view.findViewById(R.id.blog_list_view);

        firebaseAuth = FirebaseAuth.getInstance();

        blogRecyclerAdapter = new BlogRecyclerAdapter(blog_list, user_list);
        blog_list_view.setLayoutManager(new LinearLayoutManager(container.getContext()));
        blog_list_view.setAdapter(blogRecyclerAdapter);
        blog_list_view.setHasFixedSize(true);

        if (firebaseAuth.getCurrentUser() != null) {

            firebaseFirestore = FirebaseFirestore.getInstance();

            blog_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    Boolean reachBottom = !recyclerView.canScrollVertically(1);

                    if (reachBottom) {

                        loadMorePost();

                    }
                }
            });

            Query firstQuery = firebaseFirestore.collection("Posts")
                    .orderBy("timestamp", Query.Direction.DESCENDING)
                    .limit(10);

            firstQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {

                    if (!queryDocumentSnapshots.isEmpty()) {

                        if (isFirstPageFirstLoad) {
                            lastVisible = queryDocumentSnapshots.getDocuments()
                                    .get(queryDocumentSnapshots.size() - 1);
                            blog_list.clear();
                            user_list.clear();
                        }

                        for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {

                            if (doc.getType() == DocumentChange.Type.ADDED) {

                                String blogPostId = doc.getDocument().getId();
                                final BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);

                                String blogUserId = doc.getDocument().getString("user_id");
                                firebaseFirestore.collection("Users").document(blogUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                    @Override
                                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                                        if (task.isSuccessful()) {

                                            User user = task.getResult().toObject(User.class);
                                            user_list.add(user);


                                            if (isFirstPageFirstLoad) {
                                                user_list.add(user);
                                                blog_list.add(blogPost);
                                            } else {
                                                user_list.add(0, user);
                                                blog_list.add(0, blogPost);
                                            }
                                            blogRecyclerAdapter.notifyDataSetChanged();
                                        }

                                    }
                                });

                            }
                            isFirstPageFirstLoad = false;
                        }

                    }

                }
            });

        }

        // Inflate the layout for this fragment
        return view;
    }
    private void loadMorePost(){

        Query nextQuery = firebaseFirestore.collection("Posts")
                .orderBy("timestamp", Query.Direction.DESCENDING)
                .startAfter(lastVisible)
                .limit(10);

        nextQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                if(!queryDocumentSnapshots.isEmpty()) {

                    lastVisible = queryDocumentSnapshots.getDocuments()
                            .get(queryDocumentSnapshots.size() - 1);

                    for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
                        if (doc.getType() == DocumentChange.Type.ADDED) {

                            String blogPostId = doc.getDocument().getId();
                            final BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);
                            String blogUserId = doc.getDocument().getString("user_id");
                            firebaseFirestore.collection("Users").document(blogUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                                    if(task.isSuccessful()){

                                        User user = task.getResult().toObject(User.class);
                                        user_list.add(user);

                                            user_list.add(user);
                                            blog_list.add(blogPost);

                                        blogRecyclerAdapter.notifyDataSetChanged();
                                    }

                                }
                            });
                        }
                    }
                }

            }
        });


    }

}

这是我的活动

public class Feed extends AppCompatActivity {

    private Toolbar mainToolbar;
    FirebaseAuth firebaseAuth;
    private FloatingActionButton addPostbtn;
    private FirebaseFirestore firebaseFirestore;
    private String current_user_id;
    private BottomNavigationView feedbottomNav;
    private HomeFragment homeFragment;
    private NotificationFragment notificationFragment;
    private AccountFragment accountFragment;


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

        FirebaseApp.initializeApp(this);


        firebaseAuth = FirebaseAuth.getInstance();
        firebaseFirestore = FirebaseFirestore.getInstance();

        mainToolbar = findViewById(R.id.main_toolbar);
        setSupportActionBar(mainToolbar);
        getSupportActionBar().setTitle("Feed");
        if(firebaseAuth != null) {

            feedbottomNav = findViewById(R.id.feedBottomNav);

            //FRAGMENTS KO
            homeFragment = new HomeFragment();
            notificationFragment = new NotificationFragment();
            accountFragment = new AccountFragment();

            initializeFragment();


            feedbottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {


                    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.feed_container);

                    switch (menuItem.getItemId()) {
                        case R.id.bottom_home_fragment:
                            replaceFragment(homeFragment, currentFragment);
                            return true;

                        case R.id.bottom_account_fragment:
                            replaceFragment(accountFragment, currentFragment);
                            return true;

                        case R.id.bottom_notification_fragment:
                            replaceFragment(notificationFragment, currentFragment);
                            return true;

                        default:

                            return false;
                    }

                }
            });


            addPostbtn = findViewById(R.id.add_post_btn);
            addPostbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Feed.this, NewPostActivity.class));
                    finish();
                }
            });
        }
    }

    private void initializeFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        fragmentTransaction.add(R.id.feed_container, homeFragment);
        fragmentTransaction.add(R.id.feed_container, notificationFragment);
        fragmentTransaction.add(R.id.feed_container, accountFragment);

        fragmentTransaction.hide(notificationFragment);
        fragmentTransaction.hide(accountFragment);

        fragmentTransaction.commit();
    }

    @Override
    protected void onStart() {
        super.onStart();


        FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
        if (currentUser == null) {
            startActivity(new Intent(Feed.this, MainActivity.class));
            finish();
        } else {

            current_user_id = firebaseAuth.getCurrentUser().getUid();

            firebaseFirestore.collection("Users").document(current_user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()) {

                        if (!task.getResult().exists()) {
                            startActivity(new Intent(Feed.this, AccountSettings.class));
                            finish();
                        }

                    } else {
                        String errorMessage = task.getException().getMessage();
                        Toast.makeText(Feed.this, "Error: " + errorMessage, Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){

            case R.id.action_logout:
                logOut();
                return true;

            case R.id.action_settings_btn:
                startActivity(new Intent(Feed.this, AccountSettings.class));
                return true;


            default:
                return false;
        }

    }
    private void logOut(){
        firebaseAuth.signOut();
        finish();
        startActivity(new Intent(Feed.this,MainActivity.class));
    }
    private void replaceFragment(Fragment fragment, Fragment currentFragment){
        //paglipat ng fragment
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if(fragment == homeFragment){

            fragmentTransaction.hide(accountFragment);
            fragmentTransaction.hide(notificationFragment);

        }

        if(fragment == accountFragment){

            fragmentTransaction.hide(homeFragment);
            fragmentTransaction.hide(notificationFragment);

        }

        if(fragment == notificationFragment){

            fragmentTransaction.hide(homeFragment);
            fragmentTransaction.hide(accountFragment);

        }
        fragmentTransaction.show(fragment);

        //fragmentTransaction.replace(R.id.main_container, fragment);
        fragmentTransaction.commit();
    }
}

这是我的片段布局

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/blog_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

这是我的活动布局

<FrameLayout
    android:id="@+id/feed_container"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/feedBottomNav"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/main_toolbar">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/blog_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

当我发布数据时,将检索数据并将其显示在recyclerview中,并且应该在feed上看到recycler视图,但是我一直收到该错误,请帮忙。

0 个答案:

没有答案