samedi 23 janvier 2016

Adding data to SQLite

I'm creating my first data enabled app but am struggling with the last part - actually adding and retrieving the data. For now I am only concerned with adding data to the table. Following this tutorial I have created model classes for my tables and a DBHelper class with all my CRUD methods (I can post all these if required but not sure they are necessary to answer this question. Please correct me if I am wrong!). Unfortunately the tutorial ends here and doesn't go into detail on how to pass the data from the UI of the app into the DB.

After some Google searches I have found an example of how to pass some data to these methods but only how to pass one piece of data at a time, so only really useful if my table has just one field - mine has more than one.

For example, if I have a a table for "Todo" tasks, in my dbhelper my create method may be;

public void createTodo(String todoText) {
    ContentValues contentValues = new ContentValues();
    contentValues.put("todo", todoText);
    // Insert into DB
    db.insert("todos", null, contentValues);
}

so from my activity I just need

dao.createTodo(todoTextValue);

For my app I will be adding more than one field at a time, so my create method looks like this;

public long createSite(Site site){
    SQLiteDatabase database = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_SITE_NAME, site.getSiteName());
    values.put(KEY_SITE_LAT, site.getSiteLat());
    values.put(KEY_SITE_LON, site.getSiteLon());
    values.put(KEY_CREATED_AT, site.getSiteCreatedDateTime());

    // Insert Row
    long siteid = database.insert(TABLE_SITES, null, values);

So my question really is how I can pass all the different bits of data to the createSite method.

Aucun commentaire:

Enregistrer un commentaire