数据库缓存与动态TabLayout和静态帧布局加基类

//Activity基类
public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layoutResID());
        initView();
        initData();
    }


    protected abstract int layoutResID();

    protected abstract void initView();

    protected abstract void initData();


}
//Fragment基类
public abstract class BaseFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), layoutResID(), null);
        initView(view);
        initData();
        return view;
    }

    protected abstract int layoutResID();

    protected abstract void initView(View view);

    protected abstract void initData();

}
//MainActivity 
public class MainActivity extends BaseActivity {


    private RadioGroup rg;

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

    @Override
    protected void initView() {
        rg = findViewById(R.id.rg);

    }

    @Override
    protected void initData() {

        //获得管理者
        final FragmentManager manager = getSupportFragmentManager();
        //开启事务
        final FragmentTransaction transaction = manager.beginTransaction();
        //添加事务
        final Frag1 frag1 = new Frag1();
        final Frag2 frag2 = new Frag2();
        final Frag3 frag3 = new Frag3();
        transaction.add(R.id.fragment,frag1);
        transaction.add(R.id.fragment,frag2);
        transaction.add(R.id.fragment,frag3);
        //提交
        transaction.show(frag1).hide(frag2).hide(frag3);
        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);
                        break;
                    case R.id.rb2:
                        qq.show(frag2).hide(frag3).hide(frag1);
                        break;
                    case R.id.rb3:
                        qq.show(frag3).hide(frag2).hide(frag1);
                        break;

                }

                qq.commit();

            }
        });
    }
}

//Frag1
public class Frag1 extends BaseFragment {

    private TabLayout tab;
    private ViewPager viewpager;
    private ArrayList<String> tabs;
    private  ArrayList<New> newData=null;
    private ArrayList<String> tabss;


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

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

    }

    @Override
    protected void initData() {


      //判断网络
        boolean netWork = NetWorks.isNetworkConnected(getActivity());

      if(netWork){
          getServerData();

        }else{
        //获得标题数据

            Toast.makeText(getActivity(), "没有网络", Toast.LENGTH_SHORT).show();
         Dao dao = new Dao(getActivity());
          Cursor query = dao.query("person", null, null, null, null, null, null);
           //创建新集合
          newData =new ArrayList<>();


          if(query.moveToFirst()){
              do{

                  String news_id = query.getString(query.getColumnIndex("news_id"));
                  String news_title = query.getString(query.getColumnIndex("news_title"));
                  String pic_url = query.getString(query.getColumnIndex("pic_url"));
                   newData.add(new New(news_id,news_title,pic_url));
               }while(query.moveToNext());
          }
          //关闭游标
          query.close();
          tabss = new ArrayList<String>();
          //获取标签数据

          for (int i=0;i<newData.size();i++){
              tabss.add(newData.get(i).getNews_id());
          }

          //设置横向滑动模式
          tab.setTabMode(TabLayout.MODE_SCROLLABLE);

          //适配器
          viewpager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
              @Override
              public Fragment getItem(int i) {
                  ChildFragment childFragment = new ChildFragment();
                  //传标题角标
                  Bundle bundle = new Bundle();
                  bundle.putInt("i",i);
                  childFragment.setArguments(bundle);

                  return childFragment;
              }

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


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

          //关联
          tab.setupWithViewPager(viewpager);



      }


    }


    //默认获取标签数据
    private void getServerData() {
        MyAsyncTask task = new MyAsyncTask();
        task.execute();


    }

    class MyAsyncTask extends AsyncTask<String, Integer, String> {



        @Override
        protected String doInBackground(String... strings) {

            //http://api.expoon.com/AppNews/getNewsList/type/1/p/1


            String path = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
            String json = NetWorks.getJson(path);
            return json;
        }

        @Override
        protected void onPostExecute(String s) {
            Gson gson = new Gson();
            Json json = gson.fromJson(s, Json.class);
            List<Json.DataBean> data = json.getData();
            //创建tabs标题集合
            tabs = new ArrayList<>();
            //遍历添加标题的id
            for (int i = 0; i < data.size(); i++) {
                String news_id = data.get(i).getNews_id();
                //标签数据
                tabs.add(news_id);
            }
            //设置横向滑动模式
            tab.setTabMode(TabLayout.MODE_SCROLLABLE);

          //适配器
          viewpager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
             //动态创建Fragment
              @Override
              public Fragment getItem(int i) {
                  ChildFragment childFragment = new ChildFragment();
                    //传标题角标
                  Bundle bundle = new Bundle();
                  bundle.putInt("i",i);
                  childFragment.setArguments(bundle);

                  return childFragment;
              }
			//获得标题的数量
              @Override
              public int getCount() {
                  return tabs.size();
              }

			//获得标题
              @Nullable
              @Override
              public CharSequence getPageTitle(int position) {
                  return tabs.get(position);
              }
          });

            //关联
            tab.setupWithViewPager(viewpager);
      }
    }
}


