首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android数据库管理器和内部DatabaseHelper类

Android数据库管理器和内部DatabaseHelper类
EN

Stack Overflow用户
提问于 2013-12-23 22:10:01
回答 1查看 1.9K关注 0票数 0

我正在开发一个具有数据库功能的android应用程序。要与数据库通信,im创建一个DatabaseManager类,内部类名为DatabaseHelper。虽然我在执行方面有一些问题,所以如果有人能提供一点澄清,我将不胜感激。

  • 为什么访问数据库所必需的是内部类?

例如,在一个活动中

代码语言:javascript
复制
DatabaseManager db = new DatabaseManager(this);
db.open();
db.insert(some_values);

DatabaseManager类

代码语言:javascript
复制
public class DatabaseManager{

// Database details
private static final String     DATABASE_NAME = "Test Database";
// Table Names
private static final String     USER_TABLE = "User";    
// Table columns
public static final String      KEY_ROWID = "_id";
public static final String      KEY_USERNAME = "username";

private static final int        DATABASE_VERSION = 1;

private static final String     USER_CREATE =           

    "create table " + USER_TABLE +
    " (_id integer primary key autoincrement not null, " +
    "username text not null);";

public DatabaseHelper   helper;
public SQLiteDatabase   the_db;
public Context          context;

public DatabaseManager(Context c){
    this.context = c;
    helper = new DatabaseHelper(context); 
}

public void open(){
    helper.open();
}


class DatabaseHelper extends SQLiteOpenHelper{

    DatabaseHelper(Context context){
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db){            
            db.execSQL(USER_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


    public DatabaseManager(Context c){
        this.context = c;
        helper = new DatabaseHelper(context); 
    }


    // Makes the_db available to the Manager class.
    public DatabaseManager open() throws SQLException{
        this.the_db = this.helper.getWritableDatabase();
        return this;
    }

    public void close(){ 
        helper.close();     
    }


    public long insertFacebook(String uname, String pwd){
        ContentValues content = new ContentValues();
        content.put(KEY_USERNAME, uname);           
        content.put(KEY_PASSWORD, pwd);

        return the_db.insertOrThrow(FACEBOOK_TABLE, null, content);
    }}  
EN

回答 1

Stack Overflow用户

发布于 2013-12-24 04:20:40

SQLiteOpenHelper:

用于管理数据库创建和版本管理的助手类。

您可以创建一个实现onCreate(SQLiteDatabase)onUpgrade(SQLiteDatabase,int,int)的子类,并可选地创建onOpen(SQLiteDatabase),,如果存在数据库,这个类负责打开数据库,如果不存在,则创建数据库,并根据需要对其进行升级。事务用于确保数据库始终处于合理状态。

这个类使ContentProvider实现很容易将数据库的打开和升级推迟到第一次使用,以避免在长时间运行的数据库升级中阻止应用程序启动。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20751908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档