android保存聊天到sqlite db并检索它们

时间:2016-07-21 07:38:07

标签: java android sqlite

我正在开发一个消息应用程序。搜索了许多教程,了解如何将聊天/短信保存到 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并在打开时检索。

1 个答案:

答案 0 :(得分:0)

以下是创建SQLite数据库的一些很好的起点。先阅读它们,然后自己动手:

SQLite OpenHelper

SQLite Tutorial

Saving Data in SQLite Database

网上有更多的例子。我建议先阅读第3个链接,然后再阅读其余部分。