【问题标题】:Retrieving array back from database server android?从数据库服务器android检索数组?
【发布时间】:2015-05-01 16:11:40
【问题描述】:

我是 android 开发的新手我的服务器接受一些值进行所需的计算和查询需要发送回设备(应用程序)的值列表 php 脚本返回表单的数组

["12345","999989892","9888889898","9876543513","9876543210","9876543211"]

我需要在android中把这个json_encode数组转换成一个简单的数组。

try{
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://10.0.2.2/tech/serverConnection.php");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            try{
            ResponseHandler<String> responseHandler=new BasicResponseHandler();
            String responseBody = httpClient.execute(httpPost, responseHandler);
            JSONArray test = new JSONArray(responseBody);
            resultArray = test.join(",").split(",");}
            catch (JSONException e) {
                e.printStackTrace();}
            }
    catch(ClientProtocolException e){
        Log.e("ClientProtocol", "Log_tag");
        e.printStackTrace();
    }
    catch(IOException e){
        Log.e("Log_tag", "IOException");
        e.printStackTrace();
    }

当我尝试显示任何数字(比如说 resultArray[1])时,我得到一个空指针异常。我假设问题出在我的响应或解析数组上。该程序在将数据发送到服务器时正常工作,只有当我尝试从中获取数据时才会出现问题。 感谢您的任何帮助。

【问题讨论】:

  • 所以resultArray 为空?是这样,test 是空的吗?
  • 谢谢@inmyth,一旦我整理好我的 php 脚本,你的回答就奏效了。我有一个错误,但是当服务器返回一个空数组时,它会给出一个 Index out of bound 错误。
  • 首先,您的回复如何? "12345","999989892",... 或 ["12345","999989892",...(带括号)?
  • 我刚刚意识到第一个值被视为 ["1234" 而不是 "1234"。如果我只是检测到'['并删除它,它会被认为是一种糟糕的方法吗?
  • 在这种情况下,您的响应应该被解析为 JSONArray。很抱歉我误解了你的问题。我的答案之所以有效,仅仅是因为它在响应中找到了逗号。您可以尝试JSONArray test = new JSONArray(responseBody); 并获取元素String thetwo = test.get(2);

标签: php android arrays json


【解决方案1】:

您不应该加入数组或用逗号分隔它。你应该这样做

JSONArray arr = new JSONArray(responseBody);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
    list.add(arr.getJSONObject(i).toString());
}

然后你可以做 list.get(x) 来获取字符串

【讨论】:

  • W/SingleClientConnManager(2508):SingleClientConnManager 的使用无效:连接仍然分配。 W/SingleClientConnManager(2508):确保在分配另一个连接之前释放连接。 W/System.err(2508): org.json.JSONException: Value
猜你喜欢
  • 2015-06-25
  • 1970-01-01
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2019-04-03
相关资源
最近更新 更多