找不到logcat抱怨的JSON解析错误

时间:2011-06-11 18:07:50

标签: android mysql json parsing

我正在尝试一个教程,从MySQL数据库中获取数据到android,你可以在这里找到: http://www.helloandroid.com/tutorials/connecting-mysql-database

所以这是我试图获取数据的表格:

CREATE  TABLE IF NOT EXISTS `pfc_db`.`capas` (
  `id` VARCHAR(10) NOT NULL ,
  `nombre` VARCHAR(50) NOT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

这是执行查询的php脚本的片段:

$query = "select * from CAPAS";

$sql=mysql_query($query);
if (!$sql) {
    die("The query ($query) could not be executed in the BD: " . mysql_error());
}
while( $row=mysql_fetch_array($sql)){
    $output[]=$row;
    if (isset($output)){
        echo "yes ";
            echo $output[0]['nombre'];
    }
    else{echo "no";}
}
print(json_encode($output));
mysql_close();

它在浏览器上完美运行。 这是android代码:

package com.example.androidconn;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AndroidConnection extends Activity {
    /** Called when the activity is first created. */
    TextView txt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Create a crude view - this should really be set via the layout resources  
        // but since its an example saves declaring them in the XML.  
        LinearLayout rootLayout = new LinearLayout(getApplicationContext());  
        txt = new TextView(getApplicationContext());  
        rootLayout.addView(txt);  
        setContentView(rootLayout);  

        // Set the text and call the connect function.  
        txt.setText("Connecting..."); 
        //call the method to run the data retreival
        txt.setText(getServerData(KEY_121)); 
    }

    public static final String KEY_121 = "http://10.0.2.2/api/prueba.php"; //i use my real ip here

    private String getServerData(String returnString) {

        InputStream is = null;

        String result = "";
        //the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("nombre","Escuelas"));

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_121);
                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);
                StringBuilder 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());
        }
        //parse json data
        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","id: "+json_data.getString("id")+
                                ", nombre: "+json_data.getString("nombre")
                        );
                        //Get an output to the screen
                        returnString += "\n\t" + jArray.getJSONObject(i); 
                }
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
        return returnString; 
    }    
}

最后这是logcat:

D/AndroidRuntime(  313): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime(  313): CheckJNI is ON
D/AndroidRuntime(  313): --- registering native functions ---
I/ActivityManager(   58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.androidconn/.AndroidConnection }
D/AndroidRuntime(  313): Shutting down VM
D/dalvikvm(  313): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(  313): NOTE: attach of thread 'Binder Thread #3' failed
E/log_tag (  281): Error parsing data org.json.JSONException: Value yes of type java.lang.String cannot be converted to JSONArray
I/ActivityManager(   58): Displayed activity com.example.androidconn/.AndroidConnection: 1636 ms (total 1636 ms)

我一直在阅读教程中的评论,以便可能有人有同样的错误,但我没有找到它,这有点奇怪。

我在这里检查了类似的帖子,但他们没有帮助。如果重复这个问题,请指出答案,如果不是,那么任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:2)

我认为您的'echo "yes "输出在print(json_encode($output));输出之前被读取,然后Android JSON解析器会看到:

yes

它期待JSON,因此错误:

  

java.lang.String类型的值yes无法转换为JSONArray

从您的PHP中删除echo调试语句,并将while循环保留为:

while( $row=mysql_fetch_array($sql)){
    $output[]=$row;
}

至少应该为你提供一些有效的JSON输出。

答案 1 :(得分:0)

错误是由此行引起的:

JSONArray jArray = new JSONArray(result);

这是因为结果中包含的数据不代表JSON数组。您应该将结果中的数据打印到日志中,并查看服务器实际返回的内容。