网络验证更新组件报NetworkOnMainThreadException和ViewRootImpl$CalledFromWrongThreadException

今天试验写android获得web交互,仿照李兴华的web服务器交换数据。

添加了一些新的功能,即在EditText中输入用户名和密码,然后生成url,反馈给http,并解析获得数据。

实现时点击button,出现了android.os.NetworkOnMainThreadException这个错误,错误行定位在下面感叹号的地方。

public boolean connect(String username , String password) {
		// String username , String password
		try {
			 URL url = new URL("http", "192.168.1.102", 8080,
			 "/test/android.jsp?id=" + username + "&password=" + password);
			 
//			URL url = new URL("http", "192.168.1.102", 8080,
//					"/test/android.jsp?id=youjie&password=123");
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			byte data[] = new byte[512];
//!!!!!			注意这行,需要获得输入流时
			int len = http.getInputStream().read(data);
			if (len > 0) {
				// 构造一个字符串
				String str = new String(data, 0, len).trim();
				return Boolean.parseBoolean(str);
			}
			http.getInputStream().close();
		} catch (Exception e) {
			e.printStackTrace();
			 return false;
		}
		
		return false;
	}

查了一下网上有关这个的错误信息,说是访问网络不能在主线程中进行,心想行啊,起个runnable不就可以了么,然后点击按钮触发的事件时启动这个线程,然后得到反馈的数据更新ui。


可以问题又来了,报这个错误Only the original thread that created a view hierarchy can touch its views ,大概意思是只有原始线程才能修改其组建。

解决方法,大神的,来:http://blog.csdn.net/shenyuemei/article/details/11030679


采用了官方建议的方法,使用了runOnUiThread()这个方法,来更新ui。

public void startThread() {

		Runnable runable = new Runnable() {

//			调用connet放方法从http端获得数据
			@Override
			public void run() {
				flag = connect(one.getText().toString(), two.getText().toString());
//				注意这句:使用系统的更新ui界面的线程
				MainActivity.this.runOnUiThread(updateThread);
			}
		};

//		更新UI界面的线程
		updateThread = new Runnable() {

			@Override
			public void run() {
				tx.setText(String.valueOf(flag));
			}
		};

//		启动连接http端的线程
		new Thread(runable).start();

	}

ok,问题解决,具体项目代码:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值