无法从R.string获取字符串资源。* ?

时间:2023-01-20 10:29:08

I have a SQlite table with two columns _id and name. For internationalization purpose I store the name like R.string.today Now I want to get string resource associated with R.string.today:

我有一个带有两个列_id和名称的SQlite表。对于国际化目的,我将名称存储为R.string。今天,我想获取与r .string相关的字符串资源。

String column = myCursor.getString(myCursor.getColumnIndex(MainDb.NAME));

int resId = getApplicationContext().getResources().getIdentifier(column, "strings", getApplicationContext().getPackageName());

String buttonText;

if (resId != 0)
{
  buttonText = getApplicationContext().getString(resId);
} else
{
  buttonText = "Resource is null!";
} 

resId is always 0. Variable column have the right value, I've checked it with debugger. I've tried different variations in resId:

渣油总是0。变量列有正确的值,我用调试器检查过。我在resId中尝试了不同的变化:

  1. "string" instead of "strings" in defType.
  2. 在defType中“string”而不是“string”。
  3. Different variation of getResources like Resources.getSystem()...
  4. 不同的getResources,如Resources.getSystem()……
  5. Different variation of getPackageName()
  6. 不同的变异getPackageName()

What I'm doing wrong?

我做错了什么吗?

2 个解决方案

#1


1  

I think it should be string instead of strings:

我认为它应该是字符串而不是字符串:

int resId = getApplicationContext().getResources()
           .getIdentifier(column, "string", getApplicationContext().getPackageName());

Check as well whether the value of column dsignates an identifier in your strings.xml.

还可以检查列的值是否在您的strings.xml中显示了一个标识符。

This is a nice example.

这是一个很好的例子。

p.s.: instead of R.string.today just store today or extract store from R.string.today.

注。:R.string相反。今天就去商店,或者从r.t。

Resources r = getResources();
r.getIdentifier("today", "string", getPackageName()));
r.getIdentifier("R.string.today", "string", getPackageName())); // doesn't work
r.getIdentifier("R.string.today".replaceAll(".*\\.", ""), "string", getPackageName()));

Only first and third work.

只有第一和第三个工作。

#2


0  

Try this

试试这个

String str = context.getString(R.string.resId);

#1


1  

I think it should be string instead of strings:

我认为它应该是字符串而不是字符串:

int resId = getApplicationContext().getResources()
           .getIdentifier(column, "string", getApplicationContext().getPackageName());

Check as well whether the value of column dsignates an identifier in your strings.xml.

还可以检查列的值是否在您的strings.xml中显示了一个标识符。

This is a nice example.

这是一个很好的例子。

p.s.: instead of R.string.today just store today or extract store from R.string.today.

注。:R.string相反。今天就去商店,或者从r.t。

Resources r = getResources();
r.getIdentifier("today", "string", getPackageName()));
r.getIdentifier("R.string.today", "string", getPackageName())); // doesn't work
r.getIdentifier("R.string.today".replaceAll(".*\\.", ""), "string", getPackageName()));

Only first and third work.

只有第一和第三个工作。

#2


0  

Try this

试试这个

String str = context.getString(R.string.resId);