Java 为什么可以';我使用Resources.getSystem()时没有运行时错误吗?

Java 为什么可以';我使用Resources.getSystem()时没有运行时错误吗?,java,android,eclipse,sqliteopenhelper,Java,Android,Eclipse,Sqliteopenhelper,我得到这个错误 01-14 12:20:57.591:E/AndroidRuntime(1825):原因:android.content.res.Resources$NotFoundException:String resource ID#0x7f040003 导致错误的代码是createProfileTable中的一行代码,特别是,Resources.getSystem().getString(R.string.create\u profile\u table\u sql)如果我使用类变量保存

我得到这个错误

01-14 12:20:57.591:E/AndroidRuntime(1825):原因:android.content.res.Resources$NotFoundException:String resource ID#0x7f040003


导致错误的代码是createProfileTable中的一行代码,特别是,Resources.getSystem().getString(R.string.create\u profile\u table\u sql)如果我使用类变量保存上下文并执行Context.getString(R.string.create\u profile\u table\u sql)我没有收到任何错误,但我不想这样做,因为我想避免内存泄漏,而且根据我所知道的情况,这应该是可行的。知道发生了什么吗?

根据Android文档,
Resources.getSystem()
只提供系统级资源,而不提供应用程序级资源(如strings.xml文件中的资源)

如果您确实希望以这种方式检索字符串,请尝试使用应用程序的上下文,或者采纳我在问题注释中的建议。

使用Resources.getSystem().getwhere()您只能访问系统范围内的资源(由于没有ID为的系统范围内的资源,因此会出现错误)。由于资源ID在应用程序中不是唯一的,因此在访问资源时,您需要提供应用程序。在Android中,这是通过上下文完成的。 所以,如果你想访问一些资源,你需要像这样使用它

public class BobDatabase extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "bob.db";
private static final int DATABASE_VERSION = 1;
public static final String DEFAULT_PROFILE = "default_profile";

public BobDatabase(Context context) 
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase database) 
{
    createProfileTable(database);
    createTimeTable(database);
    createEventTable(database);
    createLocationTable(database);
}

/**
 * Creates a table for Profile objects, executes the string create_profile_table_sql
 * contained within strings.xml
 * @param database
 */
public void createProfileTable(SQLiteDatabase database)
{
    database.execSQL(Resources.getSystem().getString(R.string.create_profile_table_sql));
}}

除此之外,Brandon的评论是正确的。

您可以通过参数、静态变量或通过
getApplicationContext()
函数获取函数中的上下文参数。

这并不能真正回答您的问题,但字符串资源通常用于用户可显示的字符串(因此,如果愿意,以后可以提供不同的语言)。在这种情况下,定义一个常量字符串来定义create语句是可以的。谢谢,Brandon。我不知道Resources.getSystem()不会返回我的应用程序资源,尽管现在看起来有点明显(事后诸如此类)我也将考虑使用常量字符串。+ 1。这是一个非常不愉快和难以发现的错误。当然,有用的消息。所以,除非我选择在java代码中使用常量字符串,否则必须使用上下文访问String。XML。谢谢您的回答。它是一个带有Ss的GETREST,它的结尾类似于:<代码> CONTX.GETREST。().getString(R.string.yourStringID)
context.getResources().getString(myID);