0

i want to do like let user to add a new item which user can enter item name, item description, item price and so on. let say the name variable stored candy and i have a candy image in my drawable can i do like R.drawable.name to refer to R.drawable.candy?? Anyone help pls

public class item {
    String name;
    String desc;
    double price;
    int itemimage;

    public item(String name, String desc, double price) {
        this.name = name;
        this.desc = desc;
        this.price = price;

        itemimage = R.drawable.name;//my question is here
        //i want to have auto define the image of the item for later use
        // so i can do like set imageview of this item
        //i will have the image have same name with item name
        // for example my item name is candy
        //then i will have a image at the android drawable named candy
        //so in android to define this image is R.drawable.candy
        // can i do like R.drawable.name  <-- variable store with value candy
        // is it same with R.drawable.candy
    }
}//end class item

//another class
public class main {
    Arraylist<item> itemdatabase = new Arraylist<item>();

    Scanner input = new Scanner(System.in);

    System.out.print("Enter item name:");
    String itemname = input.nextLine();

    System.out.print("Enter item desc:");
    String itemdesc = input.nextLine();

    System.out.print("Enter item price:");
    double itemprice = input.nextDouble();

    itemdatabase.add(new

    item(itemname, itemdesc, itemprice);
}
1
  • But you have a lot of statements outside of methods. Didn't the compiler complain about it? Commented Sep 6, 2017 at 15:23

2 Answers 2

1

You can use the Resources.getIdentifier() method. For R.drawable.candy, you'd use it like this:

int id = getResources().getIdentifier("candy", "drawable", getPackageName());
// now `id` == R.drawable.candy

This code assumes you're running inside an Activity. If not, you'll need access to a Context instance so that you can call Context.getResources() and Context.getPackageName(). That might look like this:

int id = mContext.getResources().getIdentifier("candy", "drawable", mContext.getPackageName());
Sign up to request clarification or add additional context in comments.

Comments

0

Answer is No, You can not do like R.drawable.name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.