【发布时间】:2011-06-11 18:07:50
【问题描述】:
我正在尝试从 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();
它在浏览器上完美运行。 这是安卓代码:
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)
我一直在阅读教程上的cmets,所以也许有人有同样的错误但我没有找到它,这有点奇怪。
我在这里查看了类似的帖子,但它们没有帮助。如果这个问题是重复的,请指出我的答案,如果不是,任何帮助将不胜感激!
【问题讨论】:
-
看起来
result在这一行是"yes":JSONArray jArray = new JSONArray(result);(我不应该指出)不是有效的 JSON。
标签: android mysql json parsing