我试图为Android开发一个聊天应用程序,所以我使用了RecyclerView
。我的适配器有问题,我的聊天室在收到的JSON响应中显示空白。我在代码上错过了什么吗?
这是我的适配器类
public class PesanRecycleAdapter extends RecyclerView.Adapter<PesanRecycleAdapter.ViewHolder> {
private String username;
private Context context;
private int SELF = 786;
private ArrayList<Pesan> pesan;
public PesanRecycleAdapter(Context context, ArrayList<Pesan> pesan, String username){
this.username = username;
this.pesan = pesan;
this.context = context;
}
@Override
public int getItemViewType(int position) {
Pesan psn = pesan.get(position);
if (psn.getUsernameFrom() == username) {
return SELF;
}
return position;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == SELF) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_thread_me, parent, false);
} else {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_thread_other, parent, false);
}
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Pesan psn = pesan.get(position);
holder.textViewMessage.setText(psn.getPesan());
holder.textViewTime.setText(psn.getSentAt());
}
@Override
public int getItemCount() {
return pesan.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewMessage;
public TextView textViewTime;
public ViewHolder(View itemView) {
super(itemView);
textViewMessage = (TextView) itemView.findViewById(R.id.textViewMessage);
textViewTime = (TextView) itemView.findViewById(R.id.textViewTime);
}
}
}
欢迎任何帮助或建议
在这里我在活动中使用该适配器的地方
public void getpesan() {
try {
apiservice.get_pesan(username, "ahnafgg").enqueue(new Callback<ResponPesan>() {
@Override
public void onResponse(Call<ResponPesan> call, Response<ResponPesan> response) {
Log.d(TAG, "onResponse: response..."+response);
dummyData = response.body().getPesan();
createRecycleView();
}
@Override
public void onFailure(Call<ResponPesan> call, Throwable t) {
Log.d(TAG, "onFailure: response...");
Toast.makeText(RuangPesan.this,"Gagal ambil chat",Toast.LENGTH_SHORT).show();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void createRecycleView(){
adapter = new PesanRecycleAdapter(RuangPesan.this, pesan, username);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Log.d(TAG, "********************************");
scrollToBottom();
}
答案 0 :(得分:0)
我认为这里一切都很好,也许您忘记为recyclerView设置layoutManager或在设置数据后通知适配器
答案 1 :(得分:0)
在初始化回收者视图之前,您可能忘记了在模型中设置日期 使用活动类中的以下方法:
initData(); //Do this first
RecyclerView recyclerView = findViewById(R.id.recyclerview);
Context context = MainActivity.this;
PesanRecycleAdapter pesanRecycleAdapter = new PesanRecycleAdapter(context, list,"Fahad");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(pesanRecycleAdapter);