我无法从我的网站连接并显示我的json,因为我收到错误:
java.lang.String cannot be converted to JSONArray
这是代码:
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
private TextView results;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
results = (TextView) findViewById(R.id.results);
results.setText(invioDati());
}
public String invioDati() {
String risultati = "";
String stringaFinale = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("idnomerichiesto","1"));
InputStream is = null;
//HTTP post richiesta
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.davidedellai.net/jsonphp.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(this, "Errore connessione", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if (is != null) {
// converto la risposta in stringa
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
risultati = sb.toString();
}catch (Exception e) {
// errore conversione in stringa
Toast.makeText(this, "Errore stringa "+e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
// parsing dei dati dal json
try {
JSONArray jArray = new JSONArray(risultati);
for (int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("Test", "post_title " + json_data.getString("post_title"));
stringaFinale = json_data.getString("post_title") + " " + (json_data.getString("post_content"));
}
} catch(JSONException e) {
//errore parsing data json
Toast.makeText(this, "Errore parsing json", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
// null quindi nessuna risposta
Toast.makeText(this, "Null", Toast.LENGTH_SHORT).show();
}
return stringaFinale;
}
}
我网站上的php部分是:
<?php
// parametri del database
$db_host = "localhost";
$db_user = "user";
$db_password = "";
$db_name = "mydb";
$db = mysql_connect($db_host, $db_user, $db_password);
if ($db == FALSE)
die ("Errore nella connessione. Verificare i parametri...");
mysql_select_db($db_name, $db)
or die ("Errore nella selezione del database. Verificare i parametri...");
$q=mysql_query("SELECT post_name, post_content FROM avwp_posts WHERE post_status = 'publish' ");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print json_encode(array($output));
mysql_close();
?>
我无法显示任何结果..它会在行JSONArray jArray = new JSONArray(risultati);
的JSONArray中返回错误。 php是问题还是java?与db的连接似乎是正确的..
日志: