我想在我的数据库中读取数据,然后在模拟器中显示它,因为我使用PHP脚本作为Web服务连接到我的Mysql数据库,但是我的程序在解析Json时抛出异常,这个例外:
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray
我在互联网上做了一些研究,但我只是在没有解决方案的情况下发现了这个问题
如果有人能帮助我,我真的需要那个 这是我的代码:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bdVille");
$sql=mysql_query("select * from tblVille where Nom_ville like'".$_REQUEST['ville']."%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
这是java代码:
package com.exemple.ville;
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;
import android.widget.Toast;
public class ville extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Définir le texte et appeler la fonction de connexion.
txt.setText("Connexion...");
// Appeler la méthode pour récupérer les données JSON
txt.setText(getServerData(strURL));
}
// Mettre l'adresse du script PHP
// Attention localhost ou 127.0.0.1 ne fonctionnent pas. Mettre l'adresse IP local.
public static final String strURL = "http://192.168.1.108/htdocs/ville.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
// Envoyer la requête au script PHP.
// Script PHP : $sql=mysql_query("select * from tblVille where Nom_ville like '".$_REQUEST['ville']."%'");
// $_REQUEST['ville'] sera remplacé par L dans notre exemple.
// Ce qui veut dire que la requête enverra les villes commençant par la lettre L
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ville","L"));
// Envoie de la commande http
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
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());
}
// Convertion de la requête en 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 les données JSON
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
// Affichage ID_ville et Nom_ville dans le LogCat
Log.i("log_tag","ID_ville: "+json_data.getInt("ID_ville")+", Nom_ville: "+json_data.getString("Nom_ville"));
Toast.makeText(this, "ID_ville: "+json_data.getInt("ID_ville")+", Nom_ville: "+json_data.getString("Nom_ville"), Toast.LENGTH_SHORT).show();
// Résultats de la requête
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
答案 0 :(得分:1)
嘿,做出这些改变。
package com.Online.Test;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class OnlineTestActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
HttpClient client;
JSONObject json;
String Dat;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultView = (TextView) findViewById(R.id.tvjson);
client = new DefaultHttpClient();
try {
json = RedData();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dat = json.toString();
new Read().onPostExecute(Dat);
}
public JSONObject RedData() throws ClientProtocolException, IOException, JSONException {
HttpPost httppost = new HttpPost("//link.php");
HttpResponse r = client.execute(httppost);
// int status = r.getStatusLine().getStatusCode();
//if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray jArray = new JSONArray(data);
JSONObject last = jArray.getJSONObject(0); // 0 -> the last object
return last;
// } else {
// Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG);
// return null;
//}
}
public class Read extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = RedData();
//Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG);
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String data) {
// TODO Auto-generated method stub
resultView.setText(data);
}
}
}
答案 1 :(得分:0)
我认为错误来自那一行:
JSONArray jArray = new JSONArray(result);
您正在尝试将无效的Json字符串转换为json数组。
答案 2 :(得分:0)
事实上,你的json编码似乎没有正常工作,实际上是你给的JSON:
[
{
"ID_ville": "1",
"Nom_ville": "Paris"
},
{
"ID_ville": "2",
"Nom_ville": "Marseille"
},
{
"ID_ville": "3",
"Nom_ville": "Lyon"
},
{
"ID_ville": "4",
"Nom_ville": "Toulouse"
},
{
"ID_ville": "5",
"Nom_ville": "Nice"
},
{
"ID_ville": "6",
"Nom_ville": "Nantes"
},
{
"ID_ville": "7",
"Nom_ville": "Strasbourg"
},
{
"ID_ville": "8",
"Nom_ville": "Montpellier"
},
{
"ID_ville": "9",
"Nom_ville": "Bordeaux"
},
{
"ID_ville": "10",
"Nom_ville": "Lille"
}
]
尝试将它放在jsonlint.com中并且会给你错误,问题在于它是一个ZERO WIDTH JOINER字符,可能你可能想要开始只是回显静态json来检查这个。我的猜测,是你以某种方式复制粘贴这个角色。
测试这个角色的另一种方法是什么?,尝试复制粘贴这个{“ID_ville”:“9”,“Nom_ville”:“波尔多”},在你的控制台中我会看到类似的东西
<强>解决方案强>
检查你的字符,编码并使用静态回声尝试响应,而不是转到数据库。