基于Bmob的在线群聊之群聊天的实现

上一篇已经实现了注册,登录的功能,下面就到实现了在线群聊的功能。
先说一下思路吧,自己可能弄复杂了,所以先说一下思路。

1、实现群聊天的思路

  • 创建一个表用来存储聊天的数据
  • 发送数据调用Bmob的保存数据的方法
  • 给数据表设置表监听,也是Bmob带的方法,只要数据更新那么就将更新的数据保存到本地的数据库
  • 聊天的数据显示是通过查询数据库的方法来显示出来

2、需要在Bmob添加一个用来存储聊天数据的表

public class XdMessage extends BmobObject {//需要继承BmobObject
    private String name;//存储消息的用户名
    private String msg;//存储消息
    private BmobFile icon;//存储发送的图片
    private String path;//存储发送图片的路径
    //添加get、set方法
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public XdMessage(String name, String msg, String path){
        this.name = name;
        this.msg = msg;
        this.path = path;
    }
    public BmobFile getIcon() {
        return icon;
    }
    public void setIcon(BmobFile icon) {
        this.icon = icon;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

3、发送消息的实现

其实这里说的发送消息就是将数据保存到表格里。

public void send(View v){//点击按钮后执行的方法
        final User user = BmobUser.getCurrentUser(User.class);//获取当前用户的信息
        final String username = user.getUsername();//将当前的用户名赋值给username
        final String text = edit.getText().toString();
        if(text.equals("")){
            return;
        }else {
            sendMsg(username,text);//发送消息
        }
    }
private void sendMsg(final String username, final String text) {
        final XdMessage chat = new XdMessage(username,text,"");
        chat.save(new SaveListener() {//调用Bmob的保存数据的方法
            @Override
            public void done(String s, BmobException e) {
                if(e == null){//保存成功
                    edit.setText("");
                }else {//保存失败
                    Toast.makeText(XdChat.this,"发送失败",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

4、给表设置监听

 BmobRealTimeData data = new BmobRealTimeData();
 private void initdata() {
        data.start(new ValueEventListener() {
            @Override
            public void onConnectCompleted(Exception e) {
                if(data.isConnected()){
                    //设置监听的表名
                    data.subTableUpdate("XdMessage");
                }
            }
            @Override
            public void onDataChange(JSONObject jsonObject) {
                myAdapter1.notifyDataSetChanged();
         if(BmobRealTimeData.ACTION_UPDATETABLE.equals(jsonObject.optString("action"))){
                  JSONObject data = jsonObject.optJSONObject("data");
                  //data中有更新的数据的信息,并将数据存入数据库中  insertApi(data.optString("name"),data.optString("msg"),data.optString("path"),data.optString("createdAt"));
                    chaxun();//查询数据库
                    lvList.setSelection(lvList.FOCUS_DOWN);//将listview定位在最后一条数据
                }
            }
        });
    }

5、数据库的操作

插入数据的方法

public void insertApi(String name,String msg,String path ,String time){
        //把要插入的数据全部封装至ContentValues对象
        MyOpenHelper oh = new MyOpenHelper(this);
        SQLiteDatabase db = oh.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);//存入的数据
        values.put("msg", msg);
        values.put("path", path);
        values.put("time", time);
        db.insert("Xd_message", null, values);//数据库的表名
        db.close();
    }

查询所有的数据

 public void chaxun(){
        //把数据库的数据查询出来
        //List Localmsg = new ArrayList();
        Localmsg.clear();
        Cursor cursor = db.query("xd_message", null, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            String _id = cursor.getString(0);
            String name= cursor.getString(1);
            String msg = cursor.getString(2);
            String path = cursor.getString(3);
            String time = cursor.getString(4);
            LocalMessageXd q = new LocalMessageXd( _id, name, msg, path, time);
            Localmsg.add(q);
        }
        myAdapter1.notifyDataSetChanged();
        lvList.setSelection(lvList.FOCUS_DOWN);
        System.out.println("查询完毕" + Localmsg.size());
    }

LocalMessageXd

public class LocalMessageXd {
    private String _id;
    private String name;
    private String msg;
    private String path;
    private String time;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return
                " name='" + name +
                ", msg='" + msg +
                ", path='" + path +
                ", time='" + time;
    }

    public LocalMessageXd(String _id, String name, String msg, String path, String time) {
        super();
        this._id = _id;
        this.name = name;
        this.msg = msg;
        this.path = path;
        this.time = time;
    }
}

MyOpenHelper类用来创建数据库和表

public class MyOpenHelper extends SQLiteOpenHelper{
    public MyOpenHelper(Context context) {
        super(context, "test.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //聊天的数据库
        db.execSQL("create table xd_message(_id integer primary key autoincrement, name char(10),msg char(20), path char(20),time char(20))");
        System.out.println("数据库被创建了");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("数据库升级了");
    }
}

MyAdapter1类

private class MyAdapter1 extends BaseAdapter{

    @Override
    public int getCount() {
        return Localmsg.size();
    }

    @Override
    public Object getItem(int position) {
        return Localmsg.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        System.out.println("getView");
        MyAdapter1.ViewHolder holder = null;
        if(convertView == null){
            holder = new MyAdapter1.ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(XdChat.this);
            convertView = inflater.inflate(R.layout.item_chat, null);
            holder.my_head = (ImageView) convertView.findViewById(R.id.my_head);
            holder.my_name = (TextView) convertView.findViewById(R.id.my_name);
            holder.tv_my = (TextView) convertView.findViewById(R.id.tv_my);
            holder.iv_my = (ImageView) convertView.findViewById(R.id.iv_my);
            holder.my_time = (TextView) convertView.findViewById(R.id.my_time);
            holder.other_time = (TextView) convertView.findViewById(R.id.other_time);
            holder.other_head = (ImageView) convertView.findViewById(R.id.other_head);
            holder.other_name = (TextView) convertView.findViewById(R.id.other_name);
            holder.tv_other = (TextView) convertView.findViewById(R.id.tv_other);
            holder.iv_other = (ImageView) convertView.findViewById(R.id.iv_other);
            convertView.setTag(holder);
        }else{
            holder = (MyAdapter1.ViewHolder) convertView.getTag();
        }
        LocalMessageXd chat = Localmsg.get(position);
        User user = BmobUser.getCurrentUser(User.class);
        if(chat.getName().equals(user.getUsername())){
            holder.other_head.setVisibility(View.GONE);
            holder.other_name.setVisibility(View.GONE);
            holder.tv_other.setVisibility(View.GONE);

            holder.iv_other.setVisibility(View.GONE);
            holder.my_head.setVisibility(View.VISIBLE);
           // downloadFile1(chat.getName(),holder.my_head);
            String path = chaxunHeadPath(chat.getName());
            downloadFile(chat.getName(),holder.my_head,path);
            holder.my_name.setVisibility(View.VISIBLE);
            holder.my_name.setText(chat.getName());

            holder.other_time.setVisibility(View.GONE);
            holder.my_time.setVisibility(View.VISIBLE);
            String time = chat.getTime().substring(5);
            holder.my_time.setText(time + "  ");
            String msg = chat.getMsg();
            if(msg.equals("")){
               holder.tv_my.setVisibility(View.GONE);
                holder.iv_my.setVisibility(View.VISIBLE);
              /*  Bitmap bmp= BitmapFactory.decodeFile(chat.getPath());
                holder.iv_my.setImageBitmap(bmp);*/
                downloadFile(chat.getName(),holder.iv_my,chat.getPath());
            }else {
                holder.iv_my.setVisibility(View.GONE);
                holder.tv_my.setVisibility(View.VISIBLE);
               // holder.tv_my.setText(chat.getTime() + "\n"+ chat.getMsg());
                holder.tv_my.setText(chat.getMsg());
            }

        }
        else{
            holder.my_head.setVisibility(View.GONE);
            holder.my_name.setVisibility(View.GONE);
            holder.tv_my.setVisibility(View.GONE);
            holder.iv_my.setVisibility(View.GONE);

            holder.other_name.setText(chat.getName());
            holder.other_head.setVisibility(View.VISIBLE);
            holder.my_time.setVisibility(View.GONE);
            holder.other_time.setVisibility(View.VISIBLE);
            String time = chat.getTime().substring(5);
            holder.other_time.setText("  " + time);
          //  downloadFile1(chat.getName(),holder.other_head);
            String path = chaxunHeadPath(chat.getName());
            if(path.equals("")){
                holder.other_head.setImageResource(R.drawable.default_icon_user);
            }else {
                downloadFile(chat.getName(),holder.other_head,path);
            }
            holder.other_name.setVisibility(View.VISIBLE);
           if(chat.getMsg().equals("")){
                holder.tv_other.setVisibility(View.GONE);
                holder.iv_other.setVisibility(View.VISIBLE);
              /*  Bitmap bmp= BitmapFactory.decodeFile(chat.getPath());
                holder.iv_other.setImageBitmap(bmp);*/
                downloadFile(chat.getName(),holder.iv_other,chat.getPath());
            }else {
                holder.iv_other.setVisibility(View.GONE);
                holder.tv_other.setVisibility(View.VISIBLE);
               // holder.tv_other.setText(chat.getTime() + "\n" + chat.getMsg());
               holder.tv_other.setText(chat.getMsg());
            }

        }
        return convertView;
    }
    class ViewHolder{
        ImageView my_head;
        TextView my_name;
        TextView tv_my;
        TextView my_time;
        ImageView iv_my;
        ImageView other_head;
        TextView other_name;
        TextView tv_other;
        ImageView iv_other;
        TextView other_time;
    }
}

你可能感兴趣的:(Bmob,数据库,聊天,bmob,存储,数据)