综合

//MainActivity 
public class MainActivity extends BaseAcitivity {


    private RadioGroup rg;
    private XlistView xlistview;
    private FragmentManager manager;
    private TextView text;

    @Override
    protected int layoutResID() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        //控件
        rg = findViewById(R.id.rg);
        xlistview = findViewById(R.id.xlistview);
        text = findViewById(R.id.text);
    }

    @Override
    protected void initData() {
        //管理者
        manager = getSupportFragmentManager();
        final FragmentTransaction transaction = manager.beginTransaction();
        //添加事务
        final Frag1 frag1 = new Frag1();
        final Frag2 frag2 = new Frag2();
        final Frag3 frag3 = new Frag3();
        final Frag4 frag4 = new Frag4();
        final Frag5 frag5 = new Frag5();
        transaction.add(R.id.fragment,frag1);
        transaction.add(R.id.fragment,frag2);
        transaction.add(R.id.fragment,frag3);
        transaction.add(R.id.fragment,frag4);
        transaction.add(R.id.fragment,frag5);
        //提交
        transaction.show(frag1).hide(frag2).hide(frag3).hide(frag4).hide(frag5);
        transaction.commit();

        //默认
        rg.check(R.id.rb1);

        //点击监听
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                FragmentTransaction qq = manager.beginTransaction();
                  switch (checkedId){
                    case R.id.rb1:
                        qq.show(frag1).hide(frag2).hide(frag3).hide(frag4).hide(frag5);
                        text.setText("首页");
                        break;
                    case R.id.rb2:
                        qq.show(frag2).hide(frag1).hide(frag3).hide(frag4).hide(frag5);
                        text.setText("自选");
                        break;
                    case R.id.rb3:
                        qq.show(frag3).hide(frag2).hide(frag1).hide(frag4).hide(frag5);
                        text.setText("行情");
                        break;
                    case R.id.rb4:
                        qq.show(frag4).hide(frag2).hide(frag3).hide(frag1).hide(frag5);
                        text.setText("咨询");
                        break;
                    case R.id.rb5:
                        qq.show(frag5).hide(frag2).hide(frag3).hide(frag4).hide(frag1);
                        text.setText("交易");
                        break;

                }
                qq.commit();

            }
        });


        ArrayList<String> list = new ArrayList<>();
        list.add("客服热点");
        list.add("营业部网点");
        list.add("系统设置");
        list.add("换肤");
         //  适配器
        xlistview.setPullRefreshEnable(true);
        xlistview.setPullLoadEnable(true);
        xlistview.setAdapter(new My_Xlist_Adapter(MainActivity.this,list));


    }
}

//写TabLayout标题的Frag
public class Frag1 extends BaseFragment {


    private ViewPager pager;
    private TabLayout tab;
    private TextView text;
    private ArrayList<String> tabs;

    @Override
    protected int layoutResID() {
        return R.layout.frag1;
    }

    @Override
    protected void initView(View view) {
        tab = view.findViewById(R.id.tab);
        pager = view.findViewById(R.id.pager);
        text = view.findViewById(R.id.text);

    }

    @Override
    protected void initData() {
        //获取数据库中添加的数据
        ArrayList<ChannelItem> channelItems = DBUtil.getTabData(getActivity());
        //标签集合
        tabs = new ArrayList<>();
        for (int i = 0; i < channelItems.size(); i++) {
            String tabname = channelItems.get(i).getName();
            tabs.add(tabname);
        }

        //适配器
        pager.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                ChildFragment fragment = new ChildFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("position",i);
                fragment.setArguments(bundle);



                return fragment;
            }

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

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

        //关联适配器
        tab.setupWithViewPager(pager);



        //点击跳转
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ChannelActivity.class);
                startActivityForResult(intent, 0);
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取数据库添加的频道
        ArrayList<ChannelItem> channelItems  = DBUtil.getTabData(getActivity());
       tabs.clear();
        for (int i = 0; i < channelItems.size(); i++) {
            String tabname = channelItems.get(i).getName();
            tabs.add(tabname);
        }

        //适配器
        pager.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                ChildFragment fragment = new ChildFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("position",i);
                fragment.setArguments(bundle);
                return fragment;
            }

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

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

        //关联适配器
        tab.setupWithViewPager(pager);


    }
}


//写PullToRefreshListView的页面

public class ChildFragment extends BaseFragment {

    private PullToRefreshListView plistview;
    private int page = 1;
    private android.os.Handler handler = new android.os.Handler();
    private JSONArray newData;
    private String type = "";
    private boolean netWorks;

    @Override
    protected int layoutResID() {
        return R.layout.child_fargment;
    }

