android-Storing and Searching for Data,Remaining Backward Compatible
There are many ways to store your data, such as in an online database, in a local SQLite database, or even in a text file. It is up to you to decide what is the best solution for your application.
A virtual table behaves similarly to a SQLite table, but reads and writes to an object in memory
via callbacks, instead of to a database file.
> Create an inner class in DatabaseTable
that
extends SQLiteOpenHelper
.
public class DatabaseTable { private static final String TAG = "DictionaryDatabase"; //The columns we'll include in the dictionary table public static final String COL_WORD = "WORD"; public static final String COL_DEFINITION = "DEFINITION"; private static final String DATABASE_NAME = "DICTIONARY"; private static final String FTS_VIRTUAL_TABLE = "FTS"; private static final int DATABASE_VERSION = 1; private final DatabaseOpenHelper mDatabaseOpenHelper; public DatabaseTable(Context context) { mDatabaseOpenHelper = new DatabaseOpenHelper(context); } private static class DatabaseOpenHelper extends SQLiteOpenHelper { private final Context mHelperContext; private SQLiteDatabase mDatabase; private static final String FTS_TABLE_CREATE = "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3 (" + COL_WORD + ", " + COL_DEFINITION + ")"; DatabaseOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mHelperContext = context; } @Override public void onCreate(SQLiteDatabase db) { mDatabase = db; mDatabase.execSQL(FTS_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE); onCreate(db); } } }
Tip: You also might want to set up a callback to notify your UI activity of this thread's completion.
private void loadDictionary() { new Thread(new Runnable() { public void run() { try { loadWords(); } catch (IOException e) { throw new RuntimeException(e); } } }).start(); } private void loadWords() throws IOException { final Resources resources = mHelperContext.getResources(); InputStream inputStream = resources.openRawResource(R.raw.definitions); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { String line; while ((line = reader.readLine()) != null) { String[] strings = TextUtils.split(line, "-"); if (strings.length < 2) continue; long id = addWord(strings[0].trim(), strings[1].trim()); if (id < 0) { Log.e(TAG, "unable to add word: " + strings[0].trim()); } } } finally { reader.close(); } } public long addWord(String word, String definition) { ContentValues initialValues = new ContentValues(); initialValues.put(COL_WORD, word); initialValues.put(COL_DEFINITION, definition); return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues); }
Add the following methods to the DatabaseTable
class to build a SQL statement that searches for the query:
public Cursor getWordMatches(String query, String[] columns) { String selection = COL_WORD + " MATCH ?"; String[] selectionArgs = new String[] {query+"*"}; return query(selection, selectionArgs, columns); } private Cursor query(String selection, String[] selectionArgs, String[] columns) { SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables(FTS_VIRTUAL_TABLE); Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(), columns, selection, selectionArgs, null, null, null); if (cursor == null) { return null; } else if (!cursor.moveToFirst()) { cursor.close(); return null; } return cursor; }Remember that the searchable activity receives the query inside of the
ACTION_SEARCH
intent
as an extra, because of the intent filter that you previously created.SearchView
and
action bar are only available on Android 3.0 and later. To support older platforms, you can fall back to the search dialog. The search dialog is a system provided UI that overlays on top of your application when invoked.
To setup the search dialog, first declare in your manifest that you want to support older devices, but want to target Android 3.0 or later versions. When you do this, your application automatically uses the action bar on Android 3.0 or later and uses the traditional menu system on older devices:
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15" />
Because Android 3.0 and higher devices show the SearchView
in the action bar (as demonstrated
in the first lesson), only versions older than 3.0 call onOptionsItemSelected()
when
the user selects the search menu item.
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.search: onSearchRequested(); return true; default: return false; } }
> At runtime, check the device version to make sure an unsupported use of SearchView
does
not occur on older devices. In our example code, this happens in the onCreateOptionsMenu()
method:
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); } return true; }
相關文章
- error: RPC failed; curl 18 transfer closed with outstanding read data remainingErrorRPCAIREM
- Pytorch中backward()的思考記錄PyTorch
- Oracle 的COMPATIBLE引數Oracle
- 隨筆MySQL:Searching rows for update狀態解析MySql
- Importerror : matplotlib is required for plotting when the default backend “matplotlib“ is backwardImportErrorUI
- 對pytroch中torch.autograd.backward的思考
- PCRE Perl Compatible Regular Expressions LearningExpress
- POJ3187Backward Digit Sums[楊輝三角]Git
- Searching with Deep Learning 深度學習的搜尋應用深度學習
- Create CSS3 Buttons Compatible with All BrowsersCSSS3
- 深度學習論文翻譯解析(十九):Searching for MobileNetV3深度學習
- 【ASM】ORA-15283: ASM operation requires compatible...ASMUI
- 解決CocoaPods could not find compatible versions for pod "React/Core"React
- MPU-410 compatible 驅動解決辦法
- The COMPATIBLE Initialization Parameter and Irreversible Compatibility (119)
- 10G新特性筆記之COMPATIBLE引數筆記
- Data Quality and Data Cleaning
- Export data from a data blockExportBloC
- android TV-Making TV Apps Searchable,Searching within TV AppsAndroidAPP
- 《Object Detection Using ClusteringAlgorithm Adaptive Searching Regions in Aerial Images》論文10問ObjectGoAPT
- 如何在 SAP Spartacus 中編寫 ASM-Compatible 的程式碼ASM
- IE 相容模式 設定 Meta Compatible 和 Iframe 子頁面的關係模式
- ORA-39358: Export dump file version 12.1.0 not compatible with target version 11Export
- 使用X-UA-Compatible來設定IE瀏覽器相容模式瀏覽器模式
- data structureStruct
- jQuery data()jQuery
- Import DataImport
- Oracle 11G安裝報錯"ORA-00401: the value for parameter compatible"Oracle
- Failed ALPN negotiation: Unable to find compatible protocol&&subscriptionExpressions have not been set yetAIGoProtocolExpress
- thinkphp升級後報錯Declaration of thinkappUrl::build() must be compatible with think outeUrl::build():PHPAPPUI
- SharePoint 2007 Full Text Searching PowerShell and CS file content with SharePoint Search
- SAP ECC & APO整合 - Master Data & Transaction Data TransferAST
- DATA GUARD部署模式——DATA GUARD概念和管理模式
- P1118 [USACO06FEB]數字三角形Backward Digit Su…Git
- Suggestion: use a compatible library with a minSdk of at most 16, or increase this project's minSdkProject
- LightDB-指定lightdb_syntax_compatible_type切換不同資料引擎
- 【Data Pump】Data Pump的並行引數原理並行
- 不Root也可以app的/data/data/目錄APP