1

我正在尝试编写此代码以在 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 应用程序会因错误而终止。当这个特定的代码被注释时,应用程序就会运行。那就是它自由地创建 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");
    }
}
4

1 回答 1

0

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

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

修改你的代码。

于 2013-03-13T12:20:11.057 回答