Can't get string resource from R.string.*

瘦欲@ 提交于 2019-12-12 06:24:25

问题


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:

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:

  1. "string" instead of "strings" in defType.
  2. Different variation of getResources like Resources.getSystem()...
  3. Different variation of getPackageName()

What I'm doing wrong?


回答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.

This is a nice example.

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

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:


Try this

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


来源:https://stackoverflow.com/questions/18503341/cant-get-string-resource-from-r-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!