簡體   English   中英

如何使用sqlite數據庫存儲獲取數據和檢索

[英]How to use sqlite database to store fetch data and retrieve

我使用在線服務器/管理面板構建了一個電視應用程序。我想將獲取的數據從服務器保存到應用程序內存中。這意味着,如果無法使用互聯網,則該應用程序會顯示從sqlite數據庫檢索到的舊的獲取數據。請幫助我完成此操作我已經創建了離線數據庫文件,但是我不知道該怎么做。我正在發布活動,片段和離線數據庫的代碼。 請幫助我配置我的問題。 提前一束謝謝... !!!

 public class ActivityDetailCategory extends AppCompatActivity { private RecyclerView recyclerView; private AdapterChannel adapterChannel; private SwipeRefreshLayout swipeRefreshLayout; private Call<CallbackDetailCategory> callbackCall = null; private int post_total = 0; private int failed_page = 0; private Category category; private InterstitialAd interstitialAd; int counter = 1; private AdView adView; View view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_category_details); view = findViewById(android.R.id.content); if (Config.ENABLE_RTL_MODE) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); } } else { Log.d("Log", "Working in Normal Mode, RTL Mode is Disabled"); } loadBannerAd(); loadInterstitialAd(); category = (Category) getIntent().getSerializableExtra(Constant.EXTRA_OBJC); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout); swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); //set data and list adapter adapterChannel = new AdapterChannel(this, recyclerView, new ArrayList<Channel>()); recyclerView.setAdapter(adapterChannel); // on item list clicked adapterChannel.setOnItemClickListener(new AdapterChannel.OnItemClickListener() { @Override public void onItemClick(View v, Channel obj, int position) { Intent intent = new Intent(getApplicationContext(), ActivityDetailChannel.class); intent.putExtra(Constant.KEY_CHANNEL_CATEGORY, obj.category_name); intent.putExtra(Constant.KEY_CHANNEL_ID, obj.channel_id); intent.putExtra(Constant.KEY_CHANNEL_NAME, obj.channel_name); intent.putExtra(Constant.KEY_CHANNEL_IMAGE, obj.channel_image); intent.putExtra(Constant.KEY_CHANNEL_URL, obj.channel_url); intent.putExtra(Constant.KEY_CHANNEL_DESCRIPTION, obj.channel_description); startActivity(intent); showInterstitialAd(); } }); // detect when scroll reach bottom adapterChannel.setOnLoadMoreListener(new AdapterChannel.OnLoadMoreListener() { @Override public void onLoadMore(int current_page) { if (post_total > adapterChannel.getItemCount() && current_page != 0) { int next_page = current_page + 1; requestAction(next_page); } else { adapterChannel.setLoaded(); } } }); // on swipe list swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (callbackCall != null && callbackCall.isExecuted()) { callbackCall.cancel(); } adapterChannel.resetListData(); requestAction(1); } }); requestAction(1); setupToolbar(); } public void setupToolbar() { final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setTitle(category.category_name); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.search: Intent intent = new Intent(getApplicationContext(), ActivitySearch.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(menuItem); } } private void displayApiResult(final List<Channel> channels) { adapterChannel.insertData(channels); swipeProgress(false); if (channels.size() == 0) { showNoItemView(true); } } private void requestPostApi(final int page_no) { ApiInterface apiInterface = RestAdapter.createAPI(); callbackCall = apiInterface.getCategoryDetailsByPage(category.cid, page_no, Config.LOAD_MORE); callbackCall.enqueue(new Callback<CallbackDetailCategory>() { @Override public void onResponse(Call<CallbackDetailCategory> call, Response<CallbackDetailCategory> response) { CallbackDetailCategory resp = response.body(); if (resp != null && resp.status.equals("ok")) { post_total = resp.count_total; displayApiResult(resp.posts); } else { onFailRequest(page_no); } } @Override public void onFailure(Call<CallbackDetailCategory> call, Throwable t) { if (!call.isCanceled()) onFailRequest(page_no); } }); } private void onFailRequest(int page_no) { failed_page = page_no; adapterChannel.setLoaded(); swipeProgress(false); if (NetworkCheck.isConnect(getApplicationContext())) { showFailedView(true, getString(R.string.failed_text)); } else { showFailedView(true, getString(R.string.no_internet_text)); } } private void requestAction(final int page_no) { showFailedView(false, ""); showNoItemView(false); if (page_no == 1) { swipeProgress(true); } else { adapterChannel.setLoading(); } new Handler().postDelayed(new Runnable() { @Override public void run() { requestPostApi(page_no); } }, Constant.DELAY_TIME); } private void showFailedView(boolean show, String message) { View view = (View) findViewById(R.id.lyt_failed); ((TextView) findViewById(R.id.failed_message)).setText(message); if (show) { recyclerView.setVisibility(View.GONE); view.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); view.setVisibility(View.GONE); } ((Button) findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { requestAction(failed_page); } }); } private void showNoItemView(boolean show) { View view = (View) findViewById(R.id.lyt_no_item); ((TextView) findViewById(R.id.no_item_message)).setText(R.string.no_post_found); if (show) { recyclerView.setVisibility(View.GONE); view.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); view.setVisibility(View.GONE); } } private void swipeProgress(final boolean show) { if (!show) { swipeRefreshLayout.setRefreshing(show); return; } swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(show); } }); } @Override public void onDestroy() { super.onDestroy(); swipeProgress(false); if (callbackCall != null && callbackCall.isExecuted()) { callbackCall.cancel(); } } public void loadBannerAd() { if (Config.ENABLE_ADMOB_BANNER_ADS) { MobileAds.initialize(getApplicationContext(), getResources().getString(R.string.admob_app_id)); adView = (AdView) findViewById(R.id.adView); adView.loadAd(new AdRequest.Builder().build()); adView.setAdListener(new AdListener() { @Override public void onAdClosed() { } @Override public void onAdFailedToLoad(int error) { adView.setVisibility(View.GONE); } @Override public void onAdLeftApplication() { } @Override public void onAdOpened() { } @Override public void onAdLoaded() { adView.setVisibility(View.VISIBLE); } }); } else { Log.d("AdMob", "AdMob Banner is Disabled"); } } private void loadInterstitialAd() { if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) { interstitialAd = new InterstitialAd(getApplicationContext()); interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id)); interstitialAd.loadAd(new AdRequest.Builder().build()); interstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { interstitialAd.loadAd(new AdRequest.Builder().build()); } }); } else { Log.d("AdMob", "AdMob Interstitial is Disabled"); } } private void showInterstitialAd() { if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) { if (interstitialAd != null && interstitialAd.isLoaded()) { if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) { interstitialAd.show(); counter = 1; } else { counter++; } } else { Log.d("AdMob", "Interstitial Ad is Disabled"); } } else { Log.d("AdMob", "AdMob Interstitial is Disabled"); } } } 

 public class FragmentCategory extends Fragment { private View root_view, parent_view; private RecyclerView recyclerView; private SwipeRefreshLayout swipeRefreshLayout; private AdapterCategory adapterCategory; public static final String EXTRA_OBJC = "key.EXTRA_OBJC"; private Call<CallbackCategories> callbackCall = null; private StaggeredGridLayoutManager gaggeredGridLayoutManager; DatabaseHandlerFavorite databaseHandler; private InterstitialAd interstitialAd; private Offlinedatabase databaseHelper; int counter = 1; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root_view = inflater.inflate(R.layout.fragment_category, null); parent_view = getActivity().findViewById(R.id.main_content); databaseHelper = new Offlinedatabase(getActivity()); loadInterstitialAd(); swipeRefreshLayout = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category); swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red); recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory); recyclerView.setHasFixedSize(true); gaggeredGridLayoutManager = new StaggeredGridLayoutManager(1, 1); recyclerView.setLayoutManager(gaggeredGridLayoutManager); //set data and list adapter adapterCategory = new AdapterCategory(getActivity(), new ArrayList<Category>()); recyclerView.setAdapter(adapterCategory); // on item list clicked adapterCategory.setOnItemClickListener(new AdapterCategory.OnItemClickListener() { @Override public void onItemClick(View v, Category obj, int position) { Intent intent = new Intent(getActivity(), ActivityDetailCategory.class); intent.putExtra(EXTRA_OBJC, obj); startActivity(intent); showInterstitialAd(); } }); // on swipe list swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { adapterCategory.resetListData(); requestAction(); } }); requestAction(); return root_view; } private void displayApiResult(final List<Category> categories) { adapterCategory.setListData(categories); swipeProgress(false); if (categories.size() == 0) { showNoItemView(true); } } private void requestCategoriesApi() { ApiInterface apiInterface = RestAdapter.createAPI(); callbackCall = apiInterface.getAllCategories(); callbackCall.enqueue(new Callback<CallbackCategories>() { @Override public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) { CallbackCategories resp = response.body(); if (resp != null && resp.status.equals("ok")) { displayApiResult(resp.categories); } else { onFailRequest(); } } @Override public void onFailure(Call<CallbackCategories> call, Throwable t) { if (!call.isCanceled()) onFailRequest(); } }); } private void onFailRequest() { swipeProgress(false); if (NetworkCheck.isConnect(getActivity())) { showFailedView(true, getString(R.string.failed_text)); } else { showFailedView(true, getString(R.string.no_internet_text)); } } private void requestAction() { showFailedView(false, ""); swipeProgress(true); showNoItemView(false); new Handler().postDelayed(new Runnable() { @Override public void run() { requestCategoriesApi(); } }, Constant.DELAY_TIME); } @Override public void onDestroy() { super.onDestroy(); swipeProgress(false); if(callbackCall != null && callbackCall.isExecuted()){ callbackCall.cancel(); } } private void showFailedView(boolean flag, String message) { View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category); ((TextView) root_view.findViewById(R.id.failed_message)).setText(message); if (flag) { recyclerView.setVisibility(View.GONE); lyt_failed.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); lyt_failed.setVisibility(View.GONE); } ((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { requestAction(); } }); } private void showNoItemView(boolean show) { View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category); ((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category_found); if (show) { recyclerView.setVisibility(View.GONE); lyt_no_item.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); lyt_no_item.setVisibility(View.GONE); } } private void swipeProgress(final boolean show) { if (!show) { swipeRefreshLayout.setRefreshing(show); return; } swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(show); } }); } private int dpToPx(int dp) { Resources r = getResources(); return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics())); } private void loadInterstitialAd() { if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) { interstitialAd = new InterstitialAd(getActivity()); interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id)); interstitialAd.loadAd(new AdRequest.Builder().build()); interstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { interstitialAd.loadAd(new AdRequest.Builder().build()); } }); } else { Log.d("AdMob", "AdMob Interstitial is Disabled"); } } private void showInterstitialAd() { if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) { if (interstitialAd != null && interstitialAd.isLoaded()) { if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) { interstitialAd.show(); counter = 1; } else { counter++; } } else { Log.d("AdMob", "Interstitial Ad is Disabled"); } } else { Log.d("AdMob", "AdMob Interstitial is Disabled"); } }} 

 public class Offlinedatabase extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "db_channel_favorite"; private static final String TABLE_NAME = "tbl_channel_favorite"; private static final String KEY_ID = "id"; private static final String KEY_CAT_NAME = "CAT_NAME"; private static final String KEY_CHANNEL_ID = "channel_id"; private static final String KEY_CHANNEL_NAME = "channel_name"; private static final String KEY_CHANNEL_IMAGE = "channel_image"; private static final String KEY_CHANNEL_URL = "channel_url"; private static final String KEY_CHANNEL_DESCRIPTION = "channel_description"; public Offlinedatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } //Create tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE_CONTACTS="CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_CAT_NAME + " TEXT," + KEY_CHANNEL_ID + " TEXT," + KEY_CHANNEL_NAME + " TEXT," + KEY_CHANNEL_IMAGE + " TEXT," + KEY_CHANNEL_URL + " TEXT," + KEY_CHANNEL_DESCRIPTION + " TEXT" + ")"; db.execSQL(CREATE_TABLE_CONTACTS); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // Create tables again onCreate(db); } //Insert values to the table contacts public void addtodatabase(Channel pj){ SQLiteDatabase db = this.getReadableDatabase(); ContentValues values=new ContentValues(); values.put(KEY_CAT_NAME, pj.getCategory_name()); values.put(KEY_CHANNEL_ID, pj.getChannel_id()); values.put(KEY_CHANNEL_NAME, pj.getChannel_name()); values.put(KEY_CHANNEL_IMAGE, pj.getChannel_image()); values.put(KEY_CHANNEL_URL, pj.getChannel_url()); values.put(KEY_CHANNEL_DESCRIPTION, pj.getChannel_description()); db.insert(TABLE_NAME, null, values); db.close(); } } 

如果您使用的是沒有房間支持的Sqlite,請查看此內容Sqlite Android

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM