Java 如何将Android emulator与本地mysql数据库连接
我想用android emulator在本地连接mysql数据库。我使用http GET和POST方法通过app engine从Google Cloud SQL访问数据,但我想使用phpmyadmin将其与本地连接 当我使用下面的代码时,它显示连接失败Java 如何将Android emulator与本地mysql数据库连接,java,android,emulation,Java,Android,Emulation,我想用android emulator在本地连接mysql数据库。我使用http GET和POST方法通过app engine从Google Cloud SQL访问数据,但我想使用phpmyadmin将其与本地连接 当我使用下面的代码时,它显示连接失败 String result = ""; //the year data to send ArrayList<NameValuePair> nameValuePairs = new Arr
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 仅扩展一点-当您尝试在模拟器内甚至在设备上访问时,它会尝试连接到模拟器/设备上环回地址上的端口3306。显然,您没有在android上运行SQL服务,因此这没有意义 此外,根据您的操作系统配置,您可能必须在防火墙中打开端口3306
编辑:沃伦下面的提示让我找到了Android文档中的。如果你不想干扰操作系统的防火墙,你可能想坚持使用10.0.2.2。更多信息:如果你想从运行仿真器的机器上获取本地主机,你需要使用10.0.2.2-简短详细信息:感谢Marvin和Warren的快速回复,你是对的,我使用上述方法在本地机器上循环,工作正常。。我面临的另一个问题是,当我在第一个活动中提交我的第一个查询时,它可以正常工作,同时我移动到第二个活动,但在第二个活动中,它对我的第二个查询不起作用。我通过将第二个活动替换为launcher activity而不是第一个活动来检查它,它开始工作。。我做错了什么?