13
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内の1行です。具体的には、クラス変数を使用してContextを保持し、context.getString(R.string.create_profile_table_sql)を実行する場合、 Resources.getSystem()。getString(R.string.create_profile_table_sql)です。エラーは発生しませんが、メモリリークを回避したいので、エラーは発生しません。これは、動作するはずです。何が起こっているのか分かりますか?

4

3 に答える 3

30

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

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

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

于 2012-01-14T17:50:24.363 に答える
7

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

context.getResources().getString(myID);

それを除けば、ブランドンのコメントは正しいです。

于 2012-01-14T17:52:39.897 に答える
1

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

于 2012-01-14T20:48:10.980 に答える