1、在android4.0以后的版本,主线程(UI线程)不在支持网络请求,原因大概是影响主线程,速度太慢,容易卡机,所以需要开启新的线程请求数据;
thread1 = new Thread(){
@Override
public void run() {
try {
URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
//缓冲读取
byte[] data = new byte[1024];
int len = 0;
String bufferString = \"\";
while((len = bis.read(data)) != -1){
bufferString+=new String(data, 0, len);
}
carList = new JSONArray(bufferString.trim());
//System.out.println(carList);
/*
for(int i=0;i
2、新线程完成后一启动,发现报错,空指针 nullpointerexception,要等待线程完毕后才能得到数据,下面是两种解决方法:
1)要么判断线程是否还活着;
2)要么在线程中设置一flag,结束后,更改其状态
/*
//等待线程thread1执行完毕
while(true){
if(thread1.isAlive()){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
break;
}
}
*/
//当线程还没结束,就睡500毫秒ms
while(!flag){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}}
3、处理返回的json数据
1)向服务器请求Json数据,保存在carList
URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
//缓冲读取
byte[] data = new byte[1024];
int len = 0;
String bufferString = \"\";
while((len = bis.read(data)) != -1){
bufferString+=new String(data, 0, len);
}
carList = new JSONArray(bufferString.trim());