欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android Studio和阿里云数据库实现一个远程聊天程序

程序员文章站 2022-03-16 20:03:41
没有阿里云数据库的可以买个最便宜的,我是新用户9.9元买了一个1.买到后点击左上角的工作台2.3.4.5.6.7.8.9.10.11.12.13.开始写android studio项目代码了,先来看看...

没有阿里云数据库的可以买个最便宜的,我是新用户9.9元买了一个

1.买到后点击左上角的工作台

Android Studio和阿里云数据库实现一个远程聊天程序

2.

Android Studio和阿里云数据库实现一个远程聊天程序

3.

Android Studio和阿里云数据库实现一个远程聊天程序

 4.

Android Studio和阿里云数据库实现一个远程聊天程序

 5.

Android Studio和阿里云数据库实现一个远程聊天程序

6.

Android Studio和阿里云数据库实现一个远程聊天程序

7.

Android Studio和阿里云数据库实现一个远程聊天程序

8.

Android Studio和阿里云数据库实现一个远程聊天程序

9.

Android Studio和阿里云数据库实现一个远程聊天程序

10.

Android Studio和阿里云数据库实现一个远程聊天程序

11.

Android Studio和阿里云数据库实现一个远程聊天程序

12.

Android Studio和阿里云数据库实现一个远程聊天程序

13.

Android Studio和阿里云数据库实现一个远程聊天程序

开始写android studio项目代码了,先来看看我的项目结构

Android Studio和阿里云数据库实现一个远程聊天程序

依赖包下载地址 central repository: mysql/mysql-connector-java (maven.org)

我第一次下了个版本比较新的发现会报错,由于我能力有限,所以就老实下载一个低版本的

添加依赖包应该都会了吧,不要忘了添加后还要添加到模块

Android Studio和阿里云数据库实现一个远程聊天程序

mainactivity代码如下

注意代码里涉及sql语句,这里要根据你之前新建的数据库和新建的表来写,我新建的表是test

import android.os.bundle;
import android.os.looper;
import android.view.view;
import android.widget.button;
import android.widget.edittext;
import android.widget.textview;
import android.widget.toast;
 
import androidx.appcompat.app.appcompatactivity;
 
import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
 
public class mainactivity extends appcompatactivity {
    private textview t1;  //用于显示获取的信息
    private button sendmsg;  //发送消息按钮
    private edittext et_msg;//用户输入信息框
    private string user="user"; //默认用户昵称
    private boolean t=false;//发送标志位
    //数据库连接类对象
    private static connection con = null;
    private static preparedstatement stmt = null;
    private button revise;
    private edittext et_revise;
 
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);
        //初始化
        t1 = findviewbyid(r.id.t1);
        et_msg = findviewbyid(r.id.msg);
        et_revise = findviewbyid(r.id.revisetext);
        sendmsg = findviewbyid(r.id.button);
        revise = findviewbyid(r.id.revise);
        revise.setonclicklistener(new view.onclicklistener() {
            @override
            public void onclick(view view) {
                user = et_revise.gettext().tostring();
                toast.maketext(mainactivity.this,"修改成功",toast.length_short).show();
            }
        });
        sendmsg.setonclicklistener(new view.onclicklistener() {
            @override
            public void onclick(view v) { t=true; }
        });
        //todo 启动发送线程,用按钮控制发送标志位t,来进行发送信息【注意:连接数据库必须在线程内,不然会报错】
        threads_sendmsg threads_sendmsg = new threads_sendmsg();
        threads_sendmsg.start();
        //todo 启动获取数据线程,读取数据库里的信息【注意:连接数据库必须在线程内,不然会报错】
        threads_readsql threads_readsql = new threads_readsql();
        threads_readsql.start();
 
    }
 
    class threads_sendmsg extends thread {
 
        @override
        public void run() {
            while (true){
                while (t){
                    try {
                        con = mysqlconnections.getconnection();
                    } catch (exception e) {
                        e.printstacktrace();
                    }
                    try {
                             //注意你数据库中是否有 test 这个表,我新建的表是 test
                            //还有我的属性,是否和我一样呢,不一样就按你自己的来吧
                        string msg =et_msg.gettext().tostring().trim(); //用户发送的信息
 
                        if (msg.isempty()){
 
                            looper.prepare();
                            toast.maketext(mainactivity.this, "消息为空", toast.length_short).show();
                            looper.loop();
                            t=false;
                            break;
                        }
                        if (msg.length()>199){
                            looper.prepare();
                            toast.maketext(mainactivity.this, "消息长度超过限制", toast.length_short).show();
                            looper.loop();
                            t=false;
                            break;
                        }
 
                        if (con!=null) {
                            runonuithread(new runnable() {
                                @override
                                public void run() {
                                    toast.maketext(mainactivity.this, "发送成功", toast.length_short).show();
                                }
                            });
                            string sql = "insert into test(name,msg,sign)  values(?,?,?)";
                            stmt = con.preparestatement(sql);
                            // 关闭事务自动提交 ,这一行必须加上
                            con.setautocommit(false);
                            stmt.setstring(1,user);
                            stmt.setstring(2,msg);
                            stmt.setint(3,1);
                            stmt.addbatch();
                            stmt.executebatch();
                            con.commit();
                        }
                    }catch (sqlexception e){
                        system.out.println(e);
                        runonuithread(new runnable() {
                            @override
                            public void run() {
                                toast.maketext(mainactivity.this,"请输入正确的语句",toast.length_short).show();
                            }
                        });
 
                    }
                    t=false;
                }
            }
        }
    }
    class threads_readsql extends thread {
 
        resultset rs;
 
 
        @override
        public void run() {
            while (true) {
                try {
                    con = mysqlconnections.getconnection();
                } catch (exception e) {
                    e.printstacktrace();
                }
                try {
                            //注意你数据库中是否有 test 这个表,我新建的表是 test
                            //还有我的属性,是否和我一样呢,不一样就按你自己的来吧
                    string sql = "select name,msg,sign from test";
                    if (con != null) {
                        stmt = con.preparestatement(sql);
                        // 关闭事务自动提交
                        con.setautocommit(false);
                        rs = stmt.executequery();//创建数据对象
                        //清空上次发送的信息
                        t1.settext(null);
                        while (rs.next() ) {
                            t1.append(rs.getstring(1) + "\n" + rs.getstring(2) + "\n\n");
                        }
                        con.commit();
                        rs.close();
                        stmt.close();
                    }
                    //2秒更新一次
                    sleep(2000);
                } catch (exception e) {
                    system.out.println(e);
                    runonuithread(new runnable() {
                        @override
                        public void run() {
                            //toast.maketext(mainactivity.this,"请输入正确的语句",toast.length_short).show();
                        }
                    });
                } 
            }
        } 
    } 
}

