public class Fragment01 extends Fragment{ private static final String TAG = "MainActivity"; private String url="http://api.iclient.ifeng.com/ClientNews?id=JS83,FOCUSJS83&action=defalult"; private ListView listView; private MyHandler myHandler=new MyHandler(); @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment01,container,false); listView = view.findViewById(R.id.listview); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); new Thread(){ @Override public void run() { try { URL u = new URL(url); HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.setConnectTimeout(5000); if (connection.getResponseCode()==200){ InputStream stream = connection.getInputStream(); String json = Method(stream); Message message = new Message(); message.what=0; message.obj=json; myHandler.sendMessage(message); } }catch (Exception e){ e.printStackTrace(); } } }.start(); } public String Method(InputStream inputStream) throws IOException { int len=0; byte[] buffer=new byte[1024]; StringBuffer stringBuffer = new StringBuffer(); while ((len=inputStream.read(buffer))!=-1){ String s = new String(buffer, 0, len); stringBuffer.append(s); } return stringBuffer.toString(); } class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { switch (msg.what){ case 0: String obj = (String) msg.obj; Gson gson = new Gson(); Type type = new TypeToken<LinkedList<NewsBean>>() { }.getType(); LinkedList<NewsBean> list = gson.fromJson(obj, type); List<NewsBean.ItemBean> item = list.get(0).getItem(); MyBase myBase = new MyBase(getActivity(), item); listView.setAdapter(myBase); break; } } } }
HttpURLConnection ListView展示
最新推荐文章于 2018-12-28 21:01:57 发布