Passing a null context to a database helper - android

I have a static function that gets called whenever my background service gets a new location. In this function I want to take to coordinates passed in and save them in my database. Can I pass 'null' as the context to create an instance of the database helper or is there a better way to do this. Thanks.
public static void locationHasChanged() {
final wd_DatabaseHelper helper = new wd_DatabaseHelper(null, "myDB.db", null, 1);
}

Probably not. Usually your Database helper extends SQLiteOpenHelper and the context will be used to call the openOrCreateDatabase() or the getDatabasePath(). I can't say for sure without seeing the code of wd_DatabaseHelper but having a null context is never a good idea. See for your self ... Source of SQLiteOpenHelper

since an android Service is a context you can pass "this of the service" into your method
public class MyLocationHelper {
public static void locationHasChanged(Context context) {
final wd_DatabaseHelper helper = new wd_DatabaseHelper(context, "myDB.db", null, 1);
....
}
}
public class MyService extends Service {
private void onLocationHasChanged()
{
MyLocationHelper.locationHasChanged(this);
}
}

Related

Correct way for Singleton usage in class with static functions and callbacks

I have an DB manager class for my queries which runs with Asynctask:
public class DBManager {
private static DBCallback dbCallback;
//I need this for callbacks to main class when operation is finished
public DBManager(DBCallback mClass) {
this.dbCallback = mClass;
}
public static void getAllUsers() {
new AsyncTask<Void, Void, List<UserDB>>() {
#Override
protected List<UserDB> doInBackground(Void... voids) {
return DatabaseClient.getInstance(ApplicationContextProvider.getContext()).getAppDatabase().userDao().getAll();
}
#Override
protected void onPostExecute(List<UserDB> users) {
super.onPostExecute(users);
dbCallback.finishedReadFromDB(users); //Sending callback
}
}.execute();
}
public static void deleteUserLocal(final UserDB user) {
new AsyncTask<UserDB, Void, Void>() {
#Override
protected Void doInBackground(UserDB... users) {
DatabaseClient.getInstance(ApplicationContextProvider.getContext()).getAppDatabase().userDao().delete(users[0]);
return null;
}
}.execute(user);
}
}
At my MainClass I am using
dbManager = new DBManager(this);
for receiving callback, so I am using
dbManager.getAllUsers();
and then gets callback when operation is finished.
But I have fictions where I do not need to return anything like deleteUserLocal. So I can user ether
dbManager.deleteUserLocal(user)
or
DBManager.deleteUserLocal(user)
due to that the function is static.
From classes that not require callback of course I using
DBManager.deleteUserLocal(user)
So... I do not like that every time at onCreate am I am crating new instnce of DBManager:
dbManager = new DBManager(this);
Just for callbacks. How can I create a singleton class which I can use for callback and only use
DBManager.getAllUsers(); instead of dbManager.getAllUsers();
To achieve what you want, get rid of the constructor and change the static callback to public. That way you can set the public static variable externally before calling any of the other static methods. A constructor in a class with all static members is unnecessary.
Now with that being said, this design for accessing a database in Android is not going to scale very well. DBManager will only be able to have one client at any given time. A better approach would be to pass in the callback for any method that requires it and drop the static variable callback.
You may use this pattern
https://www.google.de/amp/s/www.geeksforgeeks.org/singleton-design-Patient tern/amp/
And then work with get instance.
But I would consider to implement the asyncTask without a return value if you are already using Callbacks already.
Try this link
https://de.m.wikibooks.org/wiki/Muster:_Java:_Singleton

Android, Singleton, context

I am stuck in a problem. I am creating a helper class that needs to be Singleton. And that class has a global context variable. I am not able to do this since context is available only from onCreate and this Singleton instance is created much before since it is static.
Can someone help me on how to solve this issue. Context is needed for the Singleton instance finally.
public class Helper {
private static Helper sHelper = new Helper() ;
private Helper () {} ;
public static Helper getInstance() {
return sHelper;
}
public boolean doSomething() {
mContext.getContentResolver;
return isDone;
}
}
You can set the context to be you ApplicationContext.
You can create an Application class and implement something like:
yourSingletonClass.getInstance().setContext(this);
This call should be in you application class under the onCreate method.
For more information try this docs:
Android - Application class
You just need to pass the following context to your helper class.
getApplicationContext()
You need pass the context trougth your construct helper class:
getApplicationContext()

