1. 程式人生 > >json解析展示ListView

json解析展示ListView

加粗樣式 public class MainActivity extends AppCompatActivity { private ListView listView; private final int UPDATE = 1; @SuppressLint(“HandlerLeak”)private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case UPDATE: // List<ContentDataBean.Result.Data> datas = (List<ContentDataBean.Result.Data>) msg.obj; mAdapter.setmDatas((List<ContentDataBean.Data>) msg.obj); break; } } }; private ContentAdapter mAdapter;

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

    listView = findViewById(R.id.listview);
    //建立介面卡
    mAdapter = new ContentAdapter(this);
    listView.setAdapter(mAdapter);

    new Thread(new Runnable() {
        @Override
        public void run() {
            requestData();
        }
    }).start();
}
//路徑
private String urlStr = "http://apis.juhe.cn/cook/query?key=749ed0361d71426cc88e77824790c5a6&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=3";
//請求資料
private void requestData(){
    try {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(5000);
        urlConnection.setConnectTimeout(5000);
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == 200){
            String result = stream2String(urlConnection.getInputStream());
            ContentDataBean dataBean = new Gson().fromJson(result, ContentDataBean.class);
            mHandler.sendMessage(mHandler.obtainMessage(UPDATE, dataBean.getResult().getData()));
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private String stream2String(InputStream inputStream) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    for (String temp = bufferedReader.readLine(); temp != null; temp = bufferedReader.readLine()){
        stringBuilder.append(temp);
    }
    return stringBuilder.toString();
}