ランタイムエラーなしでResources.getSystem()を使用できないのはなぜですか?

StackOverflow https://stackoverflow.com/questions/8864015

質問

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.resources $ notfoundexception:文字列リソースID#0x7F040003

エラーを引き起こすコードは、特にcreateprofiletable内の単一行です。 resources.getSystem()。 クラス変数を使用してコンテキストを保持して実行する場合 Context.getString(R.String.Create_Profile_Table_sql) エラーはありませんが、メモリリークを避けたいので、それをやりたくありません。何が起こっているのか考えていますか?

役に立ちましたか?

解決

Androidのドキュメントによると、 Resources.getSystem() アプリケーションレベルのリソースではなく、システムレベルのリソースのみを提供します(strings.xmlファイル内のリソースなど)。

http://developer.android.com/reference/android/content/res/resources.html#getsystem()

本当にこの方法で文字列を取得したい場合は、アプリケーションのコンテキストを使用してみてください。または、質問へのコメントで私の提案をしてください。

他のヒント

resources.getSystem()。getSyver()を使用すると、システム全体のリソースのみにアクセスできます(IDにシステム全体のリソースがないため、エラーが発生します)。リソースIDはアプリケーション間で一意ではないため、リソースにアクセスするときにアプリケーションを提供する必要があります。 Androidでは、これはコンテキストを使用して行われます。したがって、いくつかのリソースにアクセスしたい場合は、このように使用する必要があります

context.getResources().getString(myID);

そのブランドンのコメントは別として、正しいです。

パラメーター、または静的変数によって、関数のコンテキストパラメーターを取得できます。 getApplicationContext() 関数。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top