开发者

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 开发者_如何学JAVAclass 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