Android Studio和阿裡雲數據庫實現一個遠程聊天程序

沒有阿裡雲數據庫的可以買個最便宜的,我是新用戶9.9元買瞭一個

1.買到後點擊左上角的工作臺

2.

3.

 4.

 5.

6.

7.

8.

9.

10.

11.

12.

13.

開始寫Android Studio項目代碼瞭,先來看看我的項目結構

依賴包下載地址 Central Repository: mysql/mysql-connector-java (maven.org)

我第一次下瞭個版本比較新的發現會報錯,由於我能力有限,所以就老實下載一個低版本的

添加依賴包應該都會瞭吧,不要忘瞭添加後還要添加到模塊

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阿裡雲遠程聊天內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: