0

您好我正在尝试通过网络服务从数据库中加载我的列表视图。我尝试过两次这样做,但我对每个阶段都不是很有信心。

  1. 从我的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();
    

我的问题是这是从网络服务返回列表的正确方法吗?

  1. 第二阶段是将列表获取到我的列表视图,这是我的代码

    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();
    }
    

这似乎只在 web 服务返回单行文本时有效。如何从 Http 请求中检索类似数组的内容?

谢谢!

4

1 回答 1

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 客户端

于 2012-06-04T02:19:31.837 回答