异步Gson解析展示

private ListView list_v;
String url = "http://www.xieast.com/api/news/news.php?page=2";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show);
    list_v = findViewById(R.id.list_v);
    //异步
    Myasync myasync = new Myasync();
    myasync.execute(url);
}

public class Myasync extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... strings) {
        DefaultHttpClient client = new DefaultHttpClient();
        String path = strings[0];
        HttpGet gett = new HttpGet(path);
        try {
            HttpResponse response = client.execute(gett);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream inputStream = response.getEntity().getContent();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                inputStream.close();
                outputStream.close();
                String s = outputStream.toString();
                return s;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Gson gson = new Gson();
        Two two = gson.fromJson(s, Two.class);
        final List<Two.DataBean> data = two.getData();
        MyTwoAdapter myTwoAdapter = new MyTwoAdapter(ShowActivity.this, data);
        list_v.setAdapter(myTwoAdapter);
        list_v.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ShowActivity.this, data.get(position).getUrl(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ShowActivity.this, ThreeActivity.class);
                intent.putExtra("url", data.get(position).getUrl());
                startActivity(intent);
            }
        });
    }
}

猜你喜欢

转载自blog.csdn.net/H_BuilDer/article/details/81005750