大体意思是用eclipse ee创建一个Javaweb项目,该项目能从MySQL数据库中获取user表的数据,将数据封装成json格式,将此项目发布到本地Tomcat服务器,在android端获取刚才的json数据,并用listview显示。废话不多说下面直接开始。
很简单,建立一个servlet用来处理数据,再建一个数据库工具类,我这里是DatabaseUtil.java,不要忘记servlet在web.xml中需要注册。
项目结构:
package com.servlet.demo;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
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 net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.DatabaseUtil;
public class ServletDemo1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletDemo1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sql = "select * from user";
JSONArray jsonArray=new JSONArray(); //json数组
try {
ResultSet result = DatabaseUtil.query(sql);
while (result.next()) {
JSONObject jObject=new JSONObject(); //json临时对象
jObject.put("id", result.getInt(1));
jObject.put("username", result.getString(2));
jObject.put("password", result.getString(3));
jsonArray.add(jObject); //将封装好的json对象放入json数组
}
} catch (SQLException e) {
e.printStackTrace();
}
String jsondata=jsonArray.toString(); //将json数组转换成字符串,供下面返回给android端使用
//System.out.println(jsondata); //本地测试用
response.getWriter().append(jsondata).flush();
}
}
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Statement;
public class DatabaseUtil {
private static Connection mConnection;
private static Connection getConnection() {
if (mConnection == null) {
String url = "jdbc:mysql://localhost:3306/mybatis";
try {
Class.forName("com.mysql.jdbc.Driver");
mConnection = (Connection) DriverManager.getConnection(url, "root", "123");
} catch (Exception e) {
e.printStackTrace();
}
}
return mConnection;
}
//这里只用了查询操作
public static ResultSet query(String querySql) throws SQLException {
Statement stateMent = (Statement) getConnection().createStatement();
return stateMent.executeQuery(querySql);
}
public static void closeConnection() {
if (mConnection != null) {
try {
mConnection.close();
mConnection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
ConnectTest
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
ServletDemo1
com.servlet.demo.ServletDemo1
ServletDemo1
/ServletDemo1
在浏览器地址栏里输入(端口啥的自己改了的话用自己的,不多说)
http://localhost:8080/ConnectTest/ServletDemo1
测试结果:
也比较简单,有两个activity,在mainactivity中有个button按钮,点击后跳转到第二个activity,我这里是ListActivity ,在listactivity中显示获取到的json数据。
package util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class HttpUtil {
public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);
}
}
package com.ccc.connecttest.activity;
public class User {
private int id;
private String username;
private String password;
public User(int id,String username, String password){
this.id=id;
this.username=username;
this.password=password;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
package com.ccc.connecttest.activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ccc.connecttest.R;
import java.util.List;
public class UserAdapter extends ArrayAdapter {
private int resourceId;
public UserAdapter(Context context, int resourceId, List objects) {
super(context, resourceId,objects);
this.resourceId=resourceId;
}
@Override
public View getView(int position, View convertView,ViewGroup parent) {
User user=getItem(position);
View view;
ViewHolder viewHolder;
if(convertView==null){
view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
viewHolder=new ViewHolder();
viewHolder.userid=(TextView)view.findViewById(R.id.tv_id);
viewHolder.username=(TextView)view.findViewById(R.id.tv_username);
viewHolder.userpassword=(TextView)view.findViewById(R.id.tv_password);
view.setTag(viewHolder); //将viewHolder存储在view中
}else{
view=convertView;
viewHolder=(ViewHolder)view.getTag();
}
viewHolder.userid.setText(String.valueOf(user.getId()));
viewHolder.username.setText(user.getUsername());
viewHolder.userpassword.setText(user.getPassword());
return view;
}
static class ViewHolder{
TextView userid;
TextView username;
TextView userpassword;
}
}
package com.ccc.connecttest.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import com.ccc.connecttest.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import util.HttpUtil;
public class ListActivity extends AppCompatActivity {
private List userList=new ArrayList<>();
private ListView listView;
private String json_url="http://192.168.2.133:8080/ConnectTest/ServletDemo1";//本地Tomcat刚才测试的地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
queryFromServer(json_url); //处理取得数据
listView=findViewById(R.id.lv);
UserAdapter adapter = new UserAdapter(ListActivity.this, R.layout.user, userList);
listView.setAdapter(adapter);
}
private void queryFromServer(String json_url) {
HttpUtil.sendOkHttpRequest(json_url, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("error","出现错误!");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText=response.body().string();
try {
JSONArray jsonArray=new JSONArray(responseText);
for(int i=0;i
package com.ccc.connecttest.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.ccc.connecttest.R;
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.btnSign);
//点击跳转到显示页面
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ListActivity.class));
}
});
}
}
activity_main.xml:
activity_list.xml:
listview每一项适配文件: user.xml
demo
new demo
https://github.com/Commandercc/smallthings/blob/master/GetJsonDemo.zip 这个新的demo可以看一下