package com.bwie.text;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.List;import com.bwie.bean.Bean;import com.bwie.bean.Data;import com.google.gson.Gson;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListView;import android.widget.TextView;public class MainActivity extends ActionBarActivity {String dataUrl = "http://121.42.8.95:8090/AndroidServer/yk.json"; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { final Bean beans = (Bean) msg.obj; final Listlist = beans.getData();
final MyAdapter adapter= new MyAdapter(MainActivity.this, list,All);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//实现删除
list.remove(position);
adapter.notifyDataSetChanged();
}
});
}};
private ListView lv;
private TextView All;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listview);
All=(TextView) findViewById(R.id.all);
//请求数据
getData();
}
private void getData() {
new Thread() {
public void run() {
try {
URL url = new URL(dataUrl);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setRequestMethod("GET");
openConnection.connect();
if (openConnection.getResponseCode() == 200) {
InputStream inputStream = openConnection
.getInputStream();
// 解析json
Gson gson = new Gson();
Bean beans = gson.fromJson(new InputStreamReader(
inputStream), Bean.class);
// 发送给handler
Message message = Message.obtain();
message.obj = beans;
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
网友评论