private ListView listView;
private List<JsonBean.DataBean> list=new ArrayList<>();
private ListviewAdapter adapter;
//创建handler
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what==1){
// 解析json
Gson gson = new Gson();
JsonBean jsonBean = gson.fromJson(msg.obj.toString(), JsonBean.class);
list=jsonBean.getData();
// 设置适配器
adapter= new ListviewAdapter(MainActivity.this, list);
listView.setAdapter(adapter);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView= (ListView) findViewById(R.id.listview);
Task task=new Task();
task.execute();
// listviewi点击跳转
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, TwoActivity.class);
// 将数据传到另一个activity
intent.putExtra("img",list.get(position).getIMAGEURL());
intent.putExtra("title",list.get(position).getTITLE());
intent.putExtra("keywords",list.get(position).getFROMNAME());
intent.putExtra("description",list.get(position).getSHOWTIME());
startActivity(intent);
}
});
}
// 使用AsyncTask异步类代替Thread
class Task extends AsyncTask{
private StringBuffer sb;
@Override
protected Object doInBackground(Object[] params) {
// 使用HttpURLConnection发起请求获取数据(AsyncTask +HttpURLConnection )
HttpURLConnection httpURLConnection=null;
try {
// 建立连接
URL url = new URL("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=0");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
//判断返回码
if (httpURLConnection.getResponseCode()==200){
InputStream is = httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
sb = new StringBuffer();
// 请求网络数据并将tngou节点下的数据解析道数据集合中 加载的数据是A卷中的 data下的
while (true){
String s = br.readLine();
if (s==null){
break;
}
sb.append(s);
}
is.close();
br.close();
Message msg = Message.obtain();
msg.obj=sb.toString();
msg.what=1;
handler.sendMessage(msg);
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭链接
httpURLConnection.disconnect();
}
return sb.toString();
}
@Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Object o) {
}
}
}
AsyncTask+httpurl
最新推荐文章于 2018-01-01 20:07:26 发布
public class MainActivity extends AppCompatActivity {