Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.gmd.referenceapplication;
- import android.app.ListActivity;
- import android.app.SearchManager;
- import android.content.Context;
- import android.content.Intent;
- import android.database.Cursor;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.support.v7.widget.SearchView;
- import android.support.v7.widget.Toolbar;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuInflater;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ListView;
- import android.widget.SimpleCursorAdapter;
- import android.widget.TextView;
- import android.widget.Toast;
- public class SearchableActivity extends AppCompatActivity {
- DatabaseTable db= new DatabaseTable(this);
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_searchable);
- //creates toolbar
- Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
- setSupportActionBar(myToolbar);
- // get the intent sent when user searches from search widget, verify the action and extract what is typed in
- Intent intent = getIntent();
- handleIntent(intent);
- }
- //creates menu
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.overflow, menu);
- SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
- searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
- @Override
- public boolean onQueryTextSubmit(String query) {
- //search button is pressed
- Cursor c=db.getWordMatches(query,null);
- doSearch(c);
- Log.e("searchable activity","text submitted");
- return true;
- }
- @Override
- public boolean onQueryTextChange(String newText) {
- // User changed the text
- Cursor c=db.getWordMatches(newText,null);
- doSearch(c);
- Log.e("searchable activity ", "haha losing will to live");
- return true;
- }
- });
- SearchManager searchManager =
- (SearchManager) getSystemService(Context.SEARCH_SERVICE);
- searchView =
- (SearchView) menu.findItem(R.id.search).getActionView();
- searchView.setSearchableInfo(
- searchManager.getSearchableInfo(getComponentName()));
- return true;
- }
- public void onNewIntent(Intent intent) {
- setIntent(intent);
- handleIntent(intent);
- }
- private void handleIntent(Intent intent) {
- if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
- String query = intent.getStringExtra(SearchManager.QUERY);
- Cursor c = db.getWordMatches(query, null);
- doSearch(c);
- Log.e("Search Operation", "Database searched");
- //still need to process Cursor and display results
- }
- }
- public void onListItemClick(ListView l,
- View v, int position, long id) {
- // call detail activity for clicked entry
- }
- private void doSearch(Cursor query) {
- // get a Cursor, prepare the ListAdapter
- // and set it
- Cursor c = query;
- startManagingCursor(c);
- ListView sl =(ListView)findViewById(android.R.id.list);
- String[] from = new String[] {"QUANTITY", "_id"};
- int[] to = new int[] {android.R.id.text1};
- SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, from, to);
- sl.setAdapter(cursorAdapter);
- Log.e("doSearch method:", "has been called");
- sl.setOnItemClickListener(
- new AdapterView.OnItemClickListener() {
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id) {
- // When clicked, show a toast with the TextView text
- Log.e("doSearch method:", "Answer: " + ((TextView) view).getText());
- }
- });
- }
- //manages activity bar
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.constants:
- startActivity(new Intent(this, FundamentalPhysicalConstants.class));
- return true;
- case R.id.joes_rules:
- //go to rules
- //startActivity(new Intent(MainActivity.this, ExampleListView.class));
- return true;
- case R.id.home:
- //Go back to the home screen
- startActivity(new Intent(this, MainActivity.class));
- return true;
- case R.id.search:
- //open search
- //startActivity(new Intent(this, SearchableActivity.class));
- return true;
- case R.id.links:
- //go to referencelinks
- startActivity(new Intent(this, ReferenceLinks.class));
- return true;
- case R.id.base_units:
- //go to baseunits
- startActivity(new Intent(this, SIBaseUnits.class));
- return true;
- default:
- // If we got here, the user's action was not recognized.
- // Invoke the superclass to handle it.
- return super.onOptionsItemSelected(item);
- }
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context="com.gmd.referenceapplication.SearchableActivity">
- <android.support.v7.widget.Toolbar
- android:id="@+id/my_toolbar"
- android:layout_width="match_parent"
- android:layout_height="?attr/actionBarSize"
- android:background="?attr/colorPrimary"
- android:elevation="4dp"
- android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
- app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
- />
- <ListView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@id/android:list" />
- </RelativeLayout>
- package com.gmd.referenceapplication;
- import android.content.ContentValues;
- import android.content.Context;
- import android.content.res.Resources;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.database.sqlite.SQLiteQueryBuilder;
- import android.text.TextUtils;
- import android.util.Log;
- import com.gmd.referenceapplication.R;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- /**
- * Created by gmd on 6/8/2016.
- */
- public class DatabaseTable {
- public static final String TAG = "ConstantDatabase";
- //the columns included in the table
- public static final String COL_QUANTITY = "QUANTIY";
- public static final String COL_VALUE = "VALUE";
- public static final String COL_UNCERTAINTY = "UNCERTAINTY";
- public static final String COL_UNIT = "UNIT";
- public static final String _id = "_id";
- private static final String DATABASE_NAME = "CONSTANTS";
- 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 (" +_id+ ", "+
- COL_QUANTITY + ", " +
- COL_VALUE + "," +
- COL_UNCERTAINTY + "," +
- COL_UNIT + ")";
- public DatabaseOpenHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- Log.e("Database Operation", "DatabaseOpenHelper constructor called");
- mHelperContext = context;
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- mDatabase = db;
- mDatabase.execSQL(FTS_TABLE_CREATE);
- Log.e("Database Operation", "Constants Table Created ...");
- loadConstants();
- }
- @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);
- }
- public SQLiteDatabase getmDatabase(){
- return mDatabase;
- }
- // populating the virtual table with a string reading code
- private void loadConstants() {
- new Thread(new Runnable() {
- public void run() {
- try {
- loadConstantss();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }).start();
- Log.e("Loading", "Constants Table Populated ...");
- }
- private void loadConstantss() throws IOException {
- final Resources resources = mHelperContext.getResources();
- InputStream inputStream = resources.openRawResource(R.raw.txt);
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- try {
- String line;
- while ((line = reader.readLine()) != null) {
- String[] strings = TextUtils.split(line, ",");
- if (strings.length < 4) continue;
- long id = addConstant(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim());
- if (id < 0) {
- Log.e(TAG, "unable to add word: " + strings[0].trim());
- }
- }
- } finally {
- reader.close();
- }
- }
- public long addConstant(String quantity, String value, String uncertainty, String unit) {
- ContentValues initialValues = new ContentValues();
- initialValues.put(COL_QUANTITY, quantity);
- initialValues.put(COL_VALUE, value);
- initialValues.put(COL_UNCERTAINTY, uncertainty);
- initialValues.put(COL_UNIT, unit);
- return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
- }
- //database openhelper ends
- }
- public Cursor getWordMatches(String query, String[] columns) {
- String selection = COL_QUANTITY + " MATCH ?";
- String[] selectionArgs = new String[] {query+"*"};
- return query(selection, selectionArgs, columns);
- }
- public 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;
- }
- public Cursor getAllTitles()
- {
- return mDatabaseOpenHelper.getmDatabase().query(FTS_VIRTUAL_TABLE, new String[] {
- COL_QUANTITY,
- COL_UNCERTAINTY,
- COL_UNIT,
- COL_VALUE},
- null,
- null,
- null,
- null,
- null);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement