Android development, the client connects to the local server, and the data is stored in Mysql

The client connects to the local server, stores the data in Mysql, and realizes the interaction between the client and the server.

This blog is written by a little white, so all the code and open source framework will be explained from a new perspective. If there are any mistakes, please correct me and make progress together.
Purpose of this blog:

  1. Realize the data sending and receiving between the Android client and the local server, and realize the interaction.
  2. Realize the connection between the local server and Mysql database, and data storage.

Xiaobai instructions:
1. Android SDK has its own SQLite database, a lot of local data can be stored directly in this lightweight database, and there are many excellent open source frameworks, such as greenDao. However, it is impossible for a non-standalone Android application to store core data locally, and it is even more impossible for the client to directly connect to the database. Generally, the client is dealing with the server. The client sends a request, and the server responds to the request. After a three-way handshake, data exchange begins. Most of the database operations are completed by the server connection.
It's like you go to a restaurant to eat. The chef will take the food out of the refrigerator, process it and present it to you. In this scenario, you are the client, the chef is the server, and the refrigerator is the database.
2. The local server can realize the interaction between the client and the server, and the client and the client under the local area network. If you use a cloud server, such as Alibaba Cloud, Tencent Cloud, Huawei Cloud, etc., you can set up your server here, and access the WAN network according to the public network ip (that is, open mobile data, and you can use your application in all parts of the country) . Xiaobai is still learning how to build a cloud server and is looking forward to it as soon as possible. I have encountered too many pitfalls when setting up a cloud server and cried.

Text:
Preparation tools:
1. Myeclipse (used to build a local server, or eclipse-ee)
2. Tomcat server (just a few M, available online)
3. jdk
4. mysql database (why not Oracle? Because this is free )
5. Navicat database visual display (good stuff, you don’t need to use the command line to view black and white)
6. AndroidStudio Android development ide (this is nonsense, 嚯嚯)
prepare open source library:
1.Okhttp
2.struts

As for how to install the tools, I won't say much. There are many materials on the Internet, the use of the struts library:
Insert picture description here
when all the software is installed, we can start.
———————————————————————
Client (AndroidStudio):
1. Add network permissions:

 <uses-permission android:name="android.permission.INTERNET" />

2. xml file , 2 EditText, 1 Button, 1 Textview.
Insert picture description here

<?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"
    android:orientation="vertical"
    tools:context=".LinktoServerActivity">
    <EditText
        android:layout_weight="2"
        android:id="@+id/usenameer"
        android:hint="账号"
        android:layout_width="match_parent"
        android:layout_height="0dp" />
    <EditText
        android:layout_weight="2"
        android:id="@+id/passworder"
        android:hint="密码"
        android:inputType="numberPassword"
        android:layout_width="match_parent"
        android:layout_height="0dp" />
    <Button
        android:layout_gravity="center"
        android:id="@+id/dengluButton"
        android:text="登录"
        android:layout_width="80dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/xianshi"
        android:textSize="25dp"
        android:text="吧唧吧唧"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="0dp" />
    <LinearLayout
        android:layout_weight="4"
        android:layout_width="match_parent"
        android:layout_height="0dp"></LinearLayout>
</LinearLayout>
  1. Activity.java file
