سؤال

I am writing a content provider in android. I want to write query implementation. I am creating a DbHelper object in the query function of contentProvider. But I am getting error when I create this that is I cannot access MainActivity.this in this content provider class. I need that MainActivity.this so that I can initialize DbHelper and use already implemented function query in DbHelper class by me. How do I solve this problem?

Code:

public class CourseContentProvider extends ContentProvider {


    @Override
    public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
            String arg4) {
        // TODO Auto-generated method stub

        if (sURIMatcher.match(arg0)==COURSE) {
            MyDbHelper obj = new MyDbHelper(MainActivity.this);//Error msg here: No enclosing instance of the type MainActivity is accessible in scope
        }
        return null;
    }
//other auto generated functions
}

Thanks.

هل كانت مفيدة؟

المحلول

to get Context just call getContext() in your class that extends ContentProvider

example:

@Override
    public boolean onCreate() {
        Context context = getContext();
        DBHelper = new DatabaseHelper(context);
        db = DBHelper.getWritableDatabase();
        return (db == null) ? false : true;
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top