Android实战简单新闻客户端(3)---网络数据请求,json包解析

首先是Fragment嵌套一个包含listview的fragment。


参考文章:Fragment嵌套Fragment实现多tab页面的效果

在父fragemnt的oncreateview里面给父fragment添加子fragment,具体步骤如下:
1.获取fragmentmanager,但是是使用getChildFragmentManager()返回,赋值给viewpageadapter。

        MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());

2.重写viewpageadapter

public static class MyPagerAdapter extends FragmentPagerAdapter {
        private final List mFragments = new ArrayList<>();
        private final List mFragmentTitles = new ArrayList<>();

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }

3.定义新的子fragment,加入adapter列表即可。

改写后的NewsFragment:

public class NewsFragment extends Fragment {
    
    private TabLayout mTablayout;
    private ViewPager mViewPager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, null);
        mTablayout = (TabLayout) view.findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
        mViewPager.setOffscreenPageLimit(3);

        MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
        TestFragment fg1 = new TestFragment();
        Bundle args1 = new Bundle();
        args1.putString("text", "第1个Fragment");

        fg1.setArguments(args1);
        TestFragment fg2 = new TestFragment();
        Bundle args2 = new Bundle();
        args2.putString("text", "第2个Fragment");
        fg2.setArguments(args2);

        TestFragment fg3 = new TestFragment();
        Bundle args3 = new Bundle();
        args3.putString("text", "第3个Fragment");
        fg3.setArguments(args3);

        TestFragment fg4 = new TestFragment();
        Bundle args4 = new Bundle();
        args4.putString("text", "第4个Fragment");
        fg4.setArguments(args4);

        adapter.addFragment(fg1, getString(R.string.top));
        adapter.addFragment(fg2, getString(R.string.nba));
        adapter.addFragment(fg3, getString(R.string.jokes));
        adapter.addFragment(fg4, getString(R.string.cars));
        
        mViewPager.setAdapter(adapter);

        
        mTablayout.addTab(mTablayout.newTab().setText(R.string.top));
        mTablayout.addTab(mTablayout.newTab().setText(R.string.nba));
        mTablayout.addTab(mTablayout.newTab().setText(R.string.cars));
        mTablayout.addTab(mTablayout.newTab().setText(R.string.jokes));
        mTablayout.setupWithViewPager(mViewPager);
        return view;
    }

    
        

    public static class MyPagerAdapter extends FragmentPagerAdapter {
        private final List mFragments = new ArrayList<>();
        private final List mFragmentTitles = new ArrayList<>();

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}

test_fragment:

public class TestFragment extends Fragment {



    String text;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.test_fragment, null);
        TextView textView = (TextView) view.findViewById(R.id.text_1);
        Bundle args = getArguments();
        if (args != null) {
            text = args.getString("text");
        }
        textView.setText(text);
        return view;
    }
}

测试:
Android实战简单新闻客户端(3)---网络数据请求,json包解析_第1张图片

新闻信息获取:

关于这个可以去抓包或者使用爬虫的方式获取数据。我这里去百度API找一个新闻类的api使用。Android实战简单新闻客户端(3)---网络数据请求,json包解析_第2张图片

原作者使用okhttp这个库访问网络。其实无所谓,使用其他网络框架也是一样的。
我不想使用框架,就是用基本的的HttpURLConnection访问网络。
具体没什么介绍的,最基本的get请求。获得json包进行解析。

获取JsonCode:

public class HttpUtils {

    public static String urlConnget(String uri) {
        String content = "";
        try {
            URL url = new URL(uri);

            HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
            httpconn.setRequestMethod("GET");

            httpconn.setRequestProperty("apikey", "你的apikey");
            httpconn.connect();

            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");
                int i;
                // read
                while ((i = isr.read()) != -1) {
                    content = content + (char) i;
                }
                isr.close();
                Log.d("xxxx", content);
                return content;
            }
            httpconn.disconnect();

        } catch (Exception e) {
            Log.d("xxxx", e.toString());
            e.printStackTrace();
        }
        return content;
    }

}

解析json:

public class JsonUtils {

    public static List NewslistData(String jsonstring) {
        List newsList = new ArrayList();
        try {
            JSONObject jsonObject = new JSONObject(jsonstring);
            int resultCode = jsonObject.getInt("code");
            if (resultCode == 200) {
                //获取新闻列表
                JSONArray resultJsonArray = jsonObject.getJSONArray("newslist");
                //循环列表
                for (int i = 0; i < resultJsonArray.length(); i++) {
                    News news = new News();
                    JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);
                    news.setTitle(resultJsonObject.getString("title"));
                    news.setCtime(resultJsonObject.getString("ctime"));
                    news.setDescription(resultJsonObject.getString("description"));
                    news.setPicurl(resultJsonObject.getString("picUrl"));
                    news.setUrl(resultJsonObject.getString("url"));
                    newsList.add(news);
                }

                return newsList;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

        return newsList;
    }
}

数据填入Fragment:

在fragment里写一个listview:

这里使用了volley这个框架来加载网络图片:

RequestQueue mQueue = Volley.newRequestQueue(getContext());
        ImageLoader imageLoader = new ImageLoader(mQueue, new ImageLoader.ImageCache() {
            @Override
            public void putBitmap(String url, Bitmap bitmap) {
            }
            @Override
            public Bitmap getBitmap(String url) {
                return null;
            }
        });
        networkImageView.setDefaultImageResId(R.mipmap.ic_launcher);
        networkImageView.setErrorImageResId(R.mipmap.ic_launcher);
        networkImageView.setImageUrl(news.getPicurl(),
                imageLoader);

具体效果如下:
Android实战简单新闻客户端(3)---网络数据请求,json包解析_第3张图片

你可能感兴趣的:(Android开发基础)