gpt4 book ai didi

java - Android模拟器连接本地mysql数据库的方法

转载 作者:搜寻专家 更新时间:2023-11-01 07:37:32 24 4
gpt4 key购买 nike

我想在本地连接 mysql 数据库和 android 模拟器。我使用 http GET 和 POST 方法通过 App Engine 从 Google Cloud SQL 访问数据,但我想使用 phpmyadmin 将其与本地连接..

当我使用下面的代码时,它显示 Toast for connection failed

        String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","Hammad"));

//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/myApp/read_data.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

}
//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");
Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
}
is.close();

result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();

}

//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("user_id")+
", Username: "+json_data.getString("username")+
", Name: "+json_data.getInt("name")+
", City: "+json_data.getInt("city")
);
Toast.makeText(getApplicationContext(), "JsonArray pass", Toast.LENGTH_SHORT).show();
}

}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}

}

最佳答案

如果您在模拟器中运行它,localhost:3306 将无法运行。将其替换为运行 MySQL 的计算机的 IP 地址。因此,例如,如果您的本地开发机器(运行 MySQL)使用 IP 192.168.0.10,请将其更改为 192.168.0.10:3306

只是为了扩展一点 - 当您尝试访问 http://localhost:3306 时在模拟器中(甚至在设备上)它尝试连接到环回地址(在模拟器/设备上)上的端口 3306。您显然没有在 android 上运行 SQL 服务,所以这没有意义。

此外,根据您的操作系统配置,您可能需要在防火墙中打开端口 3306。

编辑:Warren 的提示(下方)将我引向 details在安卓文档中。如果您不想弄乱操作系统的防火墙,则可能要坚持使用 10.0.2.2。

关于java - Android模拟器连接本地mysql数据库的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693665/

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