//ChildFragment
public class ChildFragment extends BaseFragment {

    //http://api.expoon.com/AppNews/getNewsList/type/1/p/" + page
    //  private PullToRefreshListView plistview;
    private int type = 1;
    private int page = 1;
    private List<Json.DataBean> data;
    private Handler handler = new Handler();

    private ArrayList<Json.DataBean> list=null;
    private PullToRefreshListView plistview;
    private boolean netWork;



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

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

        //获得角标
        Bundle arguments = getArguments();
        int i = arguments.getInt("i");
             i=i%3;
        type=type+i;


    }

    @Override
    protected void initData() {

        //判断网络
        netWork = NetWorks.isNetworkConnected(getActivity());

        //设置模式
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        //设置监刷新监听 2
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                if(netWork==true){
                    page = 1;
                    getServerData();
                }

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

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

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

                if(netWork==true){
                    page++;
                    getServerData();
                }

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

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

       if(netWork==true){
           getServerData();
           Toast.makeText(getActivity(), "有网", Toast.LENGTH_SHORT).show();
        }else{
         Dao dao = new Dao(getActivity());
            //
            Toast.makeText(getActivity(), "没网", Toast.LENGTH_SHORT).show();
           Cursor query = dao.query("person", null, null, null, null, null, null);
           //创建新集合
           ArrayList<Json.DataBean> newData = new ArrayList<>();
           Json.DataBean dataBean = new Json.DataBean();
           if(query.moveToFirst()){
                    do{
                        String news_id = query.getString(query.getColumnIndex("news_id"));
                        String news_title = query.getString(query.getColumnIndex("news_title"));
                        String pic_url = query.getString(query.getColumnIndex("pic_url"));
                        newData.add(new Json.DataBean(news_id,news_title,pic_url));
                   }while(query.moveToNext());
           }
           //关闭游标
           query.close();

               //设置适配器
               MyPlistveiwAdapter myPlistveiwAdapter = new MyPlistveiwAdapter(getActivity(), newData);
               plistview.setAdapter(myPlistveiwAdapter);


       }




    }


    //默认获取标签数据
    private void getServerData() {
        MyAsyncTask task = new MyAsyncTask();
        task.execute();


    }

    private class MyAsyncTask extends AsyncTask<String, Integer, String> {




        @Override
        protected String doInBackground(String... strings) {

            //http://api.expoon.com/AppNews/getNewsList/type/1/p/1


            String path = "http://api.expoon.com/AppNews/getNewsList/type/"+type+"/p/" + page;
            String json = NetWorks.getJson(path);

            return json;
        }

        @Override
        protected void onPostExecute(String s) {
            Gson gson = new Gson();
            Json json = gson.fromJson(s, Json.class);
            data = json.getData();
            Dao dao = new Dao(getActivity());
          //  dao.delete("person",null,null);
            //创建新集合
            //private List<Json.DataBean> data;

            if (page == 1) {
                list = new ArrayList<>();

             dao.delete("person",null,null);

                //当page==1时做缓存     //从对象中获取数据存入ContentValues
                //便利集合获得对象
                for (int i=0;i<data.size();i++){

                    ContentValues values = new ContentValues();
                    values.put("news_id",data.get(i).getNews_id());
                    values.put("news_title",data.get(i).getNews_title());
                    values.put("pic_url",data.get(i).getPic_url());
                    dao.add("person",null,values);

                }




            }

            list.addAll(data);

          //  plistview.setSelection(list.size() - 19);

            //设置适配器
            MyPlistveiwAdapter myPlistveiwAdapter = new MyPlistveiwAdapter(getActivity(), list);
            plistview.setAdapter(myPlistveiwAdapter);

            //显示新数据
            plistview.setSelection(list.size()-19);

        }
    }


}


//数据库
public class MySqlite extends SQLiteOpenHelper {


 public MySqlite( Context context) {
        super(context, "bw.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        //写sql
        db.execSQL("create table person(id integer primary key AUTOINCREMENT,news_id varchar(50),news_title varchar(50),pic_url varchar(50))");

    }

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

}

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 long delete(String table, String whereClause, String[] whereArgs){
        return db.delete(table,whereClause,whereArgs);
    }

    //改
    public long update(String table, ContentValues values, String whereClause, String[] whereArgs){
        return db.update(table,values,whereClause,whereArgs);
    }

    //查
    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 class NetWorks {
/*
    public static boolean isNetWork(Context context){
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        if(info!=null){
            info.isAvailable();  没有retun
        }
        return false;
    }*/

   public static boolean isNetworkConnected(Context context) {
        //获取网络连接状态管理器
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        //得到网络信息
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {

            return info.isAvailable();
        }

        return false;


    }


    public static String getJson(String path){
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(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();
            Log.i("xxx", e.toString());
        }
        return null;
    }



}




















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