我想创建一个简单的活动,它只从数据库中获取一个值(其中只有1个)。 但我有一个大问题。我总是在LogCat中得到相同的错误:“解析data.org.json.JSONException时出错:java.lang.String类型的值1nulln无法转换为JSONArray。” 这是我的代码:
public class DailyQ extends Activity {
InputStream is;
String quest;
JSONObject json_data;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_q);
getData();
}
public void getData() {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://domain.com/file.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", "Fehler bei der http Verbindung "+e.toString());
}
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());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
int id = json_data.getInt("day");
quest = json_data.getString("question");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(quest);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
这是PHP文件:
<?php
mysql_connect(...) or die ("Keine Verbindung");
mysql_select_db("...);
$q=mysql_query("SELECT day,question FROM quest");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
我看了很多线程,但我找不到答案。你有答案吗?
先谢谢你,对不起我的英语(我是德国学生)
答案 0 :(得分:0)
我不相信你的result
是一个json编码的字符串,因此你的JSONArray函数失败了:
查看requirements for your JSONArray function
JSON字符串应该类似于this:
{"1": "1_data", "2": "2_data", "3": "3_data"}
您可以将{
添加到}
的正面result
,它可能会有效。