Anthony Honciano
Anthony Honciano

Reputation: 1677

Android SQLite question

I asked a few questions about SQLite here, and maybe its because I'm not fully understanding how this works. I'm reading two books that are using tutorials and examples, but I'm having a tough time figuring out how I'm going to do this.

What I have going is a user creating a list, they hit a plus button, enter a column name and the list view shows the list they created (the listview is plugged into an ArrayList). I want to take that ArrayList and use the strings to create the table columns.

Now, the examples I've worked with are creating classes that are extending SQLiteOpenHelper and another class that just extends Activity and shows the layout and data.

My questions are:

  1. What calls the class that extends the SQLiteOpenHelper to create the database? Is this run automatically from starting the app? Or do I call it in my activity?

  2. I was planning on building a long string with the ArrayList in a FOR loop so I can create the CREATE TABLE string for its columns. How would I take the ArrayList to the SQLite class? I was thinking of using a bundled Intent, but I'm not sure if that would work (or will it?).

Upvotes: 0

Views: 165

Answers (1)

dmon
dmon

Reputation: 30168

  1. Implementing SQLiteOpenHelper "provides" two main methods for you to override: onCreate and onUpgrade. onCreate will be called automatically the first time that you create an instance of the helper, and only if the database doesn't exist yet. It's in the onCreate where you execute your create statements.

    Then you can use this helper object to get an instance of the database, either a readable or a writable one, depending on what you need: getWritableDatabase and getReadableDatabase. Those methods return a Database object on which you can execute queries.

  2. From here, you can either wrap the helper in a super class or just add your query/insert/remove/update methods to the helper. These will take a readable or writeable instance and, say, insert the List of whatever that you're trying to add. Intents are not necessary here, you will get the Helper/Wrapper instance directly and perform your operations there.

EDIT - how to pass in the arraylist to your SQLiteOpenHelper:

class DatabaseHelper extends SQLiteOpenHelper {
    List columns;
    public AccountsDatabaseHelper(Context context, List columns) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
      this.columns = columns;
    }

    ...
}

Code in the activity:

  ...
  DatabaseHelper helper = new DatabaseHelper(this, myArrayList);
  helper.getWriteableDatabase(); //This will execute the onCreate
  ...      

Upvotes: 2

Related Questions