基類抽取http服務(網路判斷)資料庫多條目載入上拉載入下拉重新整理
阿新 • • 發佈:2018-12-10
//BaseActivity public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(initLayout()); initview(); getNews(); } /** * 設定佈局檔案 */ protected abstract int initLayout(); /** * 初始化控制元件 */ protected abstract void initview(); /** * 獲得資料 */ protected abstract void getNews(); }
//主頁面
public class MainActivity extends BaseActivity implements View.OnClickListener { private DrawerLayout dra_layout; private Button btn_1,btn_2,btn_3; private ArrayList<Fragment> fragment; private ViewPager view_pager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //設定監聽 view_pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int i) { return fragment.get(i); } @Override public int getCount() { return fragment.size(); } }); btn_1.setOnClickListener(this); btn_2.setOnClickListener(this); btn_3.setOnClickListener(this); } @Override protected int initLayout() { return R.layout.activity_main; } @Override protected void initview() { //初始化控制元件 dra_layout = findViewById(R.id.drawer_layout); view_pager = findViewById(R.id.view_pager); btn_1 = findViewById(R.id.btn_1); btn_2 = findViewById(R.id.btn_2); btn_3 = findViewById(R.id.btn_3); //建立集合 fragment = new ArrayList<>(); fragment.add(new OneFragment()); fragment.add(new TwoFragment()); fragment.add(new ThreeFragment()); } @Override protected void getNews() { } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_1: view_pager.setCurrentItem(0); break; case R.id.btn_2: view_pager.setCurrentItem(1); break; case R.id.btn_3: view_pager.setCurrentItem(2); break; } } }
//碎片
public abstract class BaseFragment extends Fragment { public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); getDatas(); } abstract void initView(View view); abstract void getDatas(); }
public class OneFragment extends BaseFragment { private static final String TAG = "ConcernFragment"; public static final String NEWS_URL="http://www.xieast.com/api/news/news.php?page="; private int page=1; private boolean isLoadMore= false; private XListView list_view; private ArrayList<News.DataBean> list; private MyAdapter adapter; private NewsDao dao; private static final int FLAG = 123; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case FLAG: String result = (String) msg.obj; Gson gson = new Gson(); News news = gson.fromJson(result, News.class); if (news != null) { ArrayList<News.DataBean> data = (ArrayList<News.DataBean>) news.getData(); if (data != null) { // 新增到資料庫中 int i = dao.insert(data); if (i > 0) { Log.i(TAG, "插入了: " + i + "條資料"); } if (!isLoadMore) { list.clear(); } list.addAll(data); adapter.notifyDataSetChanged(); } } postDelayed(new Runnable() { @Override public void run() { list_view.stopRefresh(); } }, 2000); break; } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view= inflater.inflate(R.layout.fragment_one, container, false); return view; } @Override void initView(View view) { //初始化控制元件 list_view=view.findViewById(R.id.list_view); //建立集合 list=new ArrayList<>(); //建立介面卡 adapter=new MyAdapter(list,getActivity()); list_view.setAdapter(adapter); dao=new NewsDao(getActivity()); //設定上拉載入下拉重新整理 list_view.setPullLoadEnable(true); list_view.setPullRefreshEnable(true); //設定Xlistview監聽事件 list_view.setXListViewListener(new XListView.IXListViewListener() { @Override public void onRefresh() { if (page>1){ page--; }else { Toast.makeText(getActivity(),"給不了親更多資訊了!!!",Toast.LENGTH_LONG).show(); } isLoadMore=false; getDatas(); handler.postDelayed(new Runnable() { @Override public void run() { list_view.stopRefresh(); } },1000); long l = System.currentTimeMillis(); Date date = new Date(l); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); list_view.setRefreshTime(format.format(date)); } @Override public void onLoadMore() { page ++; isLoadMore = true; getDatas(); News news = new News(); ArrayList<News.DataBean> result = (ArrayList<News.DataBean>) news.getData(); if (result == null){ Toast.makeText(getActivity(),"沒有更多的資料了",Toast.LENGTH_SHORT).show(); } handler.postDelayed(new Runnable() { @Override public void run() { list_view.stopLoadMore(); } },1000); } }); } @Override void getDatas() { if (NetworkConnected.isNetworkConnected(getActivity())){ getDataFromHttp(); }else { getDataFromDB(); } } //開啟執行緒請求資料 private void getDataFromHttp() { new AsyncTask<String,Integer,String>(){ @Override protected String doInBackground(String... strings) { String s = HttpUtils.getHttpUrlConnection(strings[0]); Message msg = Message.obtain(); msg.what = FLAG; msg.obj = s; handler.sendMessage(msg); return s; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); News news = gson.fromJson(s, News.class); if (news != null){ ArrayList<News.DataBean> result = (ArrayList<News.DataBean>) news.getData(); if (result != null){ if (!isLoadMore){ list.clear(); } list.addAll(result); adapter.notifyDataSetChanged(); } } } }.execute(NEWS_URL+page); } //從資料庫獲得資料 public void getDataFromDB(){ ArrayList<News.DataBean> dataBeans = dao.queryPage(page); if (dataBeans != null) { if (!isLoadMore) { list.clear(); } list.addAll(dataBeans); adapter.notifyDataSetChanged(); } handler.postDelayed(new Runnable() { @Override public void run() { list_view.stopRefresh(); } }, 2000); } }
//介面卡
public class MyAdapter extends BaseAdapter { private static final int TYPE_ONE_PIC = 0; private static final int TYPE_TWO_PIC = 1; private static final int TYPE_THREE_PIC = 2; private ArrayList<News.DataBean> list; private Context context; public MyAdapter(ArrayList<News.DataBean> list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public int getViewTypeCount() { return 3; } @Override public int getItemViewType(int position) { News.DataBean bean = list.get(position); if (!TextUtils.isEmpty(bean.getThumbnail_pic_s03())) { return TYPE_THREE_PIC; } else if (!TextUtils.isEmpty(bean.getThumbnail_pic_s02())) { return TYPE_TWO_PIC; } else { return TYPE_ONE_PIC; } } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder1 holder1 = null; ViewHolder2 holder2 = null; ViewHolder3 holder3 = null; int type = getItemViewType(position); switch (type) { case TYPE_ONE_PIC: if (convertView == null) { holder1 = new ViewHolder1(); convertView = View.inflate(context, R.layout.item_news_01, null); holder1.txtTitle = convertView.findViewById(R.id.txt_title); holder1.imgLogo1 = convertView.findViewById(R.id.img_logo_01); convertView.setTag(holder1); } else { holder1 = (ViewHolder1) convertView.getTag(); } holder1.txtTitle.setText(list.get(position).getTitle()); ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(), holder1.imgLogo1); break; case TYPE_TWO_PIC: if (convertView == null) { holder2 = new ViewHolder2(); convertView = View.inflate(context, R.layout.item_news_02, null); holder2.txtTitle = convertView.findViewById(R.id.txt_title); holder2.imgLogo1 = convertView.findViewById(R.id.img_logo_01); holder2.imgLogo2 = convertView.findViewById(R.id.img_logo_02); convertView.setTag(holder2); } else { holder2 = (ViewHolder2) convertView.getTag(); } holder2.txtTitle.setText(list.get(position).getTitle()); ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(), holder2.imgLogo1); ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s02(), holder2.imgLogo2); break; case TYPE_THREE_PIC: if (convertView == null) { holder3 = new ViewHolder3(); convertView = View.inflate(context, R.layout.item_news_03, null); holder3.txtTitle = convertView.findViewById(R.id.txt_title); holder3.imgLogo1 = convertView.findViewById(R.id.img_logo_01); holder3.imgLogo2 = convertView.findViewById(R.id.img_logo_02); holder3.imgLogo3 = convertView.findViewById(R.id.img_logo_03); convertView.setTag(holder3); } else { holder3 = (ViewHolder3) convertView.getTag(); } holder3.txtTitle.setText(list.get(position).getTitle()); ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(), holder3.imgLogo1); ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s02(), holder3.imgLogo2); ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s03(), holder3.imgLogo3); break; } return convertView; } class ViewHolder1 { TextView txtTitle; ImageView imgLogo1; } class ViewHolder2 { TextView txtTitle; ImageView imgLogo1; ImageView imgLogo2; } class ViewHolder3 { TextView txtTitle; ImageView imgLogo1; ImageView imgLogo2; ImageView imgLogo3; } }
//http工具類 網路判斷
public class HttpUtils { public static String getHttpUrlConnection(String urlString){ String result = ""; try { URL url = new URL(urlString); //連線 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //優化 //請求型別 connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); //超時時間 connection.setConnectTimeout(3000); connection.connect(); //獲取狀態碼 200 成功 if(connection.getResponseCode() == 200){ InputStream is = connection.getInputStream(); result = getInputStream(is); } } catch (IOException e) { e.printStackTrace(); } return result; } private static String getInputStream(InputStream is) { String result = ""; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int count = -1; byte[] buffer = new byte[1024]; while ((count = is.read(buffer,0,buffer.length)) != -1){ baos.write(buffer,0,count); baos.flush(); } result = baos.toString(); baos.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } return result; } }
public class NetworkConnected { //判斷是否有網路 public static boolean isNetworkConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null) { return mNetworkInfo.isAvailable(); } } return false; } }
//Dao包和
public class NewsDao { private final SQLiteDatabase db; public static final String TABLE_NAME = "news"; public static final String COLUMN_ID = "id"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_DATE = "_date"; public static final String COLUMN_CATEGORY = "category"; public static final String COLUMN_AUTHOR_NAME = "author_name"; public static final String COLUMN_URL = "url"; public static final String COLUMN_THUMBNAIL_01 = "thumbnail_pic_s"; public static final String COLUMN_THUMBNAIL_02 = "thumbnail_pic_s02"; public static final String COLUMN_THUMBNAIL_03 = "thumbnail_pic_s03"; public NewsDao(Context context) { DBHelper helper = new DBHelper(context); db = helper.getWritableDatabase(); } /** * 插入資料 * * @param list * @return */ public int insert(ArrayList<News.DataBean> list) { int count = 0; ContentValues values = new ContentValues(); for (News.DataBean bean : list) { /** * 有這條資料就不作操作,沒有的時候才插入 */ if (!hasId(bean.getUniquekey())) { values.put(COLUMN_ID, bean.getUniquekey()); values.put(COLUMN_TITLE, bean.getTitle()); values.put(COLUMN_DATE, bean.getDate()); values.put(COLUMN_CATEGORY, bean.getCategory()); values.put(COLUMN_AUTHOR_NAME, bean.getAuthor_name()); values.put(COLUMN_URL, bean.getUrl()); values.put(COLUMN_THUMBNAIL_01, TextUtils.isEmpty(bean.getThumbnail_pic_s()) ? "" : bean.getThumbnail_pic_s()); values.put(COLUMN_THUMBNAIL_02, TextUtils.isEmpty(bean.getThumbnail_pic_s02()) ? "" : bean.getThumbnail_pic_s02()); values.put(COLUMN_THUMBNAIL_03, TextUtils.isEmpty(bean.getThumbnail_pic_s03()) ? "" : bean.getThumbnail_pic_s03()); long l = db.insert(TABLE_NAME, null, values); if (l > 0) { count++; } } } return count; } /** * 查詢資料庫中有沒有這條id的資料 * * @param id * @return */ public boolean hasId(String id) { Cursor cursor = db.query(TABLE_NAME, null, COLUMN_ID + "=?", new String[]{id}, null, null, null); if (cursor.moveToNext()) { return true; } return false; } /** * 查詢所有的資料 * * @return */ public ArrayList<News.DataBean> queryAll() { ArrayList<News.DataBean> list = new ArrayList<>(); Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null); while (cursor.moveToNext()) { News.DataBean bean = new News.DataBean(); bean.setUniquekey(cursor.getString(cursor.getColumnIndex(COLUMN_ID))); bean.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_TITLE))); bean.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE))); bean.setAuthor_name(cursor.getString(cursor.getColumnIndex(COLUMN_AUTHOR_NAME))); bean.setCategory(cursor.getString(cursor.getColumnIndex(COLUMN_CATEGORY))); bean.setUrl(cursor.getString(cursor.getColumnIndex(COLUMN_URL))); bean.setThumbnail_pic_s(cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL_01))); bean.setThumbnail_pic_s02(cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL_02))); bean.setThumbnail_pic_s03(cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL_03))); list.add(bean); } return list; } /** * 根據頁數查詢出資料 * @param page * @return */ public ArrayList<News.DataBean> queryPage(int page) { // page=1 ==> 0-29, limit 0, 30 // page=2 ==> 30-59 limit 30, 30 String limit = (page - 1) * 30 + ", 30"; ArrayList<News.DataBean> list = new ArrayList<>(); Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, limit); while (cursor.moveToNext()) { News.DataBean bean = new News.DataBean(); bean.setUniquekey(cursor.getString(cursor.getColumnIndex(COLUMN_ID))); bean.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_TITLE))); bean.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE))); bean.setAuthor_name(cursor.getString(cursor.getColumnIndex(COLUMN_AUTHOR_NAME))); bean.setCategory(cursor.getString(cursor.getColumnIndex(COLUMN_CATEGORY))); bean.setUrl(cursor.getString(cursor.getColumnIndex(COLUMN_URL))); bean.setThumbnail_pic_s(cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL_01))); bean.setThumbnail_pic_s02(cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL_02))); bean.setThumbnail_pic_s03(cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL_03))); list.add(bean); } return list; } }
public class DBHelper extends SQLiteOpenHelper { public static final String DB_NAME = "news.db"; public static final int DB_VERSION = 1; public DBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "create table " + NewsDao.TABLE_NAME + "(" + NewsDao.COLUMN_ID + " text primary key," + NewsDao.COLUMN_TITLE + " text," + NewsDao.COLUMN_DATE + " text," + NewsDao.COLUMN_CATEGORY + " text," + NewsDao.COLUMN_AUTHOR_NAME + " text," + NewsDao.COLUMN_URL + " text," + NewsDao.COLUMN_THUMBNAIL_01 + " text," + NewsDao.COLUMN_THUMBNAIL_02 + " text," + NewsDao.COLUMN_THUMBNAIL_03 + " text)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
//ImageLoader全域性配置
public class MyApplication extends Application { private File file; private DiskCache diskCache; @Override public void onCreate() { super.onCreate(); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File rootSD = Environment.getExternalStorageDirectory(); file = new File(rootSD, "imagefile"); if (!file.exists()){ file.mkdirs(); } } try { diskCache = new LruDiskCache(file, new Md5FileNameGenerator(), 50 * 1024 * 1024); } catch (IOException e) { e.printStackTrace(); } BitmapDisplayer displayer = new RoundedBitmapDisplayer(10); DisplayImageOptions options = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .bitmapConfig(Bitmap.Config.RGB_565) .displayer(displayer) .showImageForEmptyUri(R.mipmap.ic_launcher) .showImageOnFail(R.mipmap.ic_launcher) .showImageOnLoading(R.mipmap.ic_launcher) .build(); ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this) .diskCache(diskCache) .memoryCache(new LruMemoryCache(12*1024*1024)) .threadPoolSize(3) .defaultDisplayImageOptions(options) .build(); ImageLoader.getInstance().init(configuration); } }
//清單檔案
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="bawei.com.activity"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" tools:ignore="ProtectedPermissions" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".BaseActivity"></activity> </application> </manifest>