Recycler View没有显示任何项目。

huangapple go评论69阅读模式
英文:

Recycler View doesn't show any item

问题

这是代码部分的翻译:

public class UsersFragment extends Fragment {

    RecyclerView recyclerView;
    UsersAdapter adapter;
    List<Users> actualuserList;
    List<String> contactsList;
    DatabaseReference reference;

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

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

        recyclerView = view.findViewById(R.id.userRecyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        contactsList = new ArrayList<>();
        actualuserList = new ArrayList<>();

        return view;
    }


    private void getContactList() {
        Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        while (cursor.moveToNext()) {
            String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            if (contactsList.contains(phone)) {
                cursor.moveToNext();
            } else {
                contactsList.add(phone);
            }
        }
        getActualUser();
        Log.d("contact: ", String.valueOf(contactsList.size()));

    }

    private void getActualUser() {
        reference = FirebaseDatabase.getInstance().getReference().child("Users");
        for (String number : contactsList) {
            Query query = reference.orderByChild("phoneNumber").equalTo(number);
            query.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    actualuserList.clear();
                    if (snapshot.exists()) {
                        for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                            Users user = dataSnapshot.getValue(Users.class);
                            actualuserList.add(user);
                        }
                        Log.d("actual: ", String.valueOf(actualuserList.size()));
                        adapter = new UsersAdapter(getContext(), actualuserList);
                        recyclerView.setAdapter(adapter);
                    }
                }

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

                }
            });
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getContactList();
    }
}
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
    Context mContext;
    List<Users> mList;

    public UsersAdapter(Context mContext, List<Users> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final Users users = mList.get(position);
        holder.name.setText(users.getUsername());
        holder.number.setText(users.getPhoneNumber());
        String url = users.getProfilephotoURL();
        if (url.equals(""))
            holder.circleImageView.setImageResource(R.drawable.ic_user);
        else
            Glide.with(mContext).load(url).into(holder.circleImageView);
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, ChatActivity.class);
            intent.putExtra("name", users.getUsername());
            intent.putExtra("firendPhoneNumber", users.getPhoneNumber());
            mContext.startActivity(intent);
        });
    }

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

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView name, number;
        CircleImageView circleImageView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.contactName);
            number = itemView.findViewById(R.id.contactNumber);
            circleImageView = itemView.findViewById(R.id.profilePic);
        }
    }
}

日志部分不需要翻译,因为它只是描述了应用运行过程中的输出和警告信息。如有任何问题,请随时问我。

英文:

I am trying to display contacts in a Fragment but the recycler view doesn't show any item. Despite having items in the list recycler view is not showing any item. I am not sure what I have done wrong as the app does not crash when it is running.

Here is The Code

public class UsersFragment extends Fragment {
RecyclerView recyclerView;
UsersAdapter adapter;
List&lt;Users&gt; actualuserList;
List&lt;String&gt; contactsList;
DatabaseReference reference;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
contactsList = new ArrayList&lt;&gt;();
actualuserList = new ArrayList&lt;&gt;();
return view;
}
private void getContactList() {
Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + &quot; ASC&quot;);
while (cursor.moveToNext()) {
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactsList.contains(phone)) {
cursor.moveToNext();
} else {
contactsList.add(phone);
}
}
getActualUser();
Log.d(&quot;contact: &quot;, String.valueOf(contactsList.size()));
}
private void getActualUser() {
reference = FirebaseDatabase.getInstance().getReference().child(&quot;Users&quot;);
for (String number : contactsList) {
Query query = reference.orderByChild(&quot;phoneNumber&quot;).equalTo(number);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
actualuserList.clear();
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Users user = dataSnapshot.getValue(Users.class);
actualuserList.add(user);
}
Log.d(&quot;actual: &quot;, String.valueOf(actualuserList.size()));
adapter = new UsersAdapter(getContext(), actualuserList);
recyclerView.setAdapter(adapter);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getContactList();
}
}

In the Log statement, it is showing actual:1 that means there is an item.

Here is Adapter Code

