我正在处理聊天应用程序。当我发送消息或检索消息时(使用套接字),我将其保存到嵌入式数据库中,然后显示给用户。当我第一次打开聊天活动时,一切正常。但是,如果我第二次或第三次重新打开聊天活动,则会分别插入消息两次或三次。例如:
第一次打开聊天活动,一切正常
聊天活动第三次打开,如果我发送消息,它将被克隆为3条消息
聊天活动已第六次打开,如果我发送消息,它将被克隆为6条消息
我尝试解决问题2天,但没有结果。也在互联网上搜索。没有结果
这是chatbox活动代码:
socket.on("message", new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
String room = data.getString("room");
String nickname = data.getString("senderNickname");
String message = data.getString("message");
String receiverNickname = data.getString("receiverNickname");
ContentValues contentValues = new ContentValues();
contentValues.put(DbItems.DbValues.MESSAGES_ROOM, room);
contentValues.put(DbItems.DbValues.MESSAGE_SENDER, nickname);
contentValues.put(DbItems.DbValues.MESSAGE_RECEIVER, receiverNickname);
contentValues.put(DbItems.DbValues.MESSAGE, message);
database.insert(DbItems.DbValues.TABLE_NAME, null, contentValues);
chatBoxAdapter.swapCursor(getAllItems());
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
private Cursor getAllItems(){
return database.query(
DbItems.DbValues.TABLE_NAME,
null, null,
null, null,
null, null
);
}
聊天框适配器的代码:
@Override
public void onBindViewHolder(final ChatBoxAdapter.MyViewHolder holder, final int position) {
User user = SharedPrefManager.getInstance(holder.itemView.getContext()).getUser();
String myEmail = user.getEmail();
if (!cursor.moveToPosition(position)){
return;
}
String room = cursor.getString(cursor.getColumnIndex(DbItems.DbValues.MESSAGES_ROOM));
String senderName = cursor.getString(cursor.getColumnIndex(DbItems.DbValues.MESSAGE_SENDER));
String receiverName = cursor.getString(cursor.getColumnIndex(DbItems.DbValues.MESSAGE_RECEIVER));
String message = cursor.getString(cursor.getColumnIndex(DbItems.DbValues.MESSAGE));
if (room.equals(message_room)){
if (senderName.equals(myEmail)){
holder.message_right.setText(message);
holder.message_right.setVisibility(View.VISIBLE);
}else {
if (receiverName.equals(myEmail)){
if (!email.equals(senderName)){
}else {
holder.message_left.setText(message);
holder.message_left.setVisibility(View.VISIBLE);
holder.message_user_image.setVisibility(View.VISIBLE);
String url = "http://192.168.1.111/ulgamda_iuhd/uploads/" + senderName + ".jpg";
Picasso.get()
.load(url)
.placeholder(R.drawable.default_profile)
.networkPolicy(NetworkPolicy.NO_CACHE)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.resize(604, 604)
.into(holder.message_user_image);
}
}
}
}
}
public void swapCursor(Cursor newCursor){
if (cursor != null){
cursor.close();
}
cursor = newCursor;
if (newCursor != null){
notifyDataSetChanged();
}
}