0

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?

Trinimon
  • 13,839
  • 9
  • 44
  • 60
Sergey Grabak
  • 183
  • 1
  • 12

2 Answers2

2

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.

Community
  • 1
  • 1
Trinimon
  • 13,839
  • 9
  • 44
  • 60
0

Try this

String str = context.getString(R.string.resId);
Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57