本地json数据解析

本地json数据解析_第1张图片



private ListView mF1Lv;

Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        if (msg.what==1){
            List articles = (List) msg.obj;
            //Toast.makeText(getActivity(),articles.get(0).getTitle(),Toast.LENGTH_LONG).show();
            MyAdapter myAdapter = new MyAdapter(articles,getActivity());
            mF1Lv.setAdapter(myAdapter);
        }
    }
};

try {
    InputStream open = getActivity().getAssets().open("news.json");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte[] b = new byte[1024];
    int len = -1;
    while ((len = open.read(b))!=-1){
        outputStream.write(b,0,len);
    }
    String string = outputStream.toString();
    //Log.i("xxx",string+"-------------------");
    Gson gson = new Gson();
    Bean_sj bean_sj = gson.fromJson(string, Bean_sj.class);
    List articles = bean_sj.getList().getArticles();
    Toast.makeText(getActivity(),string,Toast.LENGTH_LONG).show();

    Message message = new Message();
    message.what = 1;
    message.obj = articles;
    handler.sendMessage(message);



} catch (IOException e) {
    e.printStackTrace();
}

public class MyAdapter extends BaseAdapter{

    private List articles;
    private Context context;

    public MyAdapter(List articles, Context context) {
        this.articles = articles;
        this.context = context;
    }


    @Override
    public int getCount() {
        return articles.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view1, ViewGroup viewGroup) {

        ViewHolder viewHolder =null;

        if (view1 == null){
            viewHolder = new ViewHolder();
            view1 = View.inflate(context, R.layout.item,null);
            viewHolder.item_tv1 = view1.findViewById(R.id.item_tv1);
            viewHolder.item_tv2 = view1.findViewById(R.id.item_tv2);
            view1.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) view1.getTag();
        }

        viewHolder.item_tv1.setText(articles.get(i).getTitle());
        viewHolder.item_tv2.setText(articles.get(i).getDescription());


        return view1;
    }

    class ViewHolder{
        TextView item_tv1 ,item_tv2;
    }
}

你可能感兴趣的:(本地json数据解析)