how to set the Image.setImageResource from a string

0

I have this code and I would like to know how to do what I am trying to do

   public void SetImage(Cursor c){


    c.moveToNext();
    c.getString(12);

    im1.setImageResource( c.getString(12));      
}

I explain, in a database I have a table that contains the following:

  string:"R.drawable.ic_launcher_background",

of that database I take out a cursor with all the fields of a table and all its data, well, the c.getString (12) pulls out that string and what I want is to put that photo in the image

    
asked by Aurelio Fernandez 08.04.2018 в 18:45
source

1 answer

0

To make it more visible we will obtain the path in string format within an array.

String[] strRutas = {"R.drawable.image1","R.drawable.image2","R.drawable.image3","R.drawable.image4",
                "R.drawable.image5","R.drawable.image6","R.drawable.eliminar","R.drawable.image8"};

In my case I will get this route or string in question "R.drawable.eliminar" .

String string = strRutas[6]; //"R.drawable.eliminar";

Now I'm going to chop this String to get just the word eliminar

String[] trozosStr = string.split("\.");
String trozo3 = trozosStr[2];

And already with this portion of code we complete the rest. Say also that you have to use setImageDrawable() instead of setImageResource()

        String uri = "@drawable/"+ trozo3;
        int imageResource = getResources().getIdentifier(uri, null, getPackageName());
        Drawable imagenDra = ContextCompat.getDrawable(getApplicationContext(), imageResource);
        imagen.setImageDrawable(imagenDra);

Result:

P.d. Finally say that it depends on the ability of each one to implement it in a method and to make it easier.

    
answered by 09.04.2018 / 11:43
source