0

Recently I had an issue very similar to the one described i.e. here: Convert String containing an ID into an Integer-ID.

In short, I had resource identifiers formatted as: R.drawable.picture and wanted to transform them to integer values so that they could be stored in an array and accessed by methods building layouts of my application.

However, following the clues given by Users didn't help to solve my problem, I always ended up with improperly formatted data.

Community
  • 1
  • 1
AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52

1 Answers1

1

Looking for a solution, I came to the one described below.

Details:

  • strings containing resource IDs were kept in a database,
  • full addresses of resources were used to describe them (so, for example: R.drawable.chopin instead of simple chopin - sometimes you may forget what is actually hidden behind a resource: is it a picture or a string it points to? Keeping full identifiers doesn't let you forget about types of these),
  • resource IDs were fetched by a method as strings (also kept in the database as text values) and then parsed into integer identifiers.

Firstly, the context had to be defined:

public DBAdapter(Context context) {
   this.context = context;
   dbHelper = new dbHelper();
}

As I had the context, I could have parsed the strings:

int composerPicture = context.getResources().
        getIdentifier(composerPictureId.substring(11), "drawable",
        context.getPackageName());

and:

int composerName = context.getResources().
        getIdentifier(composerNameAddress.substring(9), "string",
        context.getPackageName());

Pay attention to the quantity of characters we cut off using substring() method. When the ID starts with R.drawable., we have 11 characters and this value has to be cut off. If there is R.string., then we cut off only 9 characters. This way we end up with a pure name of our resource (drawable or string, in this case). The methods assign ID and we have an integer. After that, we can store it in an ArrayList<Integer> or wherever else.

AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52