java - 使用 getAssets() 给出错误 "The method getAssets() is undefined for the type ClassName"?

标签 java android

我正在尝试打开 Assets 文件夹中的文件。但是使用 getAssets() 会给出上面给出的错误。我知道我必须从另一个 Activity 传递上下文,但我也不能这样做,因为另一个错误出现了——“ClassName 类型的方法 onCreate(SQLiteDatabase, Context) 必须覆盖或实现一个父类(super class)型方法”。所以我被卡住了。有没有更好的方法打开该文件?这是一行:

InputStream is = getAssets().open("file1.txt");

*注意:ClassName 不是一个 Activity ,它只是一个类,因此如果不从另一个 Activity 传递上下文,getAssets() 将无法工作。

编辑:这是类和 onCreate 声明:

public class DatabaseHandler extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {//some stuff
InputStream is = getAssets().open("file1.txt");
//more stuff
}
}

最佳答案

I am trying to open a file which is in the assets folder. But using getAssets() gives the error given above.

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 is not an activity, it's just a class

更具体地说,它是 SQLiteOpenHelper 的子类。

so getAssets() cannot work without passing context from another activity.

一个 SQLiteOpenHelper 被传递给它的构造函数一个 Context,你需要覆盖它。

除此之外,如果您的目标是将数据库与您的应用程序打包在一起,please use SQLiteAssetHelper ,因为它已经解决了这个问题。

关于java - 使用 getAssets() 给出错误 "The method getAssets() is undefined for the type ClassName"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15586072/

相关文章:

Java 将字符串转换为 URL 兼容版本

java - 注释会影响编译时间吗?

php - 从 Android 手机上传图片到笔记本电脑需要太长时间,最后上传时显示“Windows 照片查看器无法显示,因为文件为空”

android - sqlite 返回 : error code = 1, msg = no such column:kitchen1

java - 选项组水平?

java - 在 Apache Tomcat 应用程序中,MBean 字段是否需要可变/同步才能使 JMX 更新出现在其他线程中?

java - Android TextView.setText() 在 Thread.sleep() 阻塞之前调用并返回,直到 sleep() 返回。为什么?

java - HIkariCP 为每个 webapp 创建连接池

android - Instrumentation.Activity Monitor 可以查找任何正在启动的 Activity 吗?

android - 无法在标题 TextView 上设置辅助功能焦点