How to pass a String argument so it becomes part of a class method call?

Viewed 66

I am wondering how to pass the string arguments in the convert_and_multiply method into the findViewById method, so that the string becomes part of the method call, and no longer a String. For example I would like to pass the argument "fruit_1_price" such that it becomes findViewById(R.id.fruit_1_price);

I was reading about "reflection" in Java, but I could not fully understand it, and whether it applied to my situation. I also tried using String wildcards and place holders, but I cannot understand how to make a String, not a String anymore.

Thank you for any help.

        @Override
        public void onClick(View view) {
            Double fruit_1_total = convert_and_multiply("fruit_1_price", "fruit_1_spinner");//, fruit_2_total, fruit_3_total;

            Toast.makeText(c, Double.toString(fruit_1_total),Toast.LENGTH_LONG).show();
        }

        public double convert_and_multiply(String v, String s) {
           TextView price = findViewById(R.id.v);
           Spinner amount = findViewById(R.id.s);
           Double total = Double.valueOf(amount.getSelectedItem().toString()) * Double.parseDouble(price.getText().toString());

          return total;
        }
2 Answers

Change your method to this code :

public double convert_and_multiply(String v, String s) {
    Resources res = getResources();
    int id1 = res.getIdentifier(v, "id", getContext().getPackageName());
    TextView price = findViewById(id1);

    int id2 = res.getIdentifier(s, "id", getContext().getPackageName());
    Spinner amount = findViewById(id2);

    Double total = Double.valueOf(amount.getSelectedItem().toString()) * Double.parseDouble(price.getText().toString());

    return total;
}

Why do you want to complicate it? Pass the id directly to the convert_and_multiply function :

@Override
        public void onClick(View view) {
            Double fruit_1_total = convert_and_multiply(R.id.v, R.id.s);//, fruit_2_total, fruit_3_total;

            Toast.makeText(c, Double.toString(fruit_1_total),Toast.LENGTH_LONG).show();
        }

        public double convert_and_multiply(int priceId, int amtId) {
           TextView price = findViewById(priceId);
           Spinner amount = findViewById(amtId);
           Double total = Double.valueOf(amount.getSelectedItem().toString()) * Double.parseDouble(price.getText().toString());

          return total;
        }
Related