1. 程式人生 > >gson解析菜譜大全把資料放到Listview中

gson解析菜譜大全把資料放到Listview中

XML中的程式碼:

<ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>

Activity中的程式碼:

	private Mybase mybase;
    private final int UPDATE_UI=1;
    private String lujing="http://apis.juhe.cn/cook/query?key=9e7b4454a8f999479620c28f4624de83&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=30&pn=3";
    private ListView listView;
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //把解出來的資料給了介面卡中的集合
            List<Bean.Data> datas= (List<Bean.Data>) msg.obj;
            mybase.setList(datas);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取資源ID
        listView = findViewById(R.id.listview);

        //判斷網路是否可用
        if (!keyong()){
            Toast.makeText(this, "網路不可用", Toast.LENGTH_SHORT).show();
            return ;
        }
        mybase=new Mybase(this);
        listView.setAdapter(mybase);
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        huoqu();
                    }
                }
        ).start();
    }
    private boolean keyong(){
        //獲取網路狀態連線服務
        ConnectivityManager cm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //獲取網路狀態許可權
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return activeNetworkInfo!=null&&activeNetworkInfo.isAvailable();
    }
    //網路請求
    private void huoqu(){
        try {
            //定義url地址
            URL url=new URL(lujing);
            //開啟連線
            HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
            //請求方法
            urlConnection.setRequestMethod("GET");
            //讀取超時
            urlConnection.setReadTimeout(5000);
            //連線超時
            urlConnection.setConnectTimeout(5000);
            int responseCode = urlConnection.getResponseCode();
            if (responseCode==200) {
                String result = zifu(urlConnection.getInputStream());
                Bean bean = new Gson().fromJson(result, Bean.class);
                handler.sendMessage(handler.obtainMessage(UPDATE_UI,bean.getResult().getData()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //位元組流轉化成字元流
    private String zifu(InputStream zijie) throws IOException {
        InputStreamReader inputStreamReader=new InputStreamReader(zijie);
        BufferedReader buff=new BufferedReader(inputStreamReader);
        StringBuilder builder=new StringBuilder();
        for (String imp=buff.readLine();imp!=null;imp=buff.readLine()){
            builder.append(imp);
        }
        return builder.toString();
    }

介面卡中的程式碼:

	 private List<Bean.Data> list;
    private Context context;

    public Mybase(Context context) {
        this.context = context;
        list=new ArrayList<>();
    }

    public void setList(List<Bean.Data> list) {
        this.list = list;
        notifyDataSetChanged();
    }

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

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView==null){
            holder=new ViewHolder();
            convertView=LayoutInflater.from(context).inflate(R.layout.list,parent,false );
            holder.text=convertView.findViewById(R.id.text);
            holder.image=convertView.findViewById(R.id.image);
            convertView.setTag(holder);
        }else{
            holder= (ViewHolder) convertView.getTag();
        }
        holder.text.setText(list.get(position).getTitle());
        return convertView;
    }
    class ViewHolder{
        private ImageView image;
        private TextView text;
    }

解析使用的Bean類:

	public Result result;

    public void setResult(Result result) {
        this.result = result;
    }

    public Result getResult() {
        return result;
    }

    class Result{
        public List<Data> data;

        public void setData(List<Data> data) {
            this.data = data;
        }

        public List<Data> getData() {
            return data;
        }
    }
    class Data{
        public String id;
        public String title;
        public void setId(String id) {
            this.id = id;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }


    }