android错误之android.os.NetworkOnMainThreadException

来源:互联网 发布:360软件中心下载 编辑:程序博客网 时间:2024/05/16 09:37

在做一个天气预报的widget的时候,参考了一个源代码,但是一直报错,就从里面抠出来获取天气的代码试试看,结果总是报错

 

就是这个异常,android.os.NetworkOnMainThreadException

代码是这样的:

MainActivity:

public class MainActivity extends Activity {MyWeather myWeather;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myWeather = new MyWeather();System.out.println(myWeather.getCity());}}

MyWeather:

public class MyWeather {public String city;public String temp1;public String weather1;public String img1;public MyWeather(){getWeather();}public void getWeather(){try {URL url = new URL("http://m.weather.com.cn/data/101250101.html");InputStream is = url.openStream();int len = -1;byte[] buffer = new byte[1024];ByteArrayOutputStream bos = new ByteArrayOutputStream();while ((len = is.read(buffer)) != -1) {bos.write(buffer, 0, len);}String info = bos.toString("utf-8");JSONObject dataJson = new JSONObject(info);JSONObject json = dataJson.getJSONObject("weatherinfo");city = json.getString("city");temp1 = json.getString("temp1");weather1 = json.getString("weather1");img1 = json.getString("img1");bos.close();is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (JSONException e) {// TODO: handle exception}}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getTemp1() {return temp1;}public void setTemp1(String temp1) {this.temp1 = temp1;}public String getWeather1() {return weather1;}public void setWeather1(String weather1) {this.weather1 = weather1;}public String getImg1() {return img1;}public void setImg1(String img1) {this.img1 = img1;}}


经过查阅资料,大体错误应该是这样的,主要是说主线程访问网络时出的异常。

 Android在4.0之前的版本 支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,也就是说访问网络的代码不能写在主线程中了。

于是把MainActivity的代码改成如下就可以了,在新开的线程中读取天气,用handler异步加载:

public class MainActivity extends Activity {MyWeather myWeather;private Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case 0:System.out.println("jason.com" + myWeather.getCity());break;}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);new Thread() {@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();myWeather = new MyWeather();Message msg = handler.obtainMessage();msg.what = 0;handler.sendMessage(msg);}}.start();}}


 

作者:jason0539

微博:http://weibo.com/2553717707

博客:http://blog.csdn.net/jason0539(转载请说明出处)

 


原创粉丝点击