您的位置:首页 > 理论基础 > 计算机网络

Android httpGet 使用 以及使用Handler异步更新textview的text值

2013-05-07 11:48 721 查看
在 Activity中定义3个属性

private Handler handler; //实现异步更新textview值
private String result;//保存get返回的字符串
private TextView text;//textview控件


初始化属性值

//初始化的时候代码要在 onCreate方法中初始化 不能在子线程中
handler = new Handler();
text = (TextView) findViewById(R.id.text);


源代码:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
text = (TextView) findViewById(R.id.text);

new Thread() {
public void run() {

String str = "http://www.hbecoop.com/index.html";
HttpResponse httpResponse = null;
HttpGet get = new HttpGet(str);
try {

httpResponse = (new DefaultHttpClient()).execute(get);

} catch (ClientProtocolException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
result = EntityUtils.toString(httpResponse.getEntity());

handler.post(new Runnable() {

@Override
public void run() {

text.setText(result);
}
});

} catch (ParseException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}

}
}

}.start();

}
}

备注:

需要注意几点 

1:需要在xml中添加网络访问权限   <uses-permission android:name="android.permission.INTERNET" />

2:如果httpget直接在主线程里面使用有可能会抛出异常,导致程序崩溃  建议使用异步的形式来获取资源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