After you inherit from SQLiteOpenHelper and create an object out of the inherited class, the inherited class creates a whole new database to work with. How can I make the inherited class open a database I created earlier instead of making a new one?
Asked
Active
Viewed 128 times
-1
-
1Unclear. Are you asking how to ship an app with a pre-made database? – Phantômaxx Sep 08 '16 at 15:20
2 Answers
0
When you call the SQLiteOpenHelper constructor, you pass in the database filename. If you use the same filename, it will open the same db. Although having multiple classes open the same db is really not something I'd suggest.

Gabe Sechan
- 90,003
- 9
- 87
- 127
-
why do you not suggest having multiple classes opening the same database – arcode Sep 08 '16 at 15:45
-
Because then you have multiple handles writing to the database concurrently and have to start worrying about sequencing and locking. I'd use a single class to write to a single db (although having multiple dbs is fine), and break that into multiple interfaces if you want to limit what sections of the code can see. – Gabe Sechan Sep 08 '16 at 15:50
-
there are two classes I'm working with. the classes don't concurrently access the dB, rather the 1st class accesses it first, then the second one. But can I close the dB after the first class finishes modifying or accessing it(in case it starts to eat up the memory)? – arcode Sep 08 '16 at 16:11
0
If you are using a emulator then push the database file into the database folder of the project by opening android device manager->file Explorer->data->data->your project name then push the database file and then change the database name to your database name.
public class mydb extends SQLiteOpenHelper
{
String DBPATH="/data/data/com.example.aman.java/databases/";
static String DBNAME="java1db"; //here write your database name
static int DBVERSION=3;
Context mycontext;
SQLiteDatabase mydb1;
mydb(Context mycontext1)
{
super(mycontext1,DBNAME,null,DBVERSION);
mycontext=mycontext1;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public void init()
{
mydb1=this.getReadableDatabase();
}
public void close1()
{
mydb1.close();
}
}
if you are running on your device paste the database file in assets folder and paste this code in sqllitehelper class
void copyDatabase() throws IOException
{
InputStream myinput=mycontext.getAssets().open(DBNAME);
String outfile=DBPATH + DBNAME;
OutputStream myoutput=new FileOutputStream(outfile);
int a;
byte[] buffer=new byte[1024];
while((a=myinput.read(buffer))>0)
{
myoutput.write(buffer,0,a);
}
myoutput.close();
myinput.close();
}

riser
- 7
- 7