How in Android to pass an object to new Intent

I'd greatly appreciate any thoughts on the following problem:
In Android I have my MainActivity, which creates and sets up a database handler class.
e.g.
public class DbHandler extends SQLiteOpenHelper{
//do db handling
}
Also, I've created my OnClickListener, which creates an Intent then startActivity's the Intent.
My question / problem is how to best pass the DBHandler into the new Activity. I've thought about creating a global - and the risks of the thread restarting. I can't quite work out how to parcel / serialize unless I create a wrapper - but still have the problem of passing the object in the "parcel"
I'm keen to understand how others have solved this?? Many thanks.
As I know it is good practice to use only one instance of SQLiteOpenHelper, so create it as singleton and make accessible
public final class DatabaseHelper extends SQLiteOpenHelper {
/**
* instance.
*/
private static DatabaseHelper instance;
/**
* #return instance.
*/
public static synchronized DatabaseHelper getInstance() {
if (instance == null) {
instance = new DatabaseHelper();
}
return instance;
}
...
}

Using singleton class for sharing instance of database between activities?

Hey! I want to use a singleton class, because if I open the database every activity I get "Leak found"( that happens because I open the database even if it is already open ) . I create a singleton class , but I don't know how should I use it.
Here is my class:
package com.ShoppingList;
import com.ShoppingList.databases.DbAdapter;
public class DbManager {
DbAdapter db;
// singleton
private static DbManager instance = null;
private DbManager() {
}
public static DbManager getInstance() {
if (instance == null)
instance = new DbManager();
return instance;
}
public void setinstance(DbAdapter db){
this.db=db;
}
public DbAdapter getinstancedb(){
return db;
}
}
In the first activity I put :
db = new DbAdapter(this);
db.open();
DbManager.getInstance().setinstance(db);
and for the next activity : DbManager.getInstance().getinstancedb(); but I get force close for second activity.
Can anyone help me how to use it? Thanks...
You can extend Application class and create there an instance of DbAdapter. This way it will be shared by all your activities.
Because db has the same context and life cycle of your first activity. Make your methods public and make them do all the setup/teardown necessary to return your desired result.
regarding the leak warning. Are you closing your db manager connection in onDestroy()?

Access databasehelper object globally

Whenever i need to create SQLiteOpenHelper 'databasehelper' object, i need to pass the context in function call.
dbUtils.setEntityValues(this, moduleId, sendTo)
the 'this' parameter refers to the activity context. each time new databasehelper object is creating and perform db tasks.
DataBaseHelper dbHelper = new DataBaseHelper(context);
try {
dbHelper.openDataBase();
SQLiteDatabase db = dbHelper.getReadableDatabase();
From class files which are not extending Activity or Application, i cant create databasehelper object. Is there any way to get databasehelper object globally? OR any way to get the application context in classes that are not Activity...?
Im an android beginner, please suggest some tips..
Thanks in advance,
Joe
joe,
You can use getApplicationContext() or getBaseContext() to access the application context from classes that don't extend context.
You will probably also want to read up on this question a bit What's the difference between the various methods to get a Context?
Good luck!
Thanks willytate, I resolved it. the way i do it is...
class myActivity extends Activity {
public static Activity me = null;
...
protected void onCreate(Bundle icicle) {
...
me = this;
...
};
};
class myClass {
void myMthd() {
...
Intent myIntnt = myActivity.me.getIntent();
...
};
};
Now i can create the 'databasehelper' object without passing context like following..
public DataBaseHelper() {
super(myActivity.me.getApplicationContext(), DB_NAME, null, 1);
this.myContext = myActivity.me.getApplicationContext();
}
Thanks again,
Joe

Categories

Resources