質問

I have file, where I have all functions for database and for one query I need to get preferences with getDefaultSharedPreferences(), but I don’t know how I can get context easily.

Here is a fragment of this file:

public class Database {

    private SQLiteOpenHelper openHelper;

    public Cursor getVzkazy(long uzivatel) {
        SQLiteDatabase db = openHelper.getReadableDatabase();
        int limit = PreferenceManager.getDefaultSharedPreferences(this).getInt("limit", 100000);
        return db.query(TB_NAME_VZ, columns_vz, null, null, null, null, COLUMN_ID_VZ + " DESC", String.valueOf(limit));
    }
}
役に立ちましたか?

解決

You'll need to pass the Context when instantiating the the Database class. Add a public constructor to the class Database:

public class Database {

    private Context mContext;

    public Database(Context context) {
        mContext = context;
    }
}

Then use mContext, passing "this" won't work as it's of type Database and it expects type Context, so that'll produce a compilation error.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top