android錯誤之android.os.NetworkOnMainThreadException

來源:互聯網
上載者:User

在做一個天氣預報的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;}}


經過查閱資料,大體錯誤應該是這樣的,

於是把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();}}


 

 


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.