HttpURLConnection獲取資料並展示到ListView上
阿新 • • 發佈:2018-12-19
** ## MainActivity ** public class DemoActivity extends AppCompatActivity { private ListView mLVContents; private DemoAdapter mAdapter; private final int UPDATE_UI = 1; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_UI: mAdapter.setmDatas((List<List<String>>) msg.obj); break; } } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLVContents = findViewById(R.id.lv_contents); mAdapter = new DemoAdapter(this); mLVContents.setAdapter(mAdapter); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //網路判斷 if(!NetUtil.hasNetwork(DemoActivity.this)) { showNotNetworkDialog(); return; } //查詢資料 new Thread(new Runnable() { @Override public void run() { initData(); } }).start(); } }); mLVContents.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { List<String> data = mAdapter.getItem(position); Toast.makeText(DemoActivity.this, data.get(0) + ":" +data.get(1), Toast.LENGTH_LONG).show(); } }); } private void showNotNetworkDialog() { new AlertDialog.Builder(this) .setTitle("沒有可用網路") .setMessage("當前網路不可用,是否去設定") .setPositiveButton("確認", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Toast.makeText(DemoActivity.this, "去設定", Toast.LENGTH_LONG).show(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } String urlStr = "https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA"; private void initData() { try { URL url = new URL(urlStr); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // 請求方法 超時 int responseCode = urlConnection.getResponseCode(); if(responseCode == 200) { String result = stream2String(urlConnection.getInputStream()); Bean bean = new Gson().fromJson(result, Bean.class); mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, bean.getResult())); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private String stream2String(InputStream inputStream) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()){ sb.append(tmp); } return sb.toString(); } } ## **Adapter** public class DemoAdapter extends BaseAdapter { private List<List<String>> mDatas; private Context mContext; public DemoAdapter(Context context) { this.mContext = context; //初始化 為什麼在這裡寫 mDatas = new ArrayList<>(); } //外部呼叫 更新資料 public void setmDatas(List<List<String>> mDatas) { this.mDatas = mDatas; notifyDataSetChanged(); } @Override public int getCount() { return mDatas.size(); } @Override public List<String> getItem(int position) { List<String> item = mDatas.get(position); //return item.get(0); //return mDatas.get(position).get(0); return item; } @Override public long getItemId(int position) { return position; } //parent = ListView @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh; //複用,不重複建立View if(convertView == null) { //convertView = View.inflate(mContext, R.layout.item, null); convertView = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false); vh = new ViewHolder(); vh.mIcon = convertView.findViewById(R.id.iv_icon); vh.mText = convertView.findViewById(R.id.tv_text); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } //TODO 設定圖片 //設定 資料 //vh.mText.setText(getItem(position)); vh.mText.setText(getItem(position).get(0)); return convertView; } class ViewHolder { private ImageView mIcon; private TextView mText; } } ** ## Bean ** public class Bean { public List<List<String>> result; public List<List<String>> getResult() { return result; } }