我想从网址获取数据。在这种情况下,我已经有完整的php,数据已经转换为json并在localhost中运行(http://localhost/adchara1/index.php/?year = 1)
这是php脚本
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM people
WHERE
birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close(); ?>
这是结果
[{"id":"1","name":"kongkea","sex":"1","birthyear":"1990"}, {"id":"2","name":"thida","sex":"0","birthyear":"2000"}]?>
我想使用按钮点击并在textview中显示此结果
答案 0 :(得分:5)
将此代码写入Button OnClickListener
try {
String url = "http://YourIPAddress/adchara1/index.php/?year=1";
HttpPost httppost = new HttpPost(url);
try {
HttpParams p = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(p);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
JSONArray jArray = new JSONArray(responseBody);
String text="";
for (int i = 0; i < jArray.length(); i++) {
JSONObject e = jArray.getJSONObject(i);
text = text + "ID : "+e.getString("id")+"\n";
text = text + "Name : "+e.getString("name")+"\n";
text = text + "Sex : "+e.getString("sex")+"\n";
text = text + "Birthyear : "+e.getString("birthyear")+"\n";
}
Textview.setText(text);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
t.printStackTrace();
}
如果您有任何澄清通知我
答案 1 :(得分:1)
Button button =(Button) findViewById(R.id.button);
TextView tv =(TextView) findViewById(R.id.textview);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String result = connectionFromServer("http://localhost/adchara1/index.php/?year=1");
tv.setText(result);
}
});
public static String connectionFromServer(String url) throws IOException {
BufferedReader inputStream = null;
URL myurl = new URL(url);
URLConnection dc = myurl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
inputStream = new BufferedReader(new InputStreamReader(
dc.getInputStream()));
// read the JSON results into a string
String result = inputStream.readLine();
return result;
}
这将在textview中显示结果。