RecyclerView 在第二次调用 startActivity 后填充数据

RecyclerView populates data after startActivity is called a second time

我有一个从适配器加载数据的回收器视图。适配器从 Firebase 数据库填充的 Arraylist 中获取数据。当我启动应用程序时,数据没有显示。但是,如果我锁定屏幕然后再次解锁,回收站视图会很好地填充。我的 RecyclerView 或 Adapter 是否遗漏了什么?

这是我的 Activity 代码

public class MainActivity extends AppCompatActivity {

    DatabaseReference homepageRef;
    RecyclerViewAdapter mAdapter;

    private static final String TAG = "MainActivity";

    //vars
    private ArrayList<String> mAuthor = new ArrayList<>();
    private ArrayList<String> mImageUrls = new ArrayList<>();
    private ArrayList<String> mBookName = new ArrayList<>();
    List<Book> bookList;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate: started.");
        //initializing the productlist
        bookList = new ArrayList<>();

        initRecyclerView();
        initCollection();

    }

    private void initCollection(){
        Log.d(TAG, "initImageBitmaps: preparing bitmaps.");

        homepageRef=FirebaseDatabase.getInstance().getReference("collections/homepage");

        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String author = ds.child("author").getValue(String.class);
                    mAuthor.add(author);
                    String title = ds.child("title").getValue(String.class);
                    mBookName.add(title);
                    String thumbnail = ds.child("thumbnail").getValue(String.class);
                    mImageUrls.add(thumbnail);
                    Log.d("TAG", author + title);
                }

                long numOfBooks=dataSnapshot.getChildrenCount();
                Log.d(TAG, "Value is: " + numOfBooks);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(MainActivity.this, "Error fetching data", Toast.LENGTH_LONG).show();
            }
        };
        homepageRef.addValueEventListener(eventListener);
        mAdapter.notifyDataSetChanged();
        initRecyclerView();
    }
    private void initRecyclerView(){
        Log.d(TAG, "initRecyclerView: init recyclerview.");
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        mAdapter = new RecyclerViewAdapter(MainActivity.this, mAuthor, mImageUrls, mBookName);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    }

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

我在这里创建适配器

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

    private static final String TAG = "RecyclerViewAdapter";

    private ArrayList<String> mAuthor = new ArrayList<>();
    private ArrayList<String> mImages = new ArrayList<>();
    private ArrayList<String> mBookName = new ArrayList<>();
    private Context mContext;

    public RecyclerViewAdapter(Context context, ArrayList<String> author, ArrayList<String> images, ArrayList<String> bookName ) {
        mContext = context;
        mAuthor = author;
        mImages = images;
        mBookName = bookName;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_item_book, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        Log.d(TAG, "onBindViewHolder: called.");

        Glide.with(mContext)
                .asBitmap()
                .load(mImages.get(position))
                .into(holder.image);

        holder.imageName.setText(mAuthor.get(position));

        holder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: clicked on: " + mAuthor.get(position));

                Toast.makeText(mContext, mAuthor.get(position), Toast.LENGTH_SHORT).show();
/*
                Intent intent = new Intent(mContext, ReadingActivity.class);
                intent.putExtra("image_url", mImages.get(position));
                intent.putExtra("image_name", mImageNames.get(position));
                mContext.startActivity(intent);*/
                //create a Bundle object
                Bundle extras = new Bundle();
                //Adding key value pairs to this bundle
                //there are quite a lot data types you can store in a bundle
                extras.putString("BOOK_NAME",mBookName.get(position));
                extras.putInt("PAGE_NUMBER", 1);
                Intent intent = new Intent(mContext,BookDescriptionActivity.class);
                intent.putExtras(extras);
                mContext.startActivity(intent);
            }
        });
    }

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


    public class ViewHolder extends RecyclerView.ViewHolder{

        ImageView image;
        TextView imageName;
        RelativeLayout parentLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.thumbnail);
            imageName = itemView.findViewById(R.id.author);
            parentLayout = itemView.findViewById(R.id.parent_id);
        }
    }
}

当我启动应用程序时,数据没有显示。但是,如果我锁定屏幕然后再次解锁,回收站视图会很好地填充。我的 RecyclerView 或 Adapter 是否遗漏了什么?

onStart()onCreate() 以及 initCollection() 的末尾删除此行:

initRecyclerView();

并在for循环完成后在onDataChange()中调用:

    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String author = ds.child("author").getValue(String.class);
                mAuthor.add(author);
                String title = ds.child("title").getValue(String.class);
                mBookName.add(title);
                String thumbnail = ds.child("thumbnail").getValue(String.class);
                mImageUrls.add(thumbnail);
                Log.d("TAG", author + title);
            }

            long numOfBooks=dataSnapshot.getChildrenCount();

            //call it here only

            initRecyclerView();


        }
        .............
        .............

更新:

initCollection() 方法中删除这一行:

mAdapter.notifyDataSetChanged();

您首先使用空适配器初始化 recyclerView,然后调用 initCollection() 并将数据设置到适配器,所以试试这个:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate: started.");
        //initializing the productlist
        bookList = new ArrayList<>();

        initRecyclerView();
        initCollection();

    }

    private void initCollection(){
        Log.d(TAG, "initImageBitmaps: preparing bitmaps.");

        homepageRef=FirebaseDatabase.getInstance().getReference("collections/homepage");

        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String author = ds.child("author").getValue(String.class);
                    mAuthor.add(author);
                    String title = ds.child("title").getValue(String.class);
                    mBookName.add(title);
                    String thumbnail = ds.child("thumbnail").getValue(String.class);
                    mImageUrls.add(thumbnail);
                    Log.d("TAG", author + title);
                }

                long numOfBooks=dataSnapshot.getChildrenCount();
                Log.d(TAG, "Value is: " + numOfBooks);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(MainActivity.this, "Error fetching data", Toast.LENGTH_LONG).show();
            }
        };
        homepageRef.addValueEventListener(eventListener);
    mAdapter = new RecyclerViewAdapter(MainActivity.this, mAuthor, mImageUrls,  mBookName);
    mAdapter.notifyDataSetChanged();
    }
    private void initRecyclerView(){
        Log.d(TAG, "initRecyclerView: init recyclerview.");
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.setAdapter(mAdapter);
    }

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

    }
}