java - Android 中的 SQLite OpenDatabase 问题

标签 java android sqlite

我正在使用我需要的 2 个表(user_table 和 prod_table)设置我的数据库类

按照本指南操作: http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android

这看起来不错,但从未说明我如何执行典型的“getConnection()”方法。 例如,我在一个 Activity 中,我想 insertUserRow() 我需要传递 SQLiteOpenConnection 数据库和用户对象。 我在每个 Helper 中创建了一个 Singleton,如下所示:

public class UserEdbHelper extends SQLiteOpenHelper {

    static final String dbName = "edb";
    static final String userTable = "user_table";
    private static UserEdbHelper mInstance = null;

    /* --- user_table columns --- */

    static Context appContext;

    UserEdbHelper(Context context) {
        super(context, dbName, null, 33);
        this.appContext = context;
    }

    public static UserEdbHelper getInstance(Context ctx) {
        if (mInstance == null) {
            mInstance = new UserEdbHelper(ctx.getApplicationContext());
        }
        return mInstance;
    }

我还尝试跟进另一个示例,该示例告诉您执行以下操作:

public class AppCore extends Application{
    // create the 2 helpers that creates the respective tables
    public static UserEdbHelper userHelper; 
    public static ProductEdbHelper productHelper;

    public static void init(Context context )
    {
        // this is supposed to instantiate the helpers or what? what does this do?
        userHelper = new UserEdbHelper(context);
        productHelper = new ProductEdbHelper(context);
    }

}

我脑子里缺少一些东西。

另外,我为每个 Helper 创建了两个类,UserEdbHelper 和 ProductEdbHelper,这是正确的吗?它们中的每一个都创建自己的表,并且有自己的方法。 (基本上与我上面添加的链接结构相同,您可以在那里查看)

其中一个属性是“dbName”,我需要将该属性添加到两个类还是仅添加到一个类?

有点迷失了:(

我很想得到一些帮助,

提前致谢,

马里亚诺。

最佳答案

有人建议我,最好谈论做某事的正确方法,而不是担心所有错误的方法。让我建议一些我认为对您有用的内容,而不是查看您问题中的代码:

public class AppCore extends Application {
    public UserEdbHelper userHelper;
    public ProductEdbHelper productHelper;

    // onCreate and such stuff...

    public SQLiteDatabase getUserDb() {
        if (null == userHelper) { userHelper = new UserEdbHelper(this); }
        return userHelper.getWritableDatabase();
    }

    public SQLiteDatabase getProductDb() {
        if (null == productHelper) { productHelper = new ProductEdbHelper(this); }
        return productHelper.getWritableDatabase();
    }

    // other code

}

我可以引用你的话吗:“我脑子里缺少一些东西”? :-)

关于java - Android 中的 SQLite OpenDatabase 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513080/

相关文章:

java - java.util.concurrent.BlockingQueue 的实现

java - Gson 无法使用自定义序列化程序进行反序列化

android - 在 Android M 上请求麦克风权限

java - 返回并绑定(bind)到 ListView 的 double 被截断

ios - Sqlite:仅在更改行时才替换或更新行

java - 对机器人进行编程以探索网格

java - 如何在 Java 中模拟一定数量的金钱

java - Spring Async - 无法获取异步bean

android - 如何将第一个可见的 ListView 项目与 LinearLayout 顶部对齐?

ios - 在同一数据库上同时使用核心数据和基于 sqlite c 的 api