3

我从数据库中读取数据(只有最后一行,我在我的 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。

提前谢谢大家

4

3 回答 3

0

检查返回的字符串result。可能不仅有 json 结构(错误、警告等)。JSON 拼写检查器:http: //jsonlint.com/

于 2012-08-24T15:56:11.417 回答
0

检查json响应后;最好用GSON试试,方便多了;

        JsonParser jsonParser = new JsonParser();
        JsonArray jArray;
if ( jsonParser.parse(result).isJsonArray() ) {
    jArray = jsonParser.parse(result).getAsJsonArray();
} 
else { jArray = new JsonArray(); }
于 2012-08-24T16:00:45.880 回答
0

问题出在 PHP 文件中,JSON 无法理解数据,这就是它为空的原因,我对其进行了更改,现在可以正常工作。

于 2012-08-29T11:01:50.110 回答