private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { List<RequestData.NewslistBean> newslist= (List<RequestData.NewslistBean>) msg.obj; MyAdapter adapter = new MyAdapter(newslist,getActivity()); lv.setAdapter(adapter); }
};
private void requestNewData() { new Thread(){ @Override public void run() { requestData(); } }.start(); } private void requestData() { try { URL url = new URL(urlpath); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int responseCode = urlConnection.getResponseCode(); if (responseCode==200){ InputStream inputStream = urlConnection.getInputStream(); String json = toJson(inputStream); Gson gson = new Gson(); RequestData requestData = gson.fromJson(json, RequestData.class); List<RequestData.NewslistBean> newslist = requestData.getNewslist(); Message message = Message.obtain(); message.obj=newslist; handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private String toJson(InputStream inputStream) { StringBuilder builder = new StringBuilder(); String string; InputStreamReader in = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(in); try { while ((string=reader.readLine())!=null){ builder.append(string); } } catch (Exception e) { e.printStackTrace(); } return builder.toString(); }