关闭

TypeToken解析

标签: TypeToken
1587人阅读 评论(0) 收藏 举报
分类:

package com.bwie.wdhm;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;

import com.bwei.adapter.Myadapter;
import com.bwie.bean.Root;
import com.example.gaoxin1409a20160523.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@SuppressLint(“HandlerLeak”)
public class MainActivity extends Activity {
private List list = new ArrayList();
private ListView lv;
private List typelist;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
list = (List) msg.obj;
System.out.println(list.size());
Myadapter adapter = new Myadapter(MainActivity.this,list);
lv.setAdapter(adapter);
}
};

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   //获取控件     
    lv = (ListView)findViewById(R.id.lv);   
    //启动子线程用于开启数据
    new Thread(){
        @Override
        public void run() {
            NetWork();
        }
    }.start();
}
//请求网络数据
public void NetWork(){
    //请求地址
    String url = "http://172.17.29.120/localuser/ljy/datas/data.json";
    HttpClient httpClient = new DefaultHttpClient();
    //请求类型
    HttpGet httpGet = new HttpGet(url);
    //发送给服务器
    try {
        HttpResponse response = httpClient.execute(httpGet);
        //从服务器取值
        HttpEntity entity = response.getEntity();
        //转换为String类型
        String str = EntityUtils.toString(entity,"gbk");
        //用于解析数据类型的JsON串
        typelist = new ArrayList<Root>();
        Type type = new TypeToken<List<Root>>(){}.getType();
        Gson gson = new Gson();

        typelist  = gson.fromJson(str, type);
        //发送给Handler
        Message msg = Message.obtain();
        msg.obj = typelist;
        handler.sendMessage(msg);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13604次
    • 积分:365
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档