简体   繁体   English

Android SQLite:调用onCreate方法并传入一个对象

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

I am creating a database for an Android app I am working on. 我正在为我正在使用的Android应用程序创建数据库。 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. 我正在尝试学习如何按照正确的标准进行编码,并且在DbHelper类的onCreate方法中了解到如何创建数据库。 I also read that it is in the onCreate method that you should populate your database with data. 我还读到,应该在onCreate方法中用数据填充数据库。 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? 如果是这样,如何将对象传递给onCreate方法,以便可以遍历该对象并填充数据库?

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()填充数据。 onCreate() is just used to create database and tables. onCreate()仅用于创建数据库和表。

My thought was to do something like this. 我的想法是要做这样的事情。 DbHelper.onCreate(Food myFoodObj); DbHelper.onCreate(Food myFoodObj);

This is wrong, you don't need to call onCreate(). 这是错误的,您不需要调用onCreate()。 onCreate() will get called itself when you just reference an instance of the class in which you are using the Database class. 当您仅引用使用数据库类的类的实例时, onCreate()会被调用。

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 dbAdapter =新的DBAdapter(this); dbAdapter.open(); dbAdapter.open(); //If any queries write here dbadapter.close(); //如果有任何查询,请在此处写dbadapter.close();

And u can follow this tutorial 你可以按照本教程

http://www.vogella.de/articles/AndroidSQLite/article.html 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.. SQLiteOpenHelper中的onCreate方法用于创建数据库...,我认为用onCreate方法填充数据库没有用。如user1203673所说。您可以将这部分代码添加到DBAdapter类中以填充数据库。

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);" 并从您的活动中将其称为“ 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. 我创建了一个DataLyaer类,该类可与DbHelper一起使用,如下所示。

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。

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. 问题是我不知道如何在onCreate()方法甚至我的DbHelper类中添加这些东西。 I guess I can't believe anyone who posts something online. 我想我不敢相信任何在网上发布内容的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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