mainactivity布局文件activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".mainactivity"
    android:orientation="vertical">
 
    // an highlighted block
    <textview
        android:id="@+id/t1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="10"
        android:text="hello world!"
        android:layout_marginleft="8dp"
         />
 
    <linearlayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
 
        <linearlayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">
 
            <edittext
                android:id="@+id/revisetext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:hint="请输入你的昵称"
                android:inputtype="textpersonname" />
 
            <button
                android:id="@+id/revise"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="修改" />
 
        </linearlayout>
 
        <linearlayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">
 
            <edittext
                android:id="@+id/msg"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:ems="10"
                android:hint="请输入内容"
                android:inputtype="textpersonname" />
 
            <button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="发送" />
 
        </linearlayout>
 
    </linearlayout>
 
</linearlayout>

mysqlconnections代码如下

注意我写的注释,用户名,密码,外网地址,外网端口号,数据库名称,这些都要填写你自己的

import java.sql.connection;
import java.sql.drivermanager;
 
public class mysqlconnections {
    private string driver = "";
    private string dburl = "";
    private string user = "";
    private string password = "";
    private static mysqlconnections connection = null;
    private mysqlconnections() throws exception {
        driver = "com.mysql.jdbc.driver"; //这里根据你下载的依赖包版本会有不同的写法,下载低版本的就是这样写
        //rm-bp1lxt0mjpf6o.mysql.rds.aliyuncs.com:3306 这个是外网地址,3306是外网端口号,这些都需要填写你自己的
        //sqlconsole 这个是你登录你的数据库后新建的数据库(应该不绕口吧)
        dburl = "jdbc:mysql://rm-bp1lxt0m.mysql.rds.aliyuncs.com:3306/sqlconsole";
        user = "user";  //你新建库时的用户名
        password = "123456"; //你新建库时的密码,这里我就不写我的真密码了
        system.out.println("dburl:" + dburl);
    }
    public static connection getconnection() {
        connection conn = null;
        if (connection == null) {
            try {
                connection = new mysqlconnections();
            } catch (exception e) {
                e.printstacktrace();
                return null;
            }
        }
        try {
            class.forname(connection.driver);
            conn = drivermanager.getconnection(connection.dburl,
                    connection.user, connection.password);
        } catch (exception e) {
            e.printstacktrace();
        }
        return conn;
    }
}

androidmanifest.xml

注意这里要添加网络请求权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mysqlconnections">
 
    <uses-permission android:name="android.permission.internet" />
    <uses-permission android:name="android.permission.access_network_state" />
    <uses-permission android:name="android.permission.access_wifi_state" />
 
    <application
        android:usescleartexttraffic="true"
        android:allowbackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundicon="@mipmap/ic_launcher_round"
        android:supportsrtl="true"
        android:theme="@style/theme.myapplication1">
        <activity
            android:name=".mainactivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.main" />
 
                <category android:name="android.intent.category.launcher" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

最后看我运行结果

参考博客

android studio 连接阿里云数据库【制作基于数据库的多人远程聊天app】

到此这篇关于android studio和阿里云数据库实现一个远程聊天程序的文章就介绍到这了,更多相关android studio阿里云远程聊天内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!