dimanche 26 juillet 2015

Searching database created in "DB Browser for SQLite"

A little description of what I want my app to do: I want a search widget within the activity (not the action bar), I want to be able to search a database that I will create with a DB browser, I also want the search results to be presented in the same activity (If that is possible).

My database will have 3 columns: item, category, and description. (Do I also need a key_id?).

I have been using http://ift.tt/1iCOrHC as a guideline. I have gotten all the way up to "Search your data" section, which I do not know how to proceed. I have tried googling how to do this, I was able to stumble upon http://ift.tt/19PBhQ1 which showed me how to access the database in an android app. I've also looked at the "Searchable dictionary" example referenced in the android link.

It is my first time doing something of this magnitude so I am slowly beginning to feel overwhelmed. A lot of tutorials I have found online show how to make/update/add/delete a database and entries when the app runs, but is this necessary if I am using a DB browser? A lot of the codes have simple stuff like declaring the columns, but I am unsure if this would be needed in my case. If anyone could provide an overview of the general concept of incorporating a search feature (one that fits my needs above) or a link to a tutorial, that would be appreciated. As it stands now, I have a search activity, a dbHelper class, I will be needed cursors and as far as I know, a class that will be displaying the results? Unless if that stuff is also down under my search activity.

SEARCH:

public class Search extends ActionBarActivity {

private TextView mTextView;
private ListView mListView;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);
        return true;
    }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void toMainMenu(View view) {
    Intent i=new Intent(Search.this,MainMenu.class);
    startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);

    handleIntent(getIntent());
}

@Override
protected 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);
        doSearchQuery(query);
    }
}

public void doSearchQuery(String query){
    //DataBaseHelper myDbHelper = new DataBaseHelper();
    DataBaseHelper myDbHelper = new DataBaseHelper(this);

    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }
    try {
        myDbHelper.openDataBase();
    }catch(SQLException sqle){
        throw sqle;
    }
}

}

I wasn't sure where to put the createDataBase and openDataBase. Should they be outside of doSearchQuery?

dbHELPER:

public class DataBaseHelper extends SQLiteOpenHelper {

//The Android's default system path of your application database.
public static String DB_PATH = "/data/data/com.example.gus.howtorecycle/databases/";
public static String DB_NAME = "RecycleDB.db";

public static int DB_VERSION = 1;
public static String TABLE_NAME = "Recycle_Table";
public static String COL_1 = "Item";
public static String COL_2 = "Category";
public static String COL_3 = "Description";

private SQLiteDatabase myDataBase;

private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 */
public DataBaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * */
public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
    }else{

        //By calling this method and empty database will be created into the default system path
        //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

        //database does't exist yet.

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null;
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException{

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {

    if(myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.

}

Just an attempt to summarize. I have it so that it receives a search query, I have a database, what I need is to create that database in Android, search it (doSearchQuery) using a cursor, and then to be able to display the results.

So if I lost anyone, my head is a bit scrambled. I will be monitoring and answering questions if anyone needs some clarification!

Aucun commentaire:

Enregistrer un commentaire