-1

I have a method in a Fragment that takes a value from a quantity Spinner and returns it. Where can I retrieve the value of this variable? If I want to move it to a new Activity altogether, how can I retrieve it there?

public String SetupQuantitySpinner(String[] quantity) {
    Spinner spnr2;
    spnr2 = (Spinner)view.findViewById(R.id.spinner_quantity);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getActivity(),
            R.layout.custom_spinner,
            R.id.text_main_seen,
            quantity);
    spnr2.setAdapter(adapter);
    return quantity[spnr2.getSelectedItemPosition()];
}

Basically the Spinner represents the quantity of the item that a user has decided to purchase, i.e. 1 to 20 shirts. I now have to multiply this value by its cost, but the cost is retrieved in another Activity altogether:

String cost = currentProduct.getCost();

I need to send quantity[spnr2.getSelectedItemPosition()] to this new Activity so that I can multiply it by currentProduct.getCost();

How can I accomplish this?

Edit: This is different and hence not a duplicate because I only want to send and retrieve data associated with the selected Spinner item.

Martin Erlic
  • 5,467
  • 22
  • 81
  • 153

2 Answers2

3

If you want to retrieve only selected item in another activity then you can simply put this code inside onItemSelected method. And retrieve the value of extra in that activity.

String item = mSpinner.getSelectedItem().toString();
Intent intent = new Intent(this,NextActivity.class);
intent.putExtra("item",item);
startActivity(intent);
Dhrumil Patel
  • 544
  • 6
  • 16
0

This is another way to do it. Write a global variable:

public final static String PRODUCT_SIZE_MESSAGE = "com.elgami.customizer.PRODUCT_SIZE";

Start your Intent where you want to in your code:

Intent intent;
intent.putExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, productQuantity);
startActivity(intent);

You put the variable you want to send along with your Intent in the Extra, and then retrieve it in the new Class as follows:

private int getIntentMessageProductQuantity() {
    return getIntent().getIntExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, 0);
}

Now you have that variable and you can use it as a parameter in any method in the new Class, like so:

public void LaunchPurchaseIntent(MainActivity.ProductType productType, int productSize, int productQuantity, String uuid) throws ParseException {
    // Do what you want here

}
Martin Erlic
  • 5,467
  • 22
  • 81
  • 153