2

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

Jomon KC
  • 55
  • 1
  • 7

2 Answers2

0

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!

Community
  • 1
  • 1
Will Tate
  • 33,439
  • 9
  • 77
  • 71
0

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

Jomon KC
  • 55
  • 1
  • 7