简体   繁体   中英

Android SQLite: Calling the onCreate Method and passing in an Object

I am creating a database for an Android app I am working on. I am trying to learn how to code following the correct standards and I read that in the onCreate method of the DbHelper class is where you database gets created. I also read that it is in the onCreate method that you should populate your database with data. Is this correct? And if so how do I pass an object to the onCreate method so I can loop through it and populate the database?

public class DbHelper extends SQLiteOpenHelper 
{
private static String DATABASE_NAME = "FodoSubstitutes.db";
private static String FOOD_TABLE = "Food";

//Creates the database with db name and calls onCreate(). 
public DbHelper(Context context) 
{
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) 
{
    //System.out.println("in onCreate");
    //assocID   food    healthierFood category  description count submittedBy
    String sql = "CREATE TABLE IF NOT EXISTS " + FOOD_TABLE +
                "(Food_ID integer primary key, " + 
                "Food_Name string not null, " +
                "Food_Aliases string, " + 
                "Hints string, " +
                "Category string, " + 
                "Subcategory string, " +
                "Description string, " + 
                "Submission_ID int, " +
                "Comment_ID int, " + 
                "Count int); ";
   db.execSQL(sql);

}
}

My thought was to do something like this.
DbHelper.onCreate(Food myFoodObj);

but that will not work. Any thoughts? It is has got to be something simple and obvious that I am overlooking.

No it is not necessary to populate your database with data inside onCreate() . onCreate() is just used to create database and tables.

My thought was to do something like this. DbHelper.onCreate(Food myFoodObj);

This is wrong, you don't need to call onCreate(). onCreate() will get called itself when you just reference an instance of the class in which you are using the Database class.

DbHelper dbhelper = new DbHelper(this);
public class DBAdapter {

 String sql = "CREATE TABLE IF NOT EXISTS " + FOOD_TABLE +
                "(Food_ID integer primary key, " + 
                "Food_Name string not null, " +
                "Food_Aliases string, " + 
                "Hints string, " +
                "Category string, " + 
                "Subcategory string, " +
                "Description string, " + 
                "Submission_ID int, " +
                "Comment_ID int, " + 
                "Count int); ";
private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter (Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);

        }

        public void onCreate(SQLiteDatabase db) {
            db.execSQL(sql );

        }

        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("DELETE FROM" + DATABASE_USERSTATUS);
            onCreate(db);
        }
    }

    // ---opens the database---
    public SecureSMSDBAdapterAES open() throws SQLException {
        db = DBHelper.getWritableDatabase();

        return this;
    }

    // ---closes the database---
    public void close() {
        DBHelper.close();
    }

    // ---insert values into the database---

    public long insertDataByQuery(String q) {

        db.execSQL(q);

        return 0;
    }
}

And in the class where u want to instantiate the database

DBAdapter dbAdapter = new DBAdapter(this); dbAdapter.open(); //If any queries write here dbadapter.close();

And u can follow this tutorial

http://www.vogella.de/articles/AndroidSQLite/article.html

The onCreate method in SQLiteOpenHelper is for creating a database... and i think it is not useful to populate your database in onCreate method.. as user1203673 said..you can add this part of code to DBAdapter class to populate database..

public void createcustom(String category,String subcategory){
ContentValues values = new ContentValues(2);
values.put(Category string,category);
values.put(Subcategory string,subcategory);
long insertId = customdb.insert(sqliteplaylist.LIBRARY, null,values);

} 

and call this from your activity as "DBAdapter.createcustom(foodname,foodcategory);"

Here is what I ended up doing. I created a DataLyaer Class that works witht he DbHelper that looks like this.

public class DataLayer 
{

private DbHelper _dbHelper;

public DataLayer(Context c) 
{
    _dbHelper = new DbHelper(c);
}


public void populateMyDB(Table myTables ) 
{
    SQLiteDatabase db = _dbHelper.getWritableDatabase();
    try 
    {
        //do stuff. 

    }
    finally
    {
        if (db != null)
            db.close();
    }

}
}

And then I call my DataLayer by doing this.

DataLayer d = new DataLayer(context);
d.populateMyDB(myFood);

Thanks for the help. The problem was I couldn't figure out how to add this stuff in the onCreate() method or even in my DbHelper class. I guess I can't believe anyone who posts something online.

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