java 使用 getAssets() 会出现错误“getAssets() 方法未定义为 ClassName 类型”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15586072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using getAssets() gives the error "The method getAssets() is undefined for the type ClassName"?
提问by Tom Wong
I am trying to open a file which is in the assets folder. But using getAssets() gives the error given above. I know I have to pass the context from another activity, but I can't do that either as then another error comes-"The method onCreate(SQLiteDatabase, Context) of type ClassName must override or implement a supertype method". So I am stuck. Is there a better way of opening that file? Here is the line:
我正在尝试打开资产文件夹中的文件。但是使用 getAssets() 会出现上面给出的错误。我知道我必须从另一个活动传递上下文,但我也不能这样做,因为另一个错误出现 - “ClassName 类型的方法 onCreate(SQLiteDatabase, Context) 必须覆盖或实现超类型方法”。所以我被困住了。有没有更好的方法打开那个文件?这是线路:
InputStream is = getAssets().open("file1.txt");
*Note: ClassName is not an activity, it's just a class, so getAssets() cannot work without passing context from another activity.
*注意:ClassName 不是一个活动,它只是一个类,所以 getAssets() 不能在没有从另一个活动传递上下文的情况下工作。
Edit: Here is the class and onCreate declaration:
编辑:这是类和 onCreate 声明:
public class DatabaseHandler extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {//some stuff
InputStream is = getAssets().open("file1.txt");
//more stuff
}
}
回答by CommonsWare
I am trying to open a file which is in the assets folder. But using getAssets() gives the error given above.
我正在尝试打开资产文件夹中的文件。但是使用 getAssets() 会出现上面给出的错误。
getAssets()
is a method on Context
.
getAssets()
是一种方法Context
。
I know I have to pass the context from another activity, but I can't do that either as then another error comes-"The method onCreate(SQLiteDatabase, Context) of type ClassName must override or implement a supertype method".
我知道我必须从另一个活动传递上下文,但我也不能这样做,因为另一个错误出现 - “ClassName 类型的方法 onCreate(SQLiteDatabase, Context) 必须覆盖或实现超类型方法”。
Since you declined to paste the source code where this is occurring, it is difficult to help you.
由于您拒绝粘贴发生这种情况的源代码,因此很难为您提供帮助。
ClassName is not an activity, it's just a class
ClassName 不是活动,它只是一个类
More specifically, it is a subclass of SQLiteOpenHelper
.
更具体地说,它是 的子类SQLiteOpenHelper
。
so getAssets() cannot work without passing context from another activity.
所以 getAssets() 不能在没有从另一个活动传递上下文的情况下工作。
A SQLiteOpenHelper
gets passed a Context
to its constructor, which you need to override.
ASQLiteOpenHelper
被传递Context
给它的构造函数,你需要重写它。
Beyond all of this, if your objective is to package a database with your app, please use SQLiteAssetHelper
, as it has solved this problem.
除此之外,如果您的目标是将数据库与您的应用程序一起打包,请使用SQLiteAssetHelper
,因为它已经解决了这个问题。
回答by Lefteris
How about:
怎么样:
InputStream is = getActivity().getAssets().open("file1.txt");