简体   繁体   中英

Database Connection not established in Android

I ama trying to write this code for connection in 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;
    }
}

When any code calls open() method the Android App Terminates with error. and when this particular code is commented then the application runs. That is it creates SQLiteDatabase objects freely.

Please help me what should I do.?

This is code for the class which connects to 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");
    }
}

The problem is with Context Passing.. else the code would had run. You are making mistake in passing the context value to your database connection classes. Which in return is causing the application to close down. if you comment the code which creates the object of Database Connection class then the code will run.

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

Revise your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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