【问题标题】:RecyclerView doesn't load items on first start of activityRecyclerView 在第一次开始活动时不加载项目
【发布时间】:2017-11-08 11:50:27
【问题描述】:

每次我们打开暴露回收器适配器的活动时,它在第一次尝试时加载失败。退出活动并重新进入可以解决问题。例如,这是一个 gif。 https://gyazo.com/32dc664dd427ef1129704a09861a3708

我生成的物品:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/show_chat_single_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="70dp"

        app:cardBackgroundColor="#dcdada"
        app:cardCornerRadius="0dp"
        app:contentPadding="3dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/chat_persion_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/chat_persion_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Name"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@+id/chat_persion_image"
                app:layout_constraintTop_toTopOf="@+id/chat_persion_image" />

            <TextView
                android:id="@+id/chat_persion_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dp"
                android:layout_marginTop="8dp"
                android:text="Email"
                app:layout_constraintLeft_toLeftOf="@+id/chat_persion_name"
                app:layout_constraintTop_toBottomOf="@+id/chat_persion_name" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

我的对话布局:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/msgs_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:theme="@style/AppTheme2"

        >


        <android.support.v7.widget.RecyclerView

            android:id="@+id/active_chats"
            android:layout_width="match_parent"
            android:layout_height="510dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="57dp">


        </android.support.v7.widget.RecyclerView>


        <include
            android:id="@+id/include2"
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            />


    </RelativeLayout>

我的适配器:

public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
    private ArrayList<User> mUsers;
    private Context mContext;

    public ActiveChatConvo(ArrayList<User> photos,Context dick) {
        mUsers = photos;
        mContext = dick;
    }

    private Context getContext() {
        return mContext;
    }

    @Override
    public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get the data model based on position
        User user = mUsers.get(position);

        // Set item views based on your views and data model
        TextView name = holder.mItemName;
        name.setText(user.getName());
        TextView description = holder.mItemDescription;
        description.setText(user.getEmail());
        ImageView pic = holder.mItemImage;
        Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);

    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView mItemImage;
        private TextView mItemName;
        private TextView mItemDescription;
        private LinearLayout layout;
        final LinearLayout.LayoutParams params;


        public ViewHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
            mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
            mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
            layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
            //showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
            context.startActivity(showChatIntent);
        }
    }
}

我的主要课程

public class ConnectionsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView person_name,person_email;
    private RecyclerView recyclerView;
    private DatabaseReference mRef;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<User> users;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_connections);

        //Database
        mRef = FirebaseDatabase.getInstance().getReference("Users");
        mRef.keepSynced(true);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();

        users = new ArrayList<>();


        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        String name = postSnapshot.child("Name").getValue(String.class);
                        String email = postSnapshot.child("Email").getValue(String.class);
                        String pic = postSnapshot.child("image").getValue(String.class);

                        users.add(new User(name,email,pic));
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });



        //Recycler View
        recyclerView = (RecyclerView)findViewById(R.id.active_chats);
        ActiveChatConvo adapter = new ActiveChatConvo(users,this);
        recyclerView.setAdapter(adapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        //mLinearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);

        //VIEWS

        toolbar = (Toolbar) findViewById(R.id.tToolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
        ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);

        profileActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
                startActivity(profileActivity);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });

        homeActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
                startActivity(home);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });
    }







    }

因此,如果 recyclerView Activity 是我访问的第一个 Activity,那么它将不会创建项目。

【问题讨论】:

  • users.add(new User(name,email,pic));之后添加adapter.notifiyDatasetChanged()
  • 从 Firebase 加载数据需要一些时间,但您没有告诉适配器数据已加载
  • @RalphBergmann 谢谢你的回复,但我不确定你在users.add(new User(name,email,pic));.Adapter 之后添加的意思,当我收集用户时没有实例化,我还需要完整的用户列表构造适配器。
  • 您致电mRef.addListenerForSingleValueEvent,但这可能需要几秒钟。该应用程序不会等待它,而是继续运行。这意味着您创建一个带有空 users 列表的适配器。并且当加载数据并调用onDataChange 时,您不会告诉适配器内容已更改。最后在调用mRef.addListenerForSingleValueEvent 之前创建您的adatper,并在onDataChange 结束时调用adapter.notifyDatasetChanged
  • @RalphBergmann 好的,我现在开始工作了,非常感谢!

标签: android firebase firebase-realtime-database android-recyclerview firebase-authentication


【解决方案1】:

您可以使用布尔按钮来检查它是否是真正的适配器

【讨论】:

    【解决方案2】:

    在我的情况下,我设法解决了它,我找到了一种在打开活动之前启动 FirebaseDatabase 并添加鳕鱼的方法

    adapter.notifyDataSetChanged();

    然后我在用这个打开它之前启动了firebase

    FirebaseDatabase.getInstance().getReference().keepSynced(true);

    【讨论】:

      【解决方案3】:

      替换这个:

      recyclerView = (RecyclerView)findViewById(R.id.active_chats);
      ActiveChatConvo adapter = new ActiveChatConvo(users,this);
      recyclerView.setAdapter(adapter);
      mLinearLayoutManager = new LinearLayoutManager(this);
      //mLinearLayoutManager.setStackFromEnd(true);
      recyclerView.setLayoutManager(mLinearLayoutManager);
      

      用这个:

      recyclerView = (RecyclerView)findViewById(R.id.active_chats);
      ActiveChatConvo adapter = new ActiveChatConvo(users,this);
      mLinearLayoutManager = new LinearLayoutManager(this);
      //mLinearLayoutManager.setStackFromEnd(true);
      recyclerView.setLayoutManager(mLinearLayoutManager);
      recyclerView.setAdapter(adapter);
      

      设置LayoutManager后需要设置适配器。

      【讨论】:

        【解决方案4】:

        Firebase 是同步的,因此它不会阻塞应用程序的主线程,这意味着您的应用程序会继续执行,您需要在 firebase 完成工作后通知适配器,方法是在 for 循环后使用 adapter.notifiyDatasetChanged()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-09
          • 1970-01-01
          • 1970-01-01
          • 2021-12-30
          相关资源
          最近更新 更多