    @Override
    protected void initView(View view) {

        plistview = view.findViewById(R.id.plistview);
        //接受值
        Bundle bundle = getArguments();
        int i = (int) bundle.get("position");
        i %= 7;
        if (i == 0) {
            type = "xbsjxw";
        } else if (i == 1) {
            type = "txs";
        } else if (i == 2) {
            type = "toutiao";
        } else if (i == 3) {
            type = "news/mobile/jbgg";
        } else if (i == 4) {
            type = "news/mobile/mgxw";
        } else if (i == 5) {
            type = "news/mobile/ggxw";
        } else if (i == 6) {
            type = "news/mobile/jjxw";
        } else if (i == 7) {
            type = "news/mobile/lcxw";
        }
        ///网络状态
        netWorks = NetWorks.isNetWorks(getActivity());


    }

    @Override
    protected void initData() {
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (netWorks) {
                            page = 1;
                            getData();
                        }

                        plistview.onRefreshComplete();
                    }
                }, 2000);
            }

            //上拉加载
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {


                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (netWorks) {
                            page++;
                            getData();
                        }
                        plistview.onRefreshComplete();
                    }
                }, 2000);
            }
        });
        if (netWorks) {
            //解析数据
            getData();
            Toast.makeText(getActivity(), "有网", Toast.LENGTH_SHORT).show();
        } else {
            //
            Toast.makeText(getActivity(), "无网", Toast.LENGTH_SHORT).show();
            //查询
            Dao dao = new Dao(getActivity());
            //创建集合
            JSONArray jsonArray = new JSONArray();
            Cursor query = dao.query("caches", null, null, null, null, null, null);
            if(query.moveToFirst()){
                do {
                    //创建对象
                    JSONObject jsonObject = new JSONObject();
                    String title = query.getString(query.getColumnIndex("title"));
                    String img = query.getString(query.getColumnIndex("img"));
                    try {
                        //添加到对象
                        jsonObject.put("title",title);
                        jsonObject.put("img",img);
                        //添加到集合
                        jsonArray.put(jsonObject);
                        //适配器
                        plistview.setAdapter(new My_Plist_Adapter(getActivity(), jsonArray));

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

                }while(query.moveToNext());

            }



        }


    }
	//请求数据的方法
    private void getData() {
        MyAsyncTask myAsyncTask = new MyAsyncTask();
        myAsyncTask.execute();

    }

    //异步解析
    class MyAsyncTask extends AsyncTask<String, Integer, String> {


        private long add;

        @Override
        protected String doInBackground(String... strings) {
            String path = "http://mnews.gw.com.cn/wap/data/news/" + type + "/page_" + page + ".json";
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                if (conn.getResponseCode() == 200) {
                    InputStream inputStream = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        bos.write(buffer, 0, len);
                    }
                    bos.close();
                    inputStream.close();
                    String json = bos.toString();

                    return json;
                }


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


            return null;
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                //原生解析
                JSONArray jsonArray = new JSONArray(s);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                JSONArray data = jsonObject.getJSONArray("data");
                //创建一个新的集合
                if (page == 1) {
                    newData = new JSONArray();
                }
                Dao dao = new Dao(getActivity());
                //删除数据库
                dao.delete("caches",null,null);
                //添加原来集合
                for (int i = 0; i < data.length(); i++) {
                    newData.put(data.get(i));
                    //添加到数据库
			        ContentValues values = new ContentValues();
                    values.put("title", data.getJSONObject(i).getString("title"));
                    values.put("img", data.getJSONObject(i).getString("img"));
                    add = dao.add("caches", null, values);

                }
                if (add>0){
                    Toast.makeText(getActivity(), "添加成功", Toast.LENGTH_SHORT).show();
                }

                //适配器
                plistview.setAdapter(new My_Plist_Adapter(getActivity(), newData));

                //显示新一页
                plistview.setSelection(newData.length() - (data.length() - 1));


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

        }
    }
}

//sql数据库
public class MySqlite extends SQLiteOpenHelper {
    public MySqlite(Context context) {
        super(context, "bwy", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table caches(title TEXT,img TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
//Dao
public class Dao {

    private final SQLiteDatabase db;

    public Dao(Context context) {
        MySqlite mySqlite = new MySqlite(context);
        db = mySqlite.getWritableDatabase();
    }
    //添加
    public long add(String table, String nullColumnHack, ContentValues values) {
          return db.insert(table,nullColumnHack,values);
    }

    //查询
    public Cursor query(String table, String[] columns, String selection,
                        String[] selectionArgs, String groupBy, String having,
                        String orderBy){
       return db.query(table,columns,selection,selectionArgs,groupBy,having,orderBy);
    }

    //删除
    public long delete(String table, String whereClause, String[] whereArgs){
        return db.delete(table,whereClause,whereArgs);
    }





}


//网络
public class NetWork {
    public static boolean isNetWork(Context context){
        ConnectivityManager conn= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        if(info!=null){
            return info.isAvailable();
        }
        return false;
    }


}













相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页