您好我正在尝试通过Web服务从数据库加载我的listview。我尝试过两次这样做,我对每个阶段都不太自信。
从我的tomcat返回一个列表/数组,这里是代码
String mylist[] = {"", "", "", "", "", ""};
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, user, pass);
String query1 = "select username from Users where online = 'yes'";
PreparedStatement preparedStmt1 = con.prepareStatement(query1);
ResultSet result1 = preparedStmt1.executeQuery();
int i = 0;
while (result1.next()) {
mylist[i] = result1.getString(1);
}
} catch (Exception e1) {
e1.printStackTrace();
}
out.println(mylist);
out.close();
我的问题是这是从网络服务返回列表的正确方法吗?
第二阶段是将列表放到我的列表视图中,这是我的代码
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI webservice = new URI("http://192.168.0.3:8080/Users/users");
request.setURI(webservice);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
while ((rd.readLine()) != null) {
ArrayList<String> list = rd.readLine();
}
} catch (Exception e1) {
e1.printStackTrace();
}
这似乎仅在webservice返回单行文本时才起作用。如何从Http请求中检索类似数组的内容?
谢谢!
答案 0 :(得分:0)
WebService只能返回xml或字符串类型,因此您可以将列表放入一个字符串,格式如下:
"this is a string 1; this is a string 2; this is a string 3"
服务器端如下所示:
StringBuilder myList = new StringBuilder();
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, user, pass);
String query1 = "select username from Users where online = 'yes'";
PreparedStatement preparedStmt1 = con.prepareStatement(query1);
ResultSet result1 = preparedStmt1.executeQuery();
int i = 0;
while (result1.next()) {
myList.append( result1.getString(1) + ";");
}
} catch (Exception e1) {
e1.printStackTrace();
}
out.println(mylist.toString());
out.close();
然后从 Android客户端,您可以通过String.split(“;”)获取它;
这是一个例子:
private String inputStreamToString(InputStream is)
{
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024 * 4);
// Read response until the end
try
{
while ((line = rd.readLine()) != null)
{
total.append(line);
}
} catch (IOException e)
{
Log.e(TAG, "error build string" + e.getMessage());
}
// Return full string
return total.toString();
}
InputStream is = response.getEntity().getContent();
String strResponse = inputStreamToString(is);
String mylist[] = strResponse .split(";");
或者您可以使用JSON解析列表对象并从WebService转移到Android客户端