package com.ilikelxystill.fuxi;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ilikelxystill.fuxi.constant_package.Constant_name;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LinktoServerActivity extends AppCompatActivity {
    
    
    private EditText usenameer,passworder;
    private TextView xianshi;
    private Button dengluButton;
    private Constant_name constant_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linkto_server);
        init();
        constant_name = new Constant_name();

        LinkServerer();
    }

    public void init(){
    
    
        usenameer =(EditText)findViewById(R.id.usenameer);
        passworder =(EditText)findViewById(R.id.passworder);
        xianshi = (TextView)findViewById(R.id.xianshi);
        dengluButton =(Button)findViewById(R.id.dengluButton);

    }

    //连接服务器
    public void LinkServerer(){
    
    
         dengluButton.setOnClickListener(new View.OnClickListener() {
    
    
             @Override
             public void onClick(View v) {
    
    

                 //获取输入的数据
                 String getusenameer = usenameer.getText().toString();
                 String getpassworder = passworder.getText().toString();

                //建立客户端
                 OkHttpClient okHttpClient = new OkHttpClient();
                 //实例化请求构造器
                 Request.Builder builder = new Request.Builder();
                 Log.i("haha",constant_name.getUrlInMyCompter()+constant_name.getProjectname()+"Login?usename="+getusenameer+"&password="+getpassworder);
                 //构造器使用get方式绑定 url
                 Request request = builder.get().url(constant_name.getUrlInMyCompter()+constant_name.getProjectname()+"Login?usename="+getusenameer+"&password="+getpassworder).build();
                 //建立Call
                 Call call = okHttpClient.newCall(request);

                  call.enqueue(new Callback() {
    
    
                     @Override
                     public void onFailure(Call call, IOException e) {
    
    
                           Log.i("baba","shibai!!!!!!!!!!!!");
                     }

                     @Override
                     public void onResponse(Call call, Response response) throws IOException {
    
    
                         final String StrGetFromServer = response.body().string();
                         xianshi.post(new Runnable() {
    
    
                             @Override
                             public void run() {
    
    
                                 xianshi.setText(StrGetFromServer);
                             }
                         });

                     }
                 });
                 usenameer.setText("");
                 passworder.setText("");


             }
         });



    }
}

4. Create a new package, constant_package
Constant_name.java
Insert picture description here

package com.ilikelxystill.fuxi.constant_package;

public class Constant_name {
    
    
    //电脑的主机地址,以及端口号,一般是8080
    private   String UrlInMyCompter = "http://192.168.3.6:8888/";
    //服务器项目名
    private  String Projectname = "FuxiServer/";
    public String getUrlInMyCompter() {
    
    
        return UrlInMyCompter;
    }
    public String getProjectname() {
    
    
        return Projectname;
    }


}

—————————————————————————

Myeclipse

Server project name: FuxiServer
Insert picture description here
struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">


<struts>
   
      <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
    <constant name="struts.devMode" value="true"></constant>
    <package name="default" namespace="/" extends="struts-default">
       <!-- 在浏览器敲路径名/denglu,会找到class这个类,的denglu方法 -->
      <action name="Login" class="com.ilikexy.UserAction" method="index"></action>
    </package>
</struts>

UserAction.java

package com.ilikexy;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
//新建一个类,继承 ActionSupport
public class UserAction extends ActionSupport{
    
    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String usename;
    private String password;
    public String index() throws IOException, SQLException, Exception{
    
    
    	System.out.println("账号:"+getUsename()+"\n"+"密码:"+getPassword());
    	
    	 //返回给客户端的信息
    	
    	HttpServletResponse response = ServletActionContext.getResponse();
    	response.setContentType("text/html;charset=utf-8");
    	//转化为写入
    	PrintWriter  writer = response.getWriter();
    
    	//将其写入数据库,当账号和密码都不为空时
    	if((!getUsename().equals(""))&&(!getPassword().equals(""))){
    
    
    		
    		Class.forName("com.mysql.cj.jdbc.Driver");
    	   //原生的Sql语句,向表中插入usename,和 password
    		String sql = "insert into fuxiRegister values('"+getUsename()+"','"+getPassword()+"')";
    	  //连接数据库路径,数据库名为firstdatabase
    		String linktodatabase = "jdbc:mysql://localhost:3306/firstdatabase?useSSL=false&serverTimezone=UTC";
    	  //建立数据库的连接
			Connection con = DriverManager.getConnection(linktodatabase,"root","123456");
		  //执行sql语句
			PreparedStatement prt = con.prepareStatement(sql);
		    prt.execute();
		    //存入成功返回给客户端信息
		  //写入信息
	    	writer.write("login successful !!!!");
	    	
    		
    	}else{
    
    
    		//写入信息
        	writer.write("login Fail !!!!");
    		
    	}	
    	return null;
    }
    
    
	public String getUsename() {
    
    
		return usename;
	}
	public void setUsename(String usename) {
    
    
		this.usename = usename;
	}
	public String getPassword() {
    
    
		return password;
	}
	public void setPassword(String password) {
    
    
		this.password = password;
	}
       
}

Navicat
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
has any problems, errors, please correct me, qq:2569658002

Guess you like

Origin blog.csdn.net/qq_41904106/article/details/108392969