【发布时间】:2013-11-23 22:08:04
【问题描述】:
我想做一个简单的活动,它只从数据库中获取一个值(其中只有 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();
?>
我查看了很多主题,但找不到答案。你有答案吗?
提前谢谢你,对不起我的英语(我是德国学生)
【问题讨论】:
-
请发布您的 JSON。
标签: java php android mysql json