【发布时间】: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);