当前位置:   article > 正文

使用Android Studio和阿里云数据库实现一个远程聊天程序_android studio在线聊天

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

  1. import android.os.Bundle;
  2. import android.os.Looper;
  3. import android.view.View;
  4. import android.widget.Button;
  5. import android.widget.EditText;
  6. import android.widget.TextView;
  7. import android.widget.Toast;
  8. import androidx.appcompat.app.AppCompatActivity;
  9. import java.sql.Connection;
  10. import java.sql.PreparedStatement;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. public class MainActivity extends AppCompatActivity {
  14. private TextView t1; //用于显示获取的信息
  15. private Button sendmsg; //发送消息按钮
  16. private EditText et_msg;//用户输入信息框
  17. private String user="user"; //默认用户昵称
  18. private boolean T=false;//发送标志位
  19. //数据库连接类对象
  20. private static Connection con = null;
  21. private static PreparedStatement stmt = null;
  22. private Button revise;
  23. private EditText et_revise;
  24. @Override
  25. protected void onCreate(Bundle savedInstanceState) {
  26. super.onCreate(savedInstanceState);
  27. setContentView(R.layout.activity_main);
  28. //初始化
  29. t1 = findViewById(R.id.t1);
  30. et_msg = findViewById(R.id.msg);
  31. et_revise = findViewById(R.id.reviseText);
  32. sendmsg = findViewById(R.id.button);
  33. revise = findViewById(R.id.revise);
  34. revise.setOnClickListener(new View.OnClickListener() {
  35. @Override
  36. public void onClick(View view) {
  37. user = et_revise.getText().toString();
  38. Toast.makeText(MainActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
  39. }
  40. });
  41. sendmsg.setOnClickListener(new View.OnClickListener() {
  42. @Override
  43. public void onClick(View v) { T=true; }
  44. });
  45. //TODO 启动发送线程,用按钮控制发送标志位T,来进行发送信息【注意:连接数据库必须在线程内,不然会报错】
  46. Threads_sendmsg threads_sendmsg = new Threads_sendmsg();
  47. threads_sendmsg.start();
  48. //TODO 启动获取数据线程,读取数据库里的信息【注意:连接数据库必须在线程内,不然会报错】
  49. Threads_readSQL threads_readSQL = new Threads_readSQL();
  50. threads_readSQL.start();
  51. }
  52. class Threads_sendmsg extends Thread {
  53. @Override
  54. public void run() {
  55. while (true){
  56. while (T){
  57. try {
  58. con = MySQLConnections.getConnection();
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. }
  62. try {
  63. //注意你数据库中是否有 test 这个表,我新建的表是 test
  64. //还有我的属性,是否和我一样呢,不一样就按你自己的来吧
  65. String msg =et_msg.getText().toString().trim(); //用户发送的信息
  66. if (msg.isEmpty()){
  67. Looper.prepare();
  68. Toast.makeText(MainActivity.this, "消息为空", Toast.LENGTH_SHORT).show();
  69. Looper.loop();
  70. T=false;
  71. break;
  72. }
  73. if (msg.length()>199){
  74. Looper.prepare();
  75. Toast.makeText(MainActivity.this, "消息长度超过限制", Toast.LENGTH_SHORT).show();
  76. Looper.loop();
  77. T=false;
  78. break;
  79. }
  80. if (con!=null) {
  81. runOnUiThread(new Runnable() {
  82. @Override
  83. public void run() {
  84. Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
  85. }
  86. });
  87. String sql = "insert into test(name,msg,sign) values(?,?,?)";
  88. stmt = con.prepareStatement(sql);
  89. // 关闭事务自动提交 ,这一行必须加上
  90. con.setAutoCommit(false);
  91. stmt.setString(1,user);
  92. stmt.setString(2,msg);
  93. stmt.setInt(3,1);
  94. stmt.addBatch();
  95. stmt.executeBatch();
  96. con.commit();
  97. }
  98. }catch (SQLException e){
  99. System.out.println(e);
  100. runOnUiThread(new Runnable() {
  101. @Override
  102. public void run() {
  103. Toast.makeText(MainActivity.this,"请输入正确的语句",Toast.LENGTH_SHORT).show();
  104. }
  105. });
  106. }
  107. T=false;
  108. }
  109. }
  110. }
  111. }
  112. class Threads_readSQL extends Thread {
  113. ResultSet rs;
  114. @Override
  115. public void run() {
  116. while (true) {
  117. try {
  118. con = MySQLConnections.getConnection();
  119. } catch (Exception e) {
  120. e.printStackTrace();
  121. }
  122. try {
  123. //注意你数据库中是否有 test 这个表,我新建的表是 test
  124. //还有我的属性,是否和我一样呢,不一样就按你自己的来吧
  125. String sql = "select name,msg,sign from test";
  126. if (con != null) {
  127. stmt = con.prepareStatement(sql);
  128. // 关闭事务自动提交
  129. con.setAutoCommit(false);
  130. rs = stmt.executeQuery();//创建数据对象
  131. //清空上次发送的信息
  132. t1.setText(null);
  133. while (rs.next() ) {
  134. t1.append(rs.getString(1) + "\n" + rs.getString(2) + "\n\n");
  135. }
  136. con.commit();
  137. rs.close();
  138. stmt.close();
  139. }
  140. //2秒更新一次
  141. sleep(2000);
  142. } catch (Exception e) {
  143. System.out.println(e);
  144. runOnUiThread(new Runnable() {
  145. @Override
  146. public void run() {
  147. //Toast.makeText(MainActivity.this,"请输入正确的语句",Toast.LENGTH_SHORT).show();
  148. }
  149. });
  150. }
  151. }
  152. }
  153. }
  154. }

MainActivity布局文件activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context=".MainActivity"
  8. android:orientation="vertical">
  9. // An highlighted block
  10. <TextView
  11. android:id="@+id/t1"
  12. android:layout_width="match_parent"
  13. android:layout_height="0dp"
  14. android:layout_weight="10"
  15. android:text="Hello World!"
  16. android:layout_marginLeft="8dp"
  17. />
  18. <LinearLayout
  19. android:layout_width="match_parent"
  20. android:layout_height="0dp"
  21. android:layout_weight="1"
  22. android:orientation="vertical">
  23. <LinearLayout
  24. android:layout_width="match_parent"
  25. android:layout_height="match_parent"
  26. android:layout_weight="1"
  27. android:orientation="horizontal">
  28. <EditText
  29. android:id="@+id/reviseText"
  30. android:layout_width="wrap_content"
  31. android:layout_height="wrap_content"
  32. android:layout_weight="1"
  33. android:ems="10"
  34. android:hint="请输入你的昵称"
  35. android:inputType="textPersonName" />
  36. <Button
  37. android:id="@+id/revise"
  38. android:layout_width="wrap_content"
  39. android:layout_height="wrap_content"
  40. android:layout_weight="1"
  41. android:text="修改" />
  42. </LinearLayout>
  43. <LinearLayout
  44. android:layout_width="match_parent"
  45. android:layout_height="match_parent"
  46. android:layout_weight="1"
  47. android:orientation="horizontal">
  48. <EditText
  49. android:id="@+id/msg"
  50. android:layout_width="wrap_content"
  51. android:layout_height="match_parent"
  52. android:layout_weight="1"
  53. android:ems="10"
  54. android:hint="请输入内容"
  55. android:inputType="textPersonName" />
  56. <Button
  57. android:id="@+id/button"
  58. android:layout_width="wrap_content"
  59. android:layout_height="match_parent"
  60. android:layout_weight="1"
  61. android:text="发送" />
  62. </LinearLayout>
  63. </LinearLayout>
  64. </LinearLayout>

MYSQLConnections代码如下

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

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. public class MySQLConnections {
  4. private String driver = "";
  5. private String dbURL = "";
  6. private String user = "";
  7. private String password = "";
  8. private static MySQLConnections connection = null;
  9. private MySQLConnections() throws Exception {
  10. driver = "com.mysql.jdbc.Driver"; //这里根据你下载的依赖包版本会有不同的写法,下载低版本的就是这样写
  11. //rm-bp1lxt0mjpf6o.mysql.rds.aliyuncs.com:3306 这个是外网地址,3306是外网端口号,这些都需要填写你自己的
  12. //sqlconsole 这个是你登录你的数据库后新建的数据库(应该不绕口吧)
  13. dbURL = "jdbc:mysql://rm-bp1lxt0m.mysql.rds.aliyuncs.com:3306/sqlconsole";
  14. user = "user"; //你新建库时的用户名
  15. password = "123456"; //你新建库时的密码,这里我就不写我的真密码了
  16. System.out.println("dbURL:" + dbURL);
  17. }
  18. public static Connection getConnection() {
  19. Connection conn = null;
  20. if (connection == null) {
  21. try {
  22. connection = new MySQLConnections();
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. return null;
  26. }
  27. }
  28. try {
  29. Class.forName(connection.driver);
  30. conn = DriverManager.getConnection(connection.dbURL,
  31. connection.user, connection.password);
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. return conn;
  36. }
  37. }

AndroidManifest.xml

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

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.example.mysqlconnections">
  4. <uses-permission android:name="android.permission.INTERNET" />
  5. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  6. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  7. <application
  8. android:usesCleartextTraffic="true"
  9. android:allowBackup="true"
  10. android:icon="@mipmap/ic_launcher"
  11. android:label="@string/app_name"
  12. android:roundIcon="@mipmap/ic_launcher_round"
  13. android:supportsRtl="true"
  14. android:theme="@style/Theme.MyApplication1">
  15. <activity
  16. android:name=".MainActivity"
  17. android:exported="true">
  18. <intent-filter>
  19. <action android:name="android.intent.action.MAIN" />
  20. <category android:name="android.intent.category.LAUNCHER" />
  21. </intent-filter>
  22. </activity>
  23. </application>
  24. </manifest>

最后看我运行结果

Android Studio和阿里云数据库

参考博客

Android Studio 连接阿里云数据库【制作基于数据库的多人远程聊天APP】

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/400798
推荐阅读
相关标签
  

闽ICP备14008679号