我从数据库中读取数据(只有最后一行,我在我的php文件中执行)我想要做的是分别使用每个字段的数据,但问题是JSONArray是空的我试了很多如何在不同的帖子中寻找它,但它总是空的。
这是我的代码
public class MainActivity extends Activity {
/** Called when the activity is first created. */
JSONArray jArray = null;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String ct_id;
String ct_name;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://xxx.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
String line=null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("fecha");
ct_name=json_data.getString("dia");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "JSON is empty" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
它总是捕获JSONException e1。
提前感谢everibody
答案 0 :(得分:0)
检查result
中的返回字符串。可能不仅有json结构(错误,警告等)。 JSON拼写检查器:http://jsonlint.com/
答案 1 :(得分:0)
检查json响应后;更好地尝试使用GSON,更方便;
JsonParser jsonParser = new JsonParser();
JsonArray jArray;
if ( jsonParser.parse(result).isJsonArray() ) {
jArray = jsonParser.parse(result).getAsJsonArray();
}
else { jArray = new JsonArray(); }
答案 2 :(得分:0)
问题出在PHP文件中,JSON无法理解数据,这就是为什么它是空的,我改了它,现在工作正常。