数据库连接未在Android中建立

时间:2013-02-13 05:19:56

标签: java android

我试图在Android中编写此连接代码。

public class DataBaseAdapter
{
....
....
    public DataBaseAdapter(Context context)
    {
        contextApp = context;
        myAlarmDB = new MyAlarmDatabase(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public DataBaseAdapter open() throws SQLException 
    {
        try
        {
            db = myAlarmDB.getWritableDatabase();
        }
        catch (SQLiteException ex)
        {
            db = myAlarmDB.getReadableDatabase();
        }
        return this;
    }
}

当任何代码调用open()方法时,Android App会因错误而终止。 并且当评论此特定代码时,应用程序运行。也就是说它可以自由创建SQLiteDatabase对象。

请帮助我该怎么做。?

这是连接到SQLiteOpenHelper

的类的代码
public class MyAlarmDatabase extends SQLiteOpenHelper
{   
    private static final String CREATE_STATEEMENT=
    "create table if not exists AlarmDataBase" +
    "(alarm_id integer primary key auto_increment," +
    " description text," +
    " repeatType integer," +
    " repeatDay text," +
    " millis text)";
    public MyAlarmDatabase(Context context, String name, CursorFactory factory, int version)
    {
            super(context, name, factory, version);
            // TODO Auto-generated constructor stub
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
        //db = SQLiteDatabase.openOrCreateDatabase("AlarmManagerDatabase.db", Context.MODE_PRIVATE, null);
        db.execSQL(CREATE_STATEEMENT);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub
        Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
        // The simplest case is to drop the old table and create a new one.
        db.execSQL("create table alarm_standby as select * from AlarmDataBase");
        db.execSQL("DROP TABLE IF EXISTS AlarmDataBase");
        db.execSQL("create table AlarmDataBase as select * from alarm_standby");
        db.execSQL("drop table alarm_standby");
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于Context Passing ..否则代码就会运行。将上下文值传递给数据库连接类时出错。这反过来导致应用程序关闭。如果您注释创建Database Connection类对象的代码,则代码将运行。

So it is just that you are making mistake in passing context value

修改您的代码。