1package com.xtremelabs.robolectric.shadows;
2
3import android.content.Context;
4import android.database.sqlite.SQLiteDatabase;
5import android.database.sqlite.SQLiteDatabase.CursorFactory;
6import android.database.sqlite.SQLiteOpenHelper;
7import com.xtremelabs.robolectric.internal.Implementation;
8import com.xtremelabs.robolectric.internal.Implements;
9import com.xtremelabs.robolectric.internal.RealObject;
10
11/**
12 * Shadow for {@code SQLiteOpenHelper}.  Provides basic support for retrieving
13 * databases and partially implements the subclass contract.  (Currently,
14 * support for {@code #onUpgrade} is missing).
15 */
16@Implements(SQLiteOpenHelper.class)
17public class ShadowSQLiteOpenHelper {
18
19    @RealObject private SQLiteOpenHelper realHelper;
20    private static SQLiteDatabase database;
21
22    public void __constructor__(Context context, String name, CursorFactory factory, int version) {
23        if (database != null) {
24            database.close();
25        }
26        database = null;
27    }
28
29    @Implementation
30    public synchronized void close() {
31        if (database != null) {
32            database.close();
33        }
34        database = null;
35    }
36
37    @Implementation
38    public synchronized SQLiteDatabase getReadableDatabase() {
39        if (database == null) {
40            database = SQLiteDatabase.openDatabase("path", null, 0);
41            realHelper.onCreate(database);
42        }
43
44        realHelper.onOpen(database);
45        return database;
46    }
47
48    @Implementation
49    public synchronized SQLiteDatabase getWritableDatabase() {
50        if (database == null) {
51            database = SQLiteDatabase.openDatabase("path", null, 0);
52            realHelper.onCreate(database);
53        }
54
55        realHelper.onOpen(database);
56        return database;
57    }
58}
59