[英]How can I grant access of my database to a user with a certain username and password which I am not using?
[英]How can I access my DataBase (using a context) with my class (which is not an activity)
我是Android开发和Java的新手。 我正在使用搜索工具。 我有一个SQLite数据库,搜索工具成功地在其中搜索。 现在,我想使用自定义建议。
问题是:我想访问我的SearchSuggestionsProvider中的数据库,但是不能,因为我需要上下文(并且该类不是Activity)。
我读到可以在构造函数中传递上下文,但是由于我没有创建任何我不能创建的对象。 也许我在这里错过了一些东西。
我遵循了本教程: http : //weblog.plexobject.com/ ?p= 1689 。
这是我的SearchSuggestionsProvider类:
public class SearchSuggestionsProvider extends SearchRecentSuggestionsProvider {
static final String TAG = SearchSuggestionsProvider.class.getSimpleName();
public static final String AUTHORITY = SearchSuggestionsProvider.class
.getName();
public static final int MODE = DATABASE_MODE_QUERIES | DATABASE_MODE_2LINES;
private static final String[] COLUMNS = {
"_id", // must include this column
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_INTENT_DATA,
SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
SearchManager.SUGGEST_COLUMN_SHORTCUT_ID };
public SearchSuggestionsProvider() {
setupSuggestions(AUTHORITY, MODE);
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
String query = selectionArgs[0];
if (query == null || query.length() == 0) {
return null;
}
MatrixCursor cursor = new MatrixCursor(COLUMNS);
try {
List<Pokemon> list = callmyservice(query);
int n = 0;
for (Pokemon pokemon : list) {
cursor.addRow(createRow(new Integer(n), query, pokemon.getName(),
pokemon.getTier()));
n++;
}
} catch (Exception e) {
Log.e(TAG, "Failed to lookup " + query, e);
}
return cursor;
}
private Object[] createRow(Integer id, String text1, String text2,
String name) {
return new Object[] { id, // _id
text1, // text1
text2, // text2
text1, "android.intent.action.SEARCH", // action
SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT };
}
(我没有显示出delete,insert,update函数,无论如何都会抛出异常)。我唯一要做的就是创建mt自己的“ callmyservice”函数。 这是我要访问我的数据库的地方。
我怎样才能做到这一点 ?
PS:是的,我正在处理Pokemon应用程序; D.
您可以在SearchSuggestionProvider
类内使用getContext() 。
您的类扩展了SearchRecentSuggestionsProvider ,后者扩展了ContentProvider并具有方法getContext()
。
调用callmyservice
提取数据库结果时,请确保传递getContext()
以将其用于数据库。
Context context = getContext();
List<Pokemon> list = callmyservice(context, query);
或者,您可以根据您的代码结构,在数据库类中使用对应用程序上下文的引用。
尽管工人阶级不是活动班,但您至少必须有一个活动班。 对? 因此,在活动类中创建一个吸气剂。
public Context getContext(){
return mContext;
}
为此,您必须在活动类中具有一个mContext字段,该字段应进行初始化以引用活动的上下文。
mContext = getApplicationContext();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.