为什么我不能在没有运行时错误的情况下使用Resources.getSystem()?

问题描述 投票:9回答:3
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));
}}

我收到这个错误

01-14 12:20:57.591:E / AndroidRuntime(1825):引起:android.content.res.Resources $ NotFoundException:字符串资源ID#0x7f040003

导致错误的代码是createProfileTable中的单行,具体是Resources.getSystem()。getString(R.string.create_profile_table_sql)如果我使用类变量来保存Context并执行context.getString(R.string.create_profile_table_sql)我没有得到任何错误,但我不想这样做,因为我想避免内存泄漏,并根据我知道这应该工作。知道发生了什么事吗?

java android eclipse sqliteopenhelper
3个回答
25
投票

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

http://developer.android.com/reference/android/content/res/Resources.html#getSystem()

如果您真的想以这种方式检索字符串,请尝试使用应用程序的上下文,或者在评论中考虑我的建议。


5
投票

使用Resources.getSystem()。getWhatEver()只能访问系统范围的资源(因为没有带有您ID的系统范围资源,您会收到错误)。由于资源ID在应用程序之间不是唯一的,因此您在访问资源时需要提供应用程序。在Android中,这是使用Context完成的。因此,如果您想访问某些资源,则需要像这样使用它

context.getResources().getString(myID);

除了布兰登的评论是正确的。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.