我正在使用eclipse,我想将我的android应用程序连接到我的sql数据库。
我的activity.java代码是
public class MainActivity extends Activity {
TextView resultView;
private InputStream is;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultView=(TextView) findViewById(R.id.action_settings);
}
public void getData() {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","suman"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/hello/try.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("id")+
", Name: "+json_data.getString("name")+
", Address: "+json_data.getInt("address")+
", Contact: "+json_data.getInt("contact")
);
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();
}
}
}
但运行后,应用程序数据库未显示在avd上,或者显示应用程序未经检测地停止。请再试一次。
答案 0 :(得分:1)
使用应该使用localserver的路径
http://10.0.2.2 / [your application folder on server] / [php file(.php)];
http://10.0.2.2 /hello/try.php
而不是
http://127.0.0.1/hello/try.php
请参阅示例
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/