下面的代码没有从PHP文件中的这段代码中接收到PHP文件的输出,即"badminton society":
print(json_encode($row['Description']));
如果有人能发现这个错误就太好了。'result'和'is'都是空变量:
public class BackgroundAsyncTask extends AsyncTask<Void, String, Void> {
protected Void doInBackground(Void... params) {
//http post
try{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://ntusocities.host22.com/post.php");
HttpResponse response = client.execute(get);
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 {
JSONObject userObject = new JSONObject(result);
info = userObject.getString("Description");
}
catch(Exception ex){
}
return null;
}
}
非常感谢!
url http://ntusocities.host22.com/post.php
返回badminton society
字符串。这不是一个有效的JSON,所以JSON解析失败并不奇怪。您需要修复服务器端以返回有效的JSON。
如何检查JSON是否有效?-> http://jsonlint.com/
另外,有一个非常简单的方法来获得响应字符串:https://stackoverflow.com/a/4480517/247013
那么,url的输出是:
"badminton society"
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
表示它不是JSON,就像Arhimend已经提到的那样。但是这不应该阻止您获得一个有效的InputStream。试试这个:
protected Void doInBackground(Void... params) {
//http post
try{
is = new java.net.URL("http://ntusocities.host22.com/post.php").openStream();
} catch(Exception e){
Log.e("log_tag", "Error in http connection ", e);
}
...
无论如何,代码将在
处解析失败。 JSONObject userObject = new JSONObject(result);
您是否在AndroidManifest.xml中添加了权限
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
你提到的链接,给出数据
{"info":[{"SocietyID":"SOC003","Name":"Badminton","Type":"Sport","President":"Me","VicePresident":"You","ContactEmail":"me@gmail.com","Description":"badminton society"}]}<!-- some data-->
Just remove, '[' and ']' and "<!-- some data-->" from your response. I think the "some data part is comment.
其他都很好。
然后尝试下面的代码来获取值,
JSONObject userObject;
try {
userObject = new JSONObject(content);
JSONObject info = userObject.getJSONObject("info");
String name = info.getString("Name");
String type = info.getString("Type");
String description = info.getString("Description");
// like this fetch all value/fields
Log.i("JOSN", name +", "+ type +", "+ description);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
祝你一切顺利!