我也是 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 };
}
(我没有展示删除、插入、更新函数,无论如何都会抛出异常) 我唯一想做的就是创建 mt 自己的“callmyservice”功能。这是我想要访问我的数据库的地方。
我该怎么做?
PS:是的,我正在处理 Pokemon 应用程序;D。
最佳答案
您可以使用getContext()在您的 SearchSuggestionProvider
类中。
您的类(class)扩展SearchRecentSuggestionsProvider延伸ContentProvider并具有方法 getContext()
。
当您调用 callmyservice
来提取数据库结果时,请确保传入 getContext()
以将其用于您的数据库。
Context context = getContext();
List<Pokemon> list = callmyservice(context, query);
或者,您可以在数据库类中使用对应用程序上下文的引用,具体取决于您的代码结构。
关于java - 如何通过我的类(不是 Activity )访问我的数据库(使用上下文),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25247409/