android是不能直接访问数据库的,所以可以通过servlet来访问数据库显示到android界面。通常如果你的电脑运行内存还行的话,就用两个eclipse,我就用了两个eclipse,一个用于servlet连接数据库,就是有web项目的eclipse,另一个是用于android的,就是得有SDK和ADT的android项目。 在eclipse里运行,这里面有默认的浏览器,服务器Tomcat也加进去了,就直接运行了 MainActivity.java,这个用于连接访问responseJsonData,进行android界面显示 运行进入登录界面,输入用户名和密码
数据库—servlet—android
先讲第一个,也就是数据库-servlet
这是数据库的设计建表
包括一个输入校验表和一个界面主表显示
第一部分代码,也就是第一个有动态web的eclipse中的代码(由于代码较多,其他的都放在了我的网盘里,网盘放的就是我的整个项目)
链接:https://pan.baidu.com/s/1Xw2O2-C5UMIcRjNaNibBCg 提取码:jzw8
现在我展示的是servlet连接数据库的代码
responseJsonData.javapackage com.bai; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; /** * Servlet implementation class responseJsonData */ @WebServlet("/responseJsonData") public class responseJsonData extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public responseJsonData() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost( request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub Connection con; Statement sql; ResultSet rs; PrintWriter out =response.getWriter(); try{Class.forName("com.mysql.cj.jdbc.Driver").newInstance();} catch(Exception e){out.print(e);} try{ String uri="jdbc:mysql://localhost:3306/android?useSSL=false&serverTimezone=UTC"; con=DriverManager.getConnection(uri,"root","199735"); sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM student"); ArrayList<student> arrList = new ArrayList<student>(); while(rs.next()) { student s = new student(); s.setSno(rs.getString("sno")); s.setSname(rs.getString("sname")); s.setSage(rs.getString("sage")); s.setSbirth(rs.getDate("sbirth").toString()); arrList.add(s); } String js1 = JSONObject.toJSONString(arrList); System.out.println(js1); response.setContentType("text/html; charset=utf-8"); response.setCharacterEncoding("utf-8"); out.print(js1); con.close(); } catch(SQLException e1){out.print(e1);} } }
这样,就通过servlet访问连接到了数据库
第二部分,servlet-android
android项目代码,我在这儿展示的是连接访问servlet的代码,其他代码可以去看我网盘:(整个项目在网盘:链接:https://pan.baidu.com/s/1qFMYx7NXWQvrtnvnvhfafA 提取码:kemv)
RegisterAct.java,这个用于连接loginservlet,进行输入校验package com.example.testjson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONObject; import com.example.testjson.MainActivity.DownloadThread; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SimpleAdapter; import android.widget.Toast; public class RegisterAct extends Activity { private Button reset; private Button register; // 用户 private EditText uNameEditText; // 密码 private EditText pwdEditText1; private String userName; private String password; private String serverIp = "10.0.2.2"; private String serverPort = "8080"; private String httpStr; private String postStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); reset = (Button) findViewById(R.id.reset); register = (Button) findViewById(R.id.register); uNameEditText=(EditText)findViewById(R.id.username); pwdEditText1=(EditText)findViewById(R.id.password1); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (registerIsSuccsee()) { //register(); LoginThread loginThread = new LoginThread(); loginThread.start(); } } }); reset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uNameEditText.setText(""); pwdEditText1.setText(""); } }); } /* * 判断用户注册输入是否规范 录入信息验证 验证是否通过 */ private boolean registerIsSuccsee(){ //获取用户输入 userName=uNameEditText.getText().toString(); password=pwdEditText1.getText().toString(); if("".equals(userName)){ //用户输入用户名为空 Toast.makeText(RegisterAct.this, "用户名不能为空!", Toast.LENGTH_SHORT).show(); return false; }else if("".equals(password)){ //密码不能为空 Toast.makeText(RegisterAct.this, "密码不能为空!", Toast.LENGTH_SHORT).show(); return false; } return true; } class LoginThread extends Thread{ @Override public void run() { register(); } } /** * 注册 */ private void register() { httpStr = "https://"; postStr = httpStr + serverIp + ":" + serverPort + "/aaaa/loginServlet"; try { HttpParams httpParams = new BasicHttpParams(); // 设置连接超时 int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpPost httpPost = new HttpPost(postStr); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", userName)); nvps.add(new BasicNameValuePair("password", password)); nvps.add(new BasicNameValuePair("client", "1")); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); InputStream is=entity.getContent(); String isUser = ConvertStreamToString(is); Message msg = new Message(); msg.what = 3; if(!"failure".equals(isUser)){ msg.what = 1; }else{ msg.what = 2; } uiHandler.sendMessage(msg); /*if(!"failure".equals(isUser)){ //uNameEditText.setText(""); //pwdEditText1.setText(""); Intent i=new Intent(RegisterAct.this,MainActivity.class); startActivity(i); }else{ AlertDialog.Builder builder1=new Builder(RegisterAct.this); builder1.setMessage("用户名或密码不正确!!!"); builder1.setTitle("提示"); builder1.setPositiveButton("确认", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); }*/ } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private Handler uiHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case 1: uNameEditText.setText(""); pwdEditText1.setText(""); Intent i=new Intent(RegisterAct.this,MainActivity.class); startActivity(i); break; case 2: AlertDialog.Builder builder1=new Builder(RegisterAct.this); builder1.setMessage("用户名或密码不正确!!!"); builder1.setTitle("提示"); builder1.setPositiveButton("确认", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); break; default: break; } } }; // 读取字符 public String ConvertStreamToString(InputStream is) { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String returnStr = ""; try { while ((returnStr = br.readLine()) != null) { sb.append(returnStr); } } catch (IOException e) { e.printStackTrace(); } final String result = sb.toString(); System.out.println(result); return result; } }
package com.example.testjson; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Serializable; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends Activity { private ListView lv; // uiHandler在主线程中创建,所以自动绑定主线程 // private Handler uiHandler = new Handler(); //uiHandler在主线程中创建,所以自动绑定主线程 private Handler uiHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case 1: System.out.println("handleMessage thread id " + Thread.currentThread().getId()); System.out.println("msg.arg1:" + msg.arg1); int[] i = new int[] { R.id.name, R.id.jing, R.id.wei }; SimpleAdapter simplead = new SimpleAdapter(MainActivity.this, (List)msg.obj, R.layout.show, new String[] { "name", "jing", "wei" }, i); MainActivity.this.lv.setAdapter(simplead); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.listView1); DownloadThread downloadThread = new DownloadThread(); downloadThread.start(); } class DownloadThread extends Thread{ @Override public void run() { List<Map<String, Object>> listall = new ArrayList<Map<String, Object>>(); StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet( "https://10.0.2.2:8080/aaaa/responseJsonData"); try { HttpResponse response = client.execute(get); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(),"GBK")); for (String s = reader.readLine(); s != null; s = reader .readLine()) { builder.append(s); } reader.close(); String str = builder.toString(); Log.d("json",str); //str.getBytes("utf-8"); JSONArray array = new JSONArray(new String(str)); Map<String, Object> listem1 = new HashMap<String, Object>(); listem1.put("name", "学号"); listem1.put("jing", "姓名"); listem1.put("wei", "专业"); listall.add(listem1); for (int i = 0; i < array.length(); i++) { JSONObject item = array.getJSONObject(i); String name = item.getString("sno"); String u_longitude = item.getString("sname"); String u_latitude = item.getString("sage"); Map<String, Object> listem = new HashMap<String, Object>(); listem.put("name", name); listem.put("jing", u_longitude); listem.put("wei", u_latitude); listall.add(listem); } Message msg = new Message(); msg.what = 1; msg.obj = listall; //将该Message发送给对应的Handler uiHandler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } } }
最后,就显示出来了
关注小何童鞋,一只不断努力的小白!
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算