My application has a main activity which starts two different activities. One is the main game and the other is the leaderboard. I have set up a SQLite database.
I need to be able to add a score to the database via the main game activity view and then read the data inside the leaderboard activity view. If I create the database in the main activity class, I can't access the database from the other activities. Is there a way around this?
What I normally do is make a singleton class that extends SQLiteOpenHelper and handles all database interaction.
private static String DB_NAME = DATABASE_NAME;
private SQLiteDatabase myDataBase;
private final Context myContext;
private static DataBaseHelper databaseHelperInstance;
private DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public static synchronized DataBaseHelper getInstance(Context c) {
if (databaseHelperInstance == null) {
synchronized (DataBaseHelper.class) {
databaseHelperInstance = new DataBaseHelper(c);
}
}
return databaseHelperInstance;
}
Then where you need it call for it:
DataBaseHelper.getInstance(this.getApplicationContext());
This blog may be helpful: http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html
Related
I'm new to Android Studio and SQLite and wanted to run a query when the app is run for the very first time only, and when the app is run again it wont run the query again.
This will depend upon how you are accessing the database.
The most common way is to utilise the SQLiteOpenHelper class. In which case the onCreate method is called when the database is created. The database only ever being created the once (unless it is deleted e.g. the App uninstalled).
When onCreate is called the database will have been created BUT will not have any components (tables, indexes, views, triggers) other than some system components. Typically this is where the components are created but meets the criteria of your question IF using a class that extends SQLiteOpenHelper. However, unless the query is to store data, it would probably be of little use as there would be no data to query.
However, using a class that extends SQLiteOpenHelper is not the only way in which an SQLite database can be accessed, nor would onCreate be called if you were utilising a pre-existing database copied from the assets folder of the package (e.g. using SQLiteAssetHelper).
In these latter cases, you could test to see if the database actually exists and set a flag/indicator. If it does not and then after opening the database you could then check the indicator and run the query.
Demonstration
Here's a demonstration of two methods.
The first using the more typical SQLiteOpenHelper and thus the onCreate method.
The second using an indicator.
The first method utilises a class that extends SQLiteOpenHelper called DBHelper :-
class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "thedatabase.db";
public static final int DATABASE_VERSION = 1;
private static volatile DBHelper instance;
private DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.getWritableDatabase(); //Force database open
}
public static DBHelper getInstance(Context context) {
if (instance==null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Run the query here AFTER creating the components
Log.d("DBHELPER","First run detected");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Rather than run a query, data is written to the log from within the onCreate method.
The second method utilises the SQLiteDatabase openOrCreateDatabase (i.e. circumventing using the SQLiteOpenHelper). Thus it has to do some of the things that SQLiteOpenHelper conveniently does automatically:-
class OtherDBHelper {
public static final String DATABASE_NAME = "otherdatabase.db";
public static final int DATABASE_VERSION = 1;
private static boolean databaseCreateIndicator = false;
private static boolean databaseVersionChanged = false;
private SQLiteDatabase database;
private static OtherDBHelper instance;
private OtherDBHelper(Context context) {
if (!context.getDatabasePath(DATABASE_NAME).exists()) {
databaseCreateIndicator = true;
File database_dir = context.getDatabasePath(DATABASE_NAME).getParentFile();
if (!database_dir.exists()) {
database_dir.mkdirs();
}
// Copy database from assets
}
database = SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath(DATABASE_NAME),null);
//* Database now open */
// If utilising Version number check and set the version number
// If not copying pre-existing database create components (tables etc)
if (databaseCreateIndicator) {
//<<<<<<<<<< Query here >>>>>>>>>>
Log.d("OTHERDBHELPER","First run detected");
}
}
public SQLiteDatabase getSQLiteDatabase() {
return database;
}
public static OtherDBHelper getInstance(Context context) {
if (instance==null) {
instance = new OtherDBHelper(context);
}
return instance;
}
}
again the instead of running a query outputting to the log is used.
To test both in unison then some activity code:-
public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
OtherDBHelper otherDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("PREDBMSG","Just prior to getting the databases.");
dbHelper = DBHelper.getInstance(this);
otherDBHelper = OtherDBHelper.getInstance(this);
Log.d("POSTDBMSG","Just after getting the databases.");
}
}
Results
When run for the first time then the log includes:-
2022-10-20 07:09:27.633 D/PREDBMSG: Just prior to getting the databases.
2022-10-20 07:09:27.663 D/DBHELPER: First run detected
2022-10-20 07:09:27.697 D/OTHERDBHELPER: First run detected
2022-10-20 07:09:27.697 D/POSTDBMSG: Just after getting the databases.
When run again :-
2022-10-20 07:10:41.258 D/PREDBMSG: Just prior to getting the databases.
2022-10-20 07:10:41.266 D/POSTDBMSG: Just after getting the databases.
I'm trying to create a little android app.
My problem is that one: After creating a JDBC Connection to my DB in the first Activity, how can i use the same connection in other activities to make querys?
I know how to make the query with the statement, but can i pass the connection of the Main Activity in order to use only the first connection in all the other activity of the application?
My db is AS400 of the IBM and i can access to it only with JDBC (in the Android platform). I know that is simple with web service but the company want to make everything in this way.
Sorry for my english, i'm an Italian guy!
Usually it's not a problem to use your DB in many components simultaneously. If you use common pattern of your DB-class to encapsulate standard DBhelper extends SQLiteOpenHelper - you can instantiate your DB class in many Activities and it will be used in thread-safe mode.
public class DB {
private static final String TAG = "DB";
public static final int SCHEMA_VERSION = 7;
final DBhelper mDBhelper;
public SQLiteDatabase mDB;
public DB ( Context context ) {
mDBhelper = new DBhelper(context);
// open the DB for read and write
mDB = mDBhelper.getWritableDatabase();
}
public synchronized long insertSite ( objSite s ) {
...
}
...
private class DBhelper
extends SQLiteOpenHelper {
public DBhelper ( Context context ) {
super(context, C.DB_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate ( SQLiteDatabase db ) {
...
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "entering onUpgrade(): oldVersion="+oldVersion+", newVersion="+newVersion);
...
}
...
}
}
And use it as usually
public class MainActivity extends Activity {
DB eventsDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
eventsDB = new DB(this);
...
eventsDB.insertSite(objectSite);
}
...
}
In Android usually you use SQLite to persist your data. Try this tutorial.
If you have a database server and you want to access throw an android device, i suggest you to wrap database access with an intermediate server which expose data with web service (REST).
You don't specify if database access is in internet or intranet context, so i thought it is in an mixed context.
My application give me this warning
A SQLiteConnection object for database
'+data+data+com_example_test+database' was leaked! Please fix
your application to end transactions in progress properly and to close
the database when it is no longer needed.
But I close the db object and the cursor after every use.
try {
while (cursor.moveToNext()) {
...
}
} finally {
if (cursor != null && !cursor.isClosed())
cursor.close();
}
...
db.close();
Can you help me for understand what is the problem?
thanks!!!
UPDATE!
I try this solution from this post
SQLite Connection leaked although everything closed
and I don't have memory leak anymore, is it a good solution?
Possible Solutions:
You have not committed the transactions you have started (You should
always close the transaction once you started)
Check whether you have closed the cursors you have opened if you are
using Sqlite (Looks like you have done this step from the code you posted)
Also move the db.close to finally block
You have not called db.close on a database before deleting it with context.deleteDatabase(...) and then recreating it with dbHelper.getWritableDatabase()
Just drag that db.close up into the finally block.
//Inside your SQLite helper class
#Override
public synchronized void close () {
if (db != null) {
db.close();
super.close();
}
}
//Inside the activity that makes a connection to the helper class
#Override
protected void onDestroy () {
super.onDestroy();
//call close() of the helper class
dbHelper.close();
}
this code stops the leak and fixes cursor problems.
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper sInstance;
private static final String DATABASE_NAME = "database_name";
private static final String DATABASE_TABLE = "table_name";
private static final int DATABASE_VERSION = 1;
public static DatabaseHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
if (sInstance == null) {
sInstance = new DatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
/**
* Constructor should be private to prevent direct instantiation.
* make call to static factory method "getInstance()" instead.
*/
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
In my case the error was caused when y try to download new data and database should be updated.
I solved it instantiating the database by calling a SELECT 0. That cause database to be updated, so after that I try to download the new data. And worked fine.
Probably you forgot to remove the break point of debugging
sample:
In my case, I was calling to getWritableDatabase or getReadableDatabase and not use it at all. for example if you use it with "execSQL" execSQL will call "releaseReference" "Releases a reference to the object, closing the object if the last reference was released."
Situation: I am trying to export my SQLite Tables to a XML file and have followed this answer as well as a post deleted from here and also this question (apparently both last links from the same author :) )
Update-2: I already have another class named DBAdapter which extends the SQLiteOpenHelper. So I have this:
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/*...*/
onCreate()
/*...*/
onUpgrade()
/*...*/
}
already in my DBAdapter class file. How can I reuse this?
Also, I tried passing as:
DataXmlExporter dm = new DataXmlExporter(SQLiteDatabase
Database(getReadableDatabase ()));
But still got an error.
Update-1: I used the 2nd Link to implement my solution.
Problem: I am getting a Null Pointer Exception; I guess because I haven't initialized my object correctly. At the time of calling the DataXmlExporter / exportData method what is supplied as parameter? : DataXmlExporter dm = new DataXmlExporter(WHAT_IS_PASSED_HERE?);
Thanks..
looks like you need an SQLiteDatabase.
for example you can get one with getReadableDatabase() or with getWritableDatabase().
If you implemented DatabaseAssistant like in the first link you provided you have as constructor parameter a reference to a SQLiteDatabase....
You need to pass SQLiteDatabase Database ( getReadableDatabase () ):
As per constructor
public DataXmlExporter(final SQLiteDatabase db) {
this.db = db;
}
And as per comments:
Android DataExporter that allows the passed in SQLiteDatabase
to be exported to external storage (SD card) in an XML format
What I did was to extend the SQLiteOpenHelper inside the DatabaseAssistant class and used it.
I'm using ORMLite in an android project, and I'm not wanting to use the extended activities because I'm inserting values into the database on an AsyncTask.
In the docs it says:
"If you do not want to extend the OrmLiteBaseActivity and other base classes then you will need to duplicate their functionality. You will need to call OpenHelperManager.getHelper(Context context, Class openHelperClass) at the start of your code, save the helper and use it as much as you want, and then call OpenHelperManager.release() when you are done with it."
It also says to add the database helper class in the strings.xml, which I have. So I'm not sure what I'm doing wrong.
I'm using a class called DataAccess for my data tier that looks like this:
public class DataAccess {
private Context context;
private DBHelper dbHelper;
public DataAccess(Context _context) {
this.context = _context;
dbHelper = getDBHelper(_context);
}
private DBHelper getDBHelper(Context context) {
if (dbHelper == null) {
dbHelper = (DBHelper) OpenHelperManager.getHelper(context, DBHelper.class);
}
return dbHelper;
}
}
And I'm using the extended helper class:
public class DBHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "database.db";
private static final int DATABASE_VERSION = 1;
private Dao<SomeObject, Integer> someObjectTable = null;
private ConnectionSource connectionSource = null;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
this.connectionSource = connectionSource;
try {
TableUtils.createTable(connectionSource, SomeObject.class);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
}
public Dao<SomeObject, Integer> getSomeObjectDao() throws SQLException {
if (someObjectTable == null) {
dateTable = getDao(SomeObject.class);
}
return someObjectTable;
}
The idea is to create the DataAccess class and have it create the DBHelper if it hasn't already.
Can someone tell me if this is right or wrong, or if I'm on the right path?
Thanks!
I'm using ORMLite in an android project, and I'm not wanting to use the extended activities because I'm inserting values into the database on an AsyncTask.
You are on the right track but a little off #Matt. Frankly I'd never done a project without extending our base classes. But it is a good exercise so I've created this ORMLite example project which uses an Activity and manages its own helper.
Your DBHelper class is fine but really you do not need your DataAccess class. In each of your activities (or services...) you will need to have something like the following:
private DBHelper dbHelper = null;
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
OpenHelperManager.releaseHelper();
dbHelper = null;
}
}
private DBHelper getHelper() {
if (dbHelper == null) {
dbHelper = (DBHelper)OpenHelperManager.getHelper(this, DBHelper.class);
}
return dbHelper;
}
You [obviously], then use this in your code by doing something like:
Dao<SomeObject, Integer> someObjectDao = getHelper().getSomeObjectDao();
So whenever you call getHelper() the first time, it will get the helper through the manager, establishing the connection to the database. Whenever your application gets destroyed by the OS, it will release the helper -- possibly closing the underlying database connection if it is the last release.
Notice that the OpenHelperManager.getHelper() needs the Context as the first argument in case you do this without even an Activity base class.
Edit:
If you do want to create a DataAccess type class to centralize the handling of the helper class then you will need to make the methods static and do your own usage counter. If there are multiple activities and background tasks calling getHelper() then the question is when do you call releaseHelper()? You'll have to increment a count for each get and only call release when the counter gets back to 0. But even then, I'm not 100% sure how many lines you'd save out of your activity class.
I could nitpick but essentially you are doing it correct.
The call
dbHelper = (DBHelper) OpenHelperManager.getHelper(context, DBHelper.class);
Looks up the DBHelper class and instantiates it for the context. If you have defined it in your strings.xml, you can leave off the DBHelper.class at the end.
onUpgrade in you DBHelper.java, you may want to consider dropping the table you create in onCreate and then calling onCreate (to make sure you don't have conversion issues from update to update). You could do a more complex update if you wanted.
Other than that, it looks good. If you end up wanting data accessory methods for your DB objects beyond the base DAO methods, you will eventually want to create more thorough implementations of your object DAOs, but this is a good start.