public class UsersAdapter extends RecyclerView.Adapter&lt;UsersAdapter.ViewHolder&gt; {
Context mContext;
List&lt;Users&gt; mList;
public UsersAdapter(Context mContext, List&lt;Users&gt; mList) {
this.mContext = mContext;
this.mList = mList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.display_contacts, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
final Users users = mList.get(position);
holder.name.setText(users.getUsername());
holder.number.setText(users.getPhoneNumber());
String url = users.getProfilephotoURL();
if (url.equals(&quot;&quot;))
holder.circleImageView.setImageResource(R.drawable.ic_user);
else
Glide.with(mContext).load(url).into(holder.circleImageView);
holder.itemView.setOnClickListener(v -&gt; {
Intent intent = new Intent(mContext, ChatActivity.class);
intent.putExtra(&quot;name&quot;, users.getUsername());
intent.putExtra(&quot;firendPhoneNumber&quot;, users.getPhoneNumber());
mContext.startActivity(intent);
});
}
@Override
public int getItemCount() {
return mList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView name, number;
CircleImageView circleImageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.contactName);
number = itemView.findViewById(R.id.contactNumber);
circleImageView = itemView.findViewById(R.id.profilePic);
}
}
}

Logs

2020-07-27 14:52:51.651 25366-25366/com.mycompany.newchatapp D/contact:: 167
2020-07-27 14:52:51.670 25366-25366/com.mycompany.newchatapp E/RecyclerView: No adapter attached; skipping layout
2020-07-27 14:52:51.691 25366-25366/com.mycompany.newchatapp W/ClassMapper: No setter/field for status found on class com.mycompany.newchatapp.Model.Users
2020-07-27 14:52:51.691 25366-25366/com.mycompany.newchatapp D/actual:: 1
2020-07-27 14:52:51.723 25366-25366/com.mycompany.newchatapp W/ClassMapper: No setter/field for status found on class com.mycompany.newchatapp.Model.Users
2020-07-27 14:52:51.723 25366-25366/com.mycompany.newchatapp D/actual:: 1

Any Idea why this is happening?

答案1

得分: 2

Seems like you forgot to set adapter.

In onCreateView method put something like:

recyclerView.setAdapter(new UsersAdapter(this.getActivity(), getContactList()));

UPD:
Before that, make getContactList() return relevant dataset. Do not set adapter after initializing recycler view.

英文:

Seems like you forgot to set adapter.

In onCreateView method put something like:

recyclerView.setAdapter(new UsersAdapter(this.getActivity(), getContactList()));

UPD:
Before that, make getContactList() return relevant dataset. Do not set adapter after initializing recycler view.

答案2

得分: 1

奇怪的是,我最近也遇到了这个问题,我当时也在使用全局的List变量,而且列表不是空的,即使适配器也不是空的,但是 RecyclerView 直到第二次调用 adpater.notifyDataSetchanged() 才显示任何数据。

我在这个网站上找到了一个答案,上面说“创建一个新的List变量”,然后它就起作用了。

尝试将 actualUserList 声明为一个局部变量,就像在你的 onDataChange() 方法中一样,

public void onDataChange(@NonNull DataSnapshot snapshot) {
    List<Users> actualuserList = new ArrayList<>();
    if (snapshot.exists()) {
        for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
            Users user = dataSnapshot.getValue(Users.class);
            actualuserList.add(user);
        }
        Log.d("actual: ", String.valueOf(actualuserList.size()));
        adapter = new UsersAdapter(getContext(), actualuserList);
        recyclerView.setAdapter(adapter);
    }
}

如果这不解决你的问题,你还可以尝试在设置完适配器后调用 notifyDataSetChanged(),像这样:adapter.notifyDataSetChanged();

同时,在 onCreatedView() 中设置适配器,并在 onDataChange() 中调用 adapter.notifyDataSetChanged()

英文:

Strangely, I've faced this issue very recently and I was using as global List variable as well and the list wasn't empty, even the adpater was not empty but RecyclerView wasn't showing any data until second adpater.notifyDataSetchanged().

I'd found an answer here on this site that said "create a new list variable" and it worked.

Try making the actualUserList a local variable as in your onDataChange(),

public void onDataChange(@NonNull DataSnapshot snapshot) {
List&lt;Users&gt; actualuserList = new ArrayList&lt;&gt;();
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Users user = dataSnapshot.getValue(Users.class);
actualuserList.add(user);
}
Log.d(&quot;actual: &quot;, String.valueOf(actualuserList.size()));
adapter = new UsersAdapter(getContext(), actualuserList);
recyclerView.setAdapter(adapter);
}
}

If this doesn't solve your problem, you can also try calling notifyDataSetChanged() after setting up the adapter as adapter.notifyDataSetChanged();.

Also, set the adapter in onCreatedView() and call adapter.notifyDataSetChanged() in this onDataChange().

huangapple
  • 本文由 发表于 2020年7月27日 17:00:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63111972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定