Android foreground to background - background requests data from database + JSON + JDBC + MYSQL

  • Platforms and development tools used:
  • Server: Eclipse-javaEE version, Tomcat9.0
  • Android client: Eclipse-JavaSE version + ADT
  • database side mysql
  • Windows7 operating system
  • JDK
  • gson.jar package, mysql driver package
  1. Description of the completed small case: In the Android foreground, access a page in the background according to the URL, and the page in the background uses the JDBC connection database technology to connect to the database and query the corresponding information according to the query conditions, and use the third-party gson.jar package for this information. The json.toJson() method converts the object into a String string and returns it to the Android front desk. After the Android front desk gets the string, it converts it into data, and uses json.fromJson(String, Type) to convert it into an object and display it on the screen.
  2. Bug fix: directly transfer the result set of ResultSet type to the Android foreground, let the foreground use fromJson() to convert, the result conversion will report an error, try to import the gson package in the background, and use toJson() to convert the object into a string Then give it to the front desk, but the result still doesn't work. Later, I found that the result obtained by toJson() must be given to the front desk. ToJson(object) will not turn the object inside into a string. There is also a StringBuffer object must be created to use its append() method, and a null pointer is reported at the beginning.

First look at the results of the operation:

(The sql statement takes the fifth data)

Android side code:

   Layout section: item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="16dp"
     >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="120dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:scaleType="fitXY"
        android:src="@drawable/timg" />

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imageView1"
        android:layout_marginLeft="14dp"
        android:layout_toRightOf="@+id/imageView1" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="姓名:" />

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView" />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="性别:" />

            <TextView
                android:id="@+id/tv_gender"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView" />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="年龄:" />

            <TextView
                android:id="@+id/tv_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView" />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="身高:" />

            <TextView
                android:id="@+id/tv_hight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView" />

        </TableRow>
    </TableLayout>

</RelativeLayout>

java code: PersonActivity.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.internethttp.R;
import JavaBean.Person;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class PersonActivity  extends Activity{ 
	TextView tv_name,tv_gender,tv_age,tv_hight;
	String URL="http://ly-and-tl.uicp.cn:42696/AndroidServer/jsonServlet";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	// TODO Auto-generated method stub
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.item);
    	init();
    	new TASK().execute(URL);
    }
    
    void init(){
    	tv_name=(TextView) findViewById(R.id.tv_name);
    	tv_gender=(TextView) findViewById(R.id.tv_gender);
    	tv_age=(TextView) findViewById(R.id.tv_age);
    	tv_hight=(TextView) findViewById(R.id.tv_hight);
    }
    
    class TASK  extends  AsyncTask<String, Void, Person>{
    	
		@Override
		protected void onPostExecute(Person result) {
			// TODO Auto-generated method stub
			if(result!=null){
				tv_name.setText(result.getName());
				tv_gender.setText(result.getSex());
				tv_age.setText(String.valueOf(result.getAge()));
				tv_hight.setText(String.valueOf(result.getHight()));
			}
		}

		@SuppressWarnings("finally")
		@Override
		protected Person doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			Person person=null;
			String Url=arg0[0];
			String  str=null;
			StringBuffer sb=new StringBuffer();
			
			try {
				URL url=new URL(Url);
				HttpURLConnection  httpconn=(HttpURLConnection) url.openConnection();
				httpconn.setRequestMethod("GET");
				httpconn.setReadTimeout(5000);
				InputStream inputStream=httpconn.getInputStream();
				InputStreamReader inputReader=new InputStreamReader(inputStream);
				BufferedReader buff=new BufferedReader(inputReader);
				while((str=buff.readLine())!=null){
					sb.append(str);
				}
				Gson gson=new Gson();
				String ss=new String(sb);
				System.out.println(ss);
//前台对json字符串开始转化为对象
	            person=gson.fromJson(ss, new TypeToken<Person>(){}.getType());
	            System.out.println(person.getName());
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				return person;
			}
		}
    }
}

The javaBean, Person.java of the java part of the Android side

public class Person{
	private String id;
	private String name;
	private String sex;
	private int age;
	private float hight;
	private float weight;

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public float getHight() {
		return hight;
	}
	public void setHight(float hight) {
		this.hight = hight;
	}
	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
}

Next is the server-side code:

Deployment of server-side web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>AndroidServer</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
    <servlet-name>a</servlet-name>
    <servlet-class>android.Internet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>a</servlet-name>
    <url-pattern>/b</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>son</servlet-name>
    <servlet-class>android.JsonServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>son</servlet-name>
    <url-pattern>/jsonServlet</url-pattern>
  </servlet-mapping>
</web-app>

 

The main page code of the server, that is, the page connected to the Android client, JsonServlet.java

The server uses gson.jar, which must be placed in the lib directory of tomcat.

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import DataBase.DataBaseConnection;
import DataBase.StudentHealthJavaBean;

public class JsonServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		// super.doGet(req, resp);
                PreparedStatement prepare = null;
		ResultSet result = null;
		Connection con = null;
		String sql = "select * from stu_info where id=?";
		StudentHealthJavaBean student=null;
		String str=null;
		con = DataBaseConnection.getConnection();
		try {
			prepare = con.prepareStatement(sql);
			prepare.setString(1, "5");
			result = prepare.executeQuery();
			if (result != null) {
				student= new StudentHealthJavaBean();
				if (result.next()) {
					student.setName(result.getString("name"));
					student.setAge(result.getInt("age"));
					student.setId(result.getString("id"));
					student.setSex(result.getString("sex"));
					student.setHight(result.getFloat("hight"));
					student.setWeight(result.getFloat("weight"));
					Gson json=new Gson();
				 str=json.toJson(student);
//使用json包提供的转化为字符串
				}
				resp.setCharacterEncoding("utf-8");
				PrintWriter p = resp.getWriter();
				p.println(str);
//把json字符串给前台
				p.flush();
			}
			DataBaseConnection.closeDatabaseConnection(con, prepare, result);

		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		super.doPost(req, resp);
	}

}

Server-side database connection code:

public class DataBaseConnection {
	public static String url1="jdbc:mysql://localhost:3306/";
    public static String databaseName="students";
    public static String userName="&user=root";
    public static String password="&password=root";
    public static String driverName="com.mysql.jdbc.Driver";
    public static String encoding="&useUnicode=true&characterEncoding=UTF-8";
    public static String url=url1+databaseName+"?"+"useSSL=false"+encoding+userName+password;
      @SuppressWarnings("finally")
	public static Connection getConnection() {
   	   Connection con=null;
   	     try {
				Class.forName(driverName);
				con=DriverManager.getConnection(url);
			} catch (ClassNotFoundException | SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}finally {
				return con;
			}
      }
    
      public static void closeDatabaseConnection(Connection con,PreparedStatement ps,ResultSet rs) {
			try {
		    	   if(rs!=null)rs.close();
				if(ps!=null) ps.close();
		    	if(con!=null) con.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
      }
}

 The javabean on the server side is the same as that on the Android side, and the field name is exactly the same as the database.

public class StudentHealthJavaBean {
	private String id;
	private String name;
	private String sex;
	private int age;
	private float hight;
	private float weight;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public float getHight() {
		return hight;
	}

	public void setHight(float hight) {
		this.hight = hight;
	}

	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
	public StudentHealthJavaBean() {
		// TODO 自动生成的构造函数存根
	}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324935554&siteId=291194637