我正在开发一个消息应用程序。搜索了许多教程,了解如何将聊天/短信保存到 sqlite ,并在再次创建活动时检索它。我的代码是这样的 -
这是Chats.java
,
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chats, container, false);
random = new Random();
msg_text = (EditText) view.findViewById(R.id.messageText);
msgListView = (ListView) view.findViewById(R.id.msgListView);
ImageButton sendButton = (ImageButton) view
.findViewById(R.id.sendMessageButton);
sendButton.setOnClickListener(this);
msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
msgListView.setStackFromBottom(true);
chatlist = new ArrayList<ChatMessage>();
chatAdapter = new ChatAdapter(getActivity(), chatlist);
msgListView.setAdapter(chatAdapter);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
}
public void sendTextMessage(View v) {
String message = msg_edittext.getEditableText().toString();
if (!message.equalsIgnoreCase("")) {
final ChatMessage chatMessage = new ChatMessage(user1, user2,
message, "" + random.nextInt(1000), true);
chatMessage.setMsgID();
chatMessage.body = message;
chatMessage.Date = CommonMethods.getCurrentDate();
chatMessage.Time = CommonMethods.getCurrentTime();
msg_edittext.setText("");
chatAdapter.add(chatMessage);
chatAdapter.notifyDataSetChanged();
MessengerActivity activity = ((MessengerActivity) getActivity());
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sendMessageButton:
sendTextMessage(v);
}
}
在ChatAdapter.java
,
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage message = (ChatMessage) chatMessageList.get(position);
View vi = convertView;
if (message.isMine) {
layout.setBackgroundResource(R.drawable.bubble_a);
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
layout.setBackgroundResource(R.drawable.bubble_b);
parent_layout.setGravity(Gravity.LEFT);
}
}
如何将聊天保存到sqlite db并在打开时检索。
答案 0 :(得分:0)