简体   繁体   中英

How to pass parameter to onOpen() function using SQLiteOpenHelper

I'm trying to create a to do list. For it, I need to store the user's tasks in a database. For that I choose to use SQLiteOpenHelper.

I proceed in this way:

  1. get user input
  2. Create a database using getWritableDatabase() + onCreate() function
  3. Store user's input inside database -----> Don't know to do that.

     String task = String.valueOf(taskEditText.getText()); DatabaseHandler access = new DatabaseHandler(getApplication()); access.getWritableDatabase(); 

Creation of the database (The function is @Override but can't formated it properly)

public class DatabaseHandler extends SQLiteOpenHelper {

   public void onCreate(SQLiteDatabase db) {
         Log.d(TAG, "===Inside onCreate from DatabaseHandler===");
         String database_table = "CREATE TABLE task(ID INT NOT NULL, TASK CHAR(25), STATE CHAR(25))";
         db.execSQL(database_table);
     }
}

As you can see, I get the user's input using .getText() function. Then I launche the onCreate() function using .getWritableDatabase() And finally, the onOpen(SQLiteDatabase db) is automatically call when the database is open. However I can't modify the prototype of the function and even if I could, I don't how can I pass argument to it. (assuming it's possible).

So I would like to know how can I pass argument to onOpen() function for add user's input to my database ?

EDIT:

My original question was to know how could I pass argument to onCreate() function. But I realize that I wanted to pass to onOpen() function instead of onCreate().

Thanks

So I would like to know how can I pass argument to onCreate() function for add user's input to my database ?

You don't. You use the SQLiteDatabase returned by getWritableDatabase() to add your user input to the database.

Also, please do database I/O on a background thread; your current code is doing this on the main application thread, freezing your UI while that I/O is going on.

Both of these topics are covered in any decent book or course on Android app development.

You don't pass user input to onOpen . You add it to the table in the database that you created in onCreate . You would then use:

ContentValues values = new ContentValues()
values.put(COLUMN_TASK, task);
// Add any more columns here

access.getWritableDatabase().insert(TABLE_NAME, null, values);

See here for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM