Java 如何使用类(不是活动)访问数据库(使用上下文)
我对Android开发和Java都是新手。我正在开发一个搜索工具。我有一个SQLite数据库和搜索工具,搜索成功。现在我想使用自定义建议 问题是:我想在SearchSuggestionsProvider中访问我的数据库,但不能,因为我需要上下文,而类不是活动 我读到我可以在构造函数中传递上下文,但是因为我没有创建任何对象,所以我不能。也许我错过了什么 我遵循了以下教程: 以下是我的SearchSuggestionsProvider类:Java 如何使用类(不是活动)访问数据库(使用上下文),java,android,sqlite,Java,Android,Sqlite,我对Android开发和Java都是新手。我正在开发一个搜索工具。我有一个SQLite数据库和搜索工具,搜索成功。现在我想使用自定义建议 问题是:我想在SearchSuggestionsProvider中访问我的数据库,但不能,因为我需要上下文,而类不是活动 我读到我可以在构造函数中传递上下文,但是因为我没有创建任何对象,所以我不能。也许我错过了什么 我遵循了以下教程: 以下是我的SearchSuggestionsProvider类: public class SearchSuggestions
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函数,它会抛出异常
我唯一要做的就是创建自己的callmyservice函数。这是我想访问数据库的地方
Context context = getContext();
List<Pokemon> list = callmyservice(context, query);
我该怎么做
PS:是的,我正在处理一个口袋妖怪应用程序;D.您可以在SearchSuggestionProvider类内部使用
您的类扩展了getContext方法并具有该方法
当您调用callmyservice来提取数据库结果时,请确保传入getContext以将其用于您的数据库
Context context = getContext();
List<Pokemon> list = callmyservice(context, query);
或者,您也可以在数据库类中使用对应用程序上下文的引用,具体取决于您的代码结构。尽管工作类不是活动类,但您必须至少有一个活动类。正当因此,在活动类中创建一个getter
public Context getContext(){
return mContext;
}
为此,活动类中必须有一个mContext字段,该字段应初始化为引用活动的上下文
mContext = getApplicationContext();
我的主要活动是谁能胜任这项工作。但是我需要创建MainActivity类的实例来使用这个getter,对吗?这不是有点问题吗?