gpt4 book ai didi

php - 使用android php json远程连接mysql数据库?

转载 作者:行者123 更新时间:2023-11-29 23:22:39 28 4
gpt4 key购买 nike

我正在尝试使用带有 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时出错:值!类型为java.lang.String的DOCTYPE无法转换为JSONArray

[编辑2]

好的,我明白了这个问题。但现在我面临着一个新的挑战。今天再次尝试执行代码,但现在我在这条线上遇到超时异常 HttpResponse response = httpclient.execute(httppost); (昨天工作正常,我没有改变任何东西)。这不是 URL 问题,因为如果我将其放在浏览器上,它就可以正常工作。

最佳答案

您的响应类型是 String,您应该将其转换为 JSONObject

关于php - 使用android php json远程连接mysql数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194817/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com