android手风琴特效(五) 从网上获取数据

1 网络请求

public class HttpUtils {
    public static String doGet(String urlStr){
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(urlStr);
         conn = (HttpURLConnection) url.openConnection();
           conn.setReadTimeout(5000);
           conn.setConnectTimeout(5000);
           conn.setRequestMethod("GET");
           if(conn.getResponseCode()==200){
               is = conn.getInputStream();
              baos = new ByteArrayOutputStream();
               int len =-1;
               byte[] buf = new byte[512];
               while ((len = is.read(buf))!=-1){
                   baos.write(buf,0,len);
                   baos.flush();
               }
               Log.d(MainActivity.Tag, "doGet: "+baos.toString());
               return  baos.toString();
           }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null)
            {
                conn.disconnect();
            }
        }
        return null;
    }
}

2 业务逻辑

public class ChapterBiz  {
    public void loadDatas(final Context context, final CallBack callback, boolean useCache){
        AsyncTask<Boolean,Void,List<Chapter>> asyncTask = new AsyncTask<Boolean, Void, List<Chapter>>() {
           private Exception ex;
            @Override
            protected List<Chapter> doInBackground(Boolean... booleans) {
                boolean isUseCache = booleans[0];
                List<Chapter> chapterList = new ArrayList<Chapter>();
                try {
                    if(isUseCache){
                        //Todo load datas from db

                    }
                    //Todo load from net
                    if(chapterList.isEmpty()){
                        List<Chapter> chapterListFromNet = loadFromNet(context);
                        chapterList.addAll(chapterListFromNet);
                    }
                }catch (Exception ex){
                    ex.printStackTrace();
                    this.ex = ex;
                }

                return chapterList;
            }

            @Override
            protected void onPostExecute(List<Chapter> chapters) {
               if(ex!=null){
                   callback.onFailed(ex);
                   return;
               }
               callback.onSuccess(chapters);

            }


        };
        asyncTask.execute(useCache);
    }

    private List<Chapter> loadFromNet(Context context) {
        String Url ="http://www.imooc.com/api/expandablelistview";
        List<Chapter> chapters=new ArrayList<>();
        //1 发请求获取 string数据
        String content =HttpUtils.doGet(Url);
        Log.d(MainActivity.Tag,"获取网络数据成功"+content);
        //2 content-->List<Chapter>
        if (content!=null){
           chapters  = parseContent(content);
        }

        return  chapters;

    }

    private List<Chapter> parseContent(String content) {

        List<Chapter> chapterList = new ArrayList<Chapter>();
        try {
            JSONObject root = new JSONObject(content);
            int errorCode =root.getInt("errorCode");
            if(errorCode==0){
                JSONArray data = root.getJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    JSONObject chapterJsonObj = data.getJSONObject(i);
                    int id =chapterJsonObj.optInt("id");
                    String name =chapterJsonObj.optString("name");
                    Chapter chapter = new Chapter(id,name);
                    chapterList.add(chapter);
                    JSONArray childrenJsonArray=chapterJsonObj.optJSONArray("children");
                    if(childrenJsonArray!=null){
                        for (int j = 0; j <childrenJsonArray.length() ; j++) {
                            JSONObject childJsonObj = childrenJsonArray.getJSONObject(j);
                            int childId =childJsonObj.getInt("id");
                            int pi = childJsonObj.getInt("pid");
                            String childName =childJsonObj.getString("name");
                            ChapterItem chapterItem = new ChapterItem(childId,childName);
                            chapter.addChild(chapterItem);
                        }
                    }

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return chapterList;

    }

    public static interface CallBack{
        void onSuccess(List<Chapter> chapters);
        void onFailed(Exception ex);
    }
}

3获取数据改变expandLisView

private void loadDatas() {
   mchapterBiz.loadDatas(this, new ChapterBiz.CallBack() {
       @Override
       public void onSuccess(List<Chapter> chapters) {
           mDatas.addAll(chapters);
           Log.d(Tag, "onSuccess: "+chapterAdapter);
           chapterAdapter.notifyDataSetChanged();
       }

       @Override
       public void onFailed(Exception ex) {
            ex.printStackTrace();
       }
   }, false);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值