您的位置:首页 > 移动开发 > Android开发

php+mysql+json android 连接wamp

2016-04-22 00:00 351 查看
参考 http://blog.sina.com.cn/s/blog_6923201d01011t6h.html

http://www.cnphp6.com/archives/106137

遇到的问题:

找不到NameValuePair cannot be resolve....,

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
解决方法: build path中删除无效的jar路径,添加 eclipse安装路径下 sdk\platforms\android-23\optional 路径下的jar文件

在主线程中不能进行耗时操作以及在非UI线程中,禁止修改UI:
修改部分代码如下:

b1.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(){
@SuppressWarnings("deprecation")
@Override
public void run() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// http get
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(
"http://wlan_address:80/test.php");
//			                  HttpGet httpget = new HttpGet(
//				                         "http://computer_address:80/test.php");
HttpResponse response = httpclient.execute(httpget);
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");

String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
int ct_id;
String ct_name;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
ct_id = json_data.getInt("id");
ct_name = json_data.getString("name");

Message msg = new Message();
msg.what = 0x123;
msg.obj = ct_name;
Log.e("NAME", ct_name);
myhandler.sendMessage(msg);

// tv.append(ct_name + " \n");
}
} catch (JSONException e1) {
// Toast.makeText(getBaseContext(), "No City Found"
// ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}

}
}.start();
}
});


private final Handler myhandler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == 0x123){
System.out.println("------->" + msg.obj);
tv.append(msg.obj + "\n");
}
}
};
6. org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android
当在模拟器中运行程序时,ip地址是自己电脑的真实ip地址
当在真机上运行时,ip地址是cmd-》ipconfig 下wlan的ip地址 (真机和电脑需要在同一无线局域网下)
7. PHP代码修改

<?php
$link=mysqli_connect("localhost","root","123456","test");
mysqli_set_charset($link, "utf8");
//mysqli_select_db("test",$link);
$sql=mysqli_query($link,"select * from teacher ");
while($row=mysqli_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysqli_close($link);

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: