json listView 資料請求解析小例子

weixin_34320159發表於2017-02-13
package com.example.requestdata;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.R.string;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    // 請求地址
    private final String path = "http://pkuie.euming.com/urming_pkuie/system/getMyIndex?offset=0&pageSize=10&accessToken=&_=1486990327923";
    // 超時時常
    private final int timeout = 5000;
    // 轉圈
    private ProgressDialog progressDialog;

    private List<userData> datas = new ArrayList<userData>();
    private ListView listView;
    private Myadapter adapter;
    private Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);

            datas = (List<userData>) msg.obj;
            adapter.notifyDataSetChanged();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.iv);
        if (adapter == null) {

            adapter = new Myadapter();
            listView.setAdapter(adapter);

        } else {
            adapter.notifyDataSetChanged();
        }
        

        // 轉圈
        progressDialog = new ProgressDialog(this);
        progressDialog.show();

        // 開啟子執行緒請求資料
        new Thread() {
            @Override
            public void run() {

                try {
                    // 請求資料
                    URL url = new URL(path);
                    // httpurlConnection
                    HttpURLConnection con = (HttpURLConnection) url
                            .openConnection();
                    // 設定請求資訊
                    con.setRequestMethod("GET");
                    con.setConnectTimeout(timeout);
                    // 得到請求的狀態碼
                    int status = con.getResponseCode();
                    // 得到輸入流
                    InputStream inputStream = con.getInputStream();
                    // 建立輸出流
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    // OK
                    if (status == 200) {
                        List<userData> ds = new ArrayList<userData>();
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        // 迴圈獲取資料
                        while ((len = inputStream.read(buffer)) > 0) {
                            os.write(buffer, 0, len);
                        }
                        // 轉化資料型別
                        String data = os.toString();
                        // 列印資料

                        //
                        // //轉化資料格式
                        JSONObject ob = new JSONObject(data);
                        JSONArray arr = ob.getJSONArray("datas");
                        for (int i = 0; i < arr.length(); i++) {

                            JSONObject o = arr.getJSONObject(i);

                            userData d = new userData(o.getString("title"),
                                    o.getString("realname"));

                            ds.add(d);
                        }

                        Message s = Message.obtain();
                        s.obj = ds;
                        handle.sendMessage(s);

                    }
                    // 關閉流
                    os.close();
                    inputStream.close();

                    // 停止
                    progressDialog.dismiss();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    // e.printStackTrace();
                    // 停止
                    progressDialog.dismiss();

                    Log.e("出錯了", e.getMessage() + "error11111");

                }
            };

        }.start();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    class Myadapter extends BaseAdapter {

        @Override
        public int getCount() {

            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = null;
            
            if (convertView == null) {
                
                v= View.inflate(MainActivity.this, R.layout.item, null);
            }
            
            userData userData = datas.get(position);
            Log.e("datas", userData.toString());
            TextView tv1 = (TextView) v.findViewById(R.id.tv1);
            TextView tv2 = (TextView) v.findViewById(R.id.tv2);
            tv1.setText(userData.getTitle());
            tv2.setText(userData.getRealname());
            Log.e("haah", userData.getTitle() + "ddddddd");
            return v;
        }

    }
}

相關文章