【发布时间】:2014-11-28 19:20:50
【问题描述】:
我正在尝试使用带有 HTTP 连接的 android 应用程序连接到 mysql 数据库,然后检索 JSONArray 以扫描查询结果。代码如下:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
new JSONfunction().execute();
}
private class JSONfunction extends AsyncTask<Void,Void,JSONArray> {
private JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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());
}
// 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();
jArray=new JSONArray(result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return jArray;
}
@Override
protected JSONArray doInBackground(Void... voids) {
JSONArray jArray=getJSONfromURL("http://192.168.1.5/ConnectData/index.php");
return jArray;
}
protected void onPostExecute(JSONArray result) {
TextView prova = (TextView)findViewById(R.id.txtProva);
try {
JSONObject rec = result.getJSONObject(1);
prova.setText(rec.getString("first_name"));
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
我在执行 while 时遇到错误。在应用程序崩溃的 2 或 3 个周期之后。你能给我任何帮助吗?
[编辑]
我收到此错误: 11-28 20:42:19.006 27688-27702/com.example.marco.provadatabase E/log_tag﹕错误转换结果 org.json.JSONException: Value !DOCTYPE of type java.lang.String cannot be convert to JSONArray
[编辑 2]
好的,我明白了这个问题。但是现在我面临着一个新的。今天再次尝试执行代码,但现在我在 HttpResponse response = httpclient.execute(httppost); (昨天它工作得很好,我没有改变任何东西)。这不是 URL 问题,因为如果我把它放在浏览器上它就可以正常工作。
【问题讨论】:
-
发布 logcat 跟踪。
-
你能发布从服务器返回的内容吗?看起来它不是有效的 JSON...
标签: php android mysql json database