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
Related
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);
}
}
DBHelper db =new DBHelper(context);
Cursor result = db.weeklyMedicinesTaken();
//WeeklyMedicinesTaken is a function in DBHelper class which returns cursor containing an integer value.
startManagingCursor(result); //this function is a resistance in what i want to do.
while(result.moveToNext())
{
int count=result.getInt(0);
}
result.close();
Actually I have simple classes (non activity classes) in which i want to retrieve data from sqlite and apply some processing and evaluation of data., but the problem is that the code above is working fine in activity but not working in any non activity class or in any static function of activity so that i can call that function from any class.
Any Suggestion Please??
Use getActivity().startManagingCursor(c) or pass an instance of your context to the class inwhich you want to call startManagingCursor()
Lets say your class is sth like this:
Person{
Context mContext;
String name, surname;
Person (Context context){
mContext = context;
}
While creating your Person object you should pass the context like this:
in your onCreate() or somewhere else inside the activity:
Person p = new Person(getActivity());
However, it's not a good practice to manage your cursor outside the activity.
You can examine this tutorial for simple patterns.
I have a class extending SQLiteOpenHelper to manage my database stuff. I find it rather tedious to be writing code like this to use my database(DBHelper is the SQLiteOpenHelper object):
DBHelper dbHelper = new DBHelper(context);
FeedResponse feedResponse = dbHelper.getFeedResponse(...);
dbHelper.close();
Is there anything wrong with replacing the above code with a static method and using it like this? Where might I run into trouble when implementing my database access like this?
FeedResponse feedResponse = DBHelper.getFeedResponse(context, ...);
public static FeedResponse getFeedResponse(Context context, ...) {
DBHelper dbHelper = new DBHelper(context);
FeedResponse feedResponse = dbHelper.getFeedResponse(...);
dbHelper.close();
return feedResponse;
}
public FeedResponse getFeedResponse(...) {
//returns data from database
}
Doing this really cuts down on always creating(typing out) a new instance of DBHelper and also closes it without a fuss. It's all taken care of behind the scenes.
Your solution should work, but isn't optimal as you'll create a new DBHelper object for each database query. And the creation of an object is a expensive operation. It would be better if you reuse the DBHelper object.
Also you may have troubles using your DBHelper from multiple threads.
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()?
I have a DBHandler class that will be used in several activities to do some crud operations. created a MyApp class (extends Application) to hold one instantiation of the DBHandler.
My DBHandler class needs a Context to create the SQLiteOpenHelper to populate the db, etc.
That's where the problem starts: in my MyApp constructor, I want to instantiate my DBHandler, so I wrote this:
public MyApp() {
super();
dbh = DBHandler(<WHAT DO I PASS HERE>);
}
I tried getApplicationContext(), getBaseContext(), 'this'... nothing seems to be a fully-instantiated context at this point. I get a NPE when the SQLiteOpenHelper tries ctx.getResources().
A workaround: create the DBHandler and set it in the onCreate of my main class. -> UGLY (call me a aesthetician)
Question: is there a way to do it when Android creates MyApp?
Thanks!
Creating your DBHandler in MyApp.onCreate() is the proper way to do what you want.
#Override
public void onCreate() {
super.onCreate();
dbh = new DBHandler(this);
}