Question

I have database and i want fill it with some values from xml file. I'm using this code stream = context.getResources().openRawResource(R.xml.test_entry); to define the stream, but context make error "cannot resolve symbol 'context'". I tried replace context with getActivity(), getContext(), this, class name and it still doesn't work. I need some help...

public class DatabaseHelper extends SQLiteOpenHelper {

<...>

public DatabaseHelper(Context context) {
    super(context, dbName, null, dbv);
}


public void onCreate (SQLiteDatabase db) {
 <...>
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+tableName);
    onCreate(db);
    /////////////////
    loadTestValuyes(); <----- My function
    /////////////////
}


public  void loadTestValuyes() {

    test_addEntry stackOverflowXmlParser = new test_addEntry();
    List<Entry> entries = null;
    InputStream stream = null;

    ///// I need context here
    stream = context.getResources().openRawResource(R.xml.test_entry);
    /////////////////

    try {
        entries = stackOverflowXmlParser.parse(stream);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }


    for (Entry entry : entries) {
         <...>
    }

}


}

Thanks

Was it helpful?

Solution

You're passing a Context as a constructor argument. Just store it to a member variable:

private Context mContext;

public DatabaseHelper(Context context) {
    super(context, dbName, null, dbv);
    mContext = context;

and then use mContext where you need a Context.

OTHER TIPS

You can save a reference to the Context object as an instance variable and use it wherever you need it:

public class DatabaseHelper extends SQLiteOpenHelper {

    private Context mContext;

    public DatabaseHelper(Context context) {
        super(context, dbName, null, dbv);
        mContext = context;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top