如何将数据从适配器发送到活动并在recyclerview中显示?

时间:2019-05-26 19:29:45

标签: android firebase android-recyclerview

我尝试将数据从适配器传递到活动,并将其显示在recyclerview中。运行应用程序时出现NullPointerException。我在做什么错了?

这是我要显示数据的活动

public class ListOfChatsActivity extends AppCompatActivity {
Toolbar lToolbar;
RecyclerView lRV;
BottomNavigationView lBnv;
ListOfChatsAdapter adapter;
LinearLayoutManager layoutManager;
ArrayList<String> chatList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_of_chats);

    lToolbar = findViewById(R.id.lToolbar);
    lRV = findViewById(R.id.lRV);
    lBnv = findViewById(R.id.lBnv);
    Intent intent = this.getIntent();
    if(intent!=null){
    String string = intent.getStringExtra("username");
    chatList.add(string);}

    adapter = new ListOfChatsAdapter(chatList, getApplicationContext());
    layoutManager = new LinearLayoutManager(getApplicationContext());
    lRV.setAdapter(adapter);
    lRV.setLayoutManager(layoutManager);
}

这是我要从中发送数据的适配器:

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

ArrayList<User> friendsSearchedList = new ArrayList<>();
Context mContext;

public SearchAdapter(ArrayList<User> friendsSearchedList, Context mContext){
    this.friendsSearchedList = friendsSearchedList;
    this.mContext = mContext;
}

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

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
    final User username = friendsSearchedList.get(position);
    holder.text.setText(username.getUsername());
   holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String iUsername = holder.text.getText().toString();
            Intent intent = new Intent();
            intent.putExtra("username", iUsername);
        }
    });

}

@Override
public int getItemCount() {
    return friendsSearchedList == null ? 0:friendsSearchedList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView text;
    Button button;
    RelativeLayout relativeLayout;
    public ViewHolder(View itemView){
        super(itemView);

        text = itemView.findViewById(R.id.sText);
        button = itemView.findViewById(R.id.addFriend);
        relativeLayout = itemView.findViewById(R.id.relativeLayout);
    }
}

}

我没有从此适配器打开活动。我只想发送其他内容。我尝试了更多选择,但我做错了。

1 个答案:

答案 0 :(得分:0)

  

更改1

adapter = new ListOfChatsAdapter(chatList, getApplicationContext());

为什么在这里使用ListOfChatsAdapter?您已经包括SearchAdapter作为要在RecyclerView中使用的适配器。

  

更改2

onCreateViewHolder()返回的ViewHolder对象应为SearchAdapter.ViewHolder类型,而不仅仅是ViewHolderonBindViewHolder()的第一个论点也是如此。

尝试这些并检查