How can I sum multiple spinners? - java

I have multiple spinners with a string array that has 3 items called "70","80" and "90". After the user selects these different spinner items I want to be able to sum up all of the items which the user has selected and display the total in a textview.For example a user selects "70" from one spinner and "70" from another, a textview will show the total 140. How can I do this?
public class FragmentCalc3 extends Fragment{
Context context;
TextView Results;
public static FragmentCalc3 newInstance()
{
FragmentCalc3 fragment = new FragmentCalc3();
return fragment;
}
public FragmentCalc3() {}
// Required empty public constructor
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_calculator3, container, false);
Results = (TextView) rootView.findViewById(R.id.Results);
context = container.getContext();
final Spinner spinner1 = (Spinner) rootView.findViewById(R.id.TestSpinner2);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(context, R.array.GradeTest, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinner1.setAdapter(adapter1); // Apply the adapter to the spinner
final Spinner spinner2 = (Spinner) rootView.findViewById(R.id.TestSpinner1);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(context, R.array.GradeTest, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinner2.setAdapter(adapter2); // Apply the adapter to the spinner
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int spinner2Value = Integer.parseInt(spinner2.getSelectedItem().toString());
int spinner1Value = Integer.parseInt(spinner1.getSelectedItem().toString());
int Results = spinner2Value + spinner1Value;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
}

If you have two spinners spinner2 and spinner1, And you want to get result when item of spinner2 is selected then simply do like this,
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int spinner2Value = Integer.parseInt(spinner2.getSelectedItem().toString()); //Add try catch block if necessary
int spinner1Value = Integer.parseInt(spinner1.getSelectedItem().toString());
int yourResult = spinner2Value + spinner1Value; //Result
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
//Do nothing
}
});

Related

How to get the values of a spinner into a different fragment?

I'm trying to pass the value of a spinner into a different fragment so that it can be used in a different fragment to convert it to a different unit. I have the code here. I have an onitemselected method which takes the value of the spinner and displays it at the bottom of the application.
Any help would be appreciated.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
String[] values =
{"Select Units:", "Miles", "Kilometers", "Meters", "Yards",};
final Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
String[] values1=
{"Select Units:", "Miles", "Kilometers", "Meters", "Yards",};
Spinner spinner1 = (Spinner) view.findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values1);
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(this);
button1 =view.findViewById(R.id.button_confirm);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = spinner.
}
});
return view;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
How to transfer some data to another Fragment?
In your fragment that creates the data, store it in a bundle and send it to the next fragment via arguments, then in a method which takes a bundle (like onCreateView), use the value that is found in the bundle.

Unable to get Second Spinner value based on first Spinner Value

I'm using Two Spinners where Second Spinner Value is based on First Spinner Value.
For Example If user Select Option A in First Spinner Then Second Spinner drop down list must contain value ( ox, cow, goat ) and if user select option B, then second Spinner value must contain ( Lion, Tiger and Cheetha ).
But I'm unable to do so. On selecting any value in first spinner value, Second Spinner always loads same value. Below is the screenshot
As you can see, In selecting any option in first spinner master or diploma...In second spinner value is same.it does not change.
Below is my Activity Code
public class UploadBook extends AppCompatActivity
Spinner spinnerCountry,spinnerDivision,spinner_condition;
ArrayAdapter<String> countryArray,divisionArray;
String item = "start";
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_book);
getSupportActionBar().setTitle("Upload book");
spinnerCountry = (Spinner) findViewById(R.id.spinnerCountry);
//implementing OnItemSelectedListener (need to override the method)
spinnerCountry.setOnItemSelectedListener(this);
countryArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
countryArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(countryArray);
countryArray.add("Master");
countryArray.add("Diploma");
countryArray.setNotifyOnChange(true);
spinnerCountry.setSelection(0);
spinnerDivision = (Spinner) findViewById(R.id.spinnerDivision);
//implementing OnItemSelectedListener (need to override the method)
spinnerDivision.setOnItemSelectedListener(this);
divisionArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
divisionArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDivision.setAdapter(divisionArray);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
count = position;
//first spinner item position
int countrySpinnerPosition = spinnerCountry.getSelectedItemPosition();
switch (countrySpinnerPosition){
case 1:
//fill data for second spinner
fillMasterDivision();
break;
case 2:
//fill data for second spinner
fillDiplomaDivision();
break;
}
}
private void fillMasterDivision() {
divisionArray.clear();
divisionArray.add("Select Subject:-");
divisionArray.add("MSC Physics");
divisionArray.add("MSC Chemistry");
divisionArray.notifyDataSetChanged();
}
private void fillDiplomaDivision() {
divisionArray.add("Select Subject:-");
divisionArray.add("Science");
divisionArray.add("CTEVT");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
Please Help.
There is two mistake in your code.
CountrySpinnerPosition will be 0 and 1 for your case so the case should be "case 0" and "case 1".
In fillDiplomaDivision method, you have to first clear the list and after adding into the list you have to call notifyDataSetChanged().
try to clear the arraylist and notifydatasetchanged in second method too
private void fillDiplomaDivision() {
divisionArray.clear();
divisionArray.add("Select Subject:-");
divisionArray.add("Science");
divisionArray.add("CTEVT");
divisionArray.notifyDataSetChanged();
}
First of all ,you are using same onItemSelected for both the spinner . so remove spinnerCountry.setOnItemSelectedListener(this); and spinnerDivision.setOnItemSelectedListener(this);
After setting data to spinnerCountry use this .
spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i == 0){
fillMasterDivision();
}else{
fillBachelorDivision();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
and clear your Division array in fillBachelorDivision()
See my example:
I have 2 spinners, firstSpinner and secndSpinner, Second depends of First.
First you have to initialize the spinners in onCreate method, and follow steps:
1 - You'll insert in first spinner your data ("Master", "Diploma");
2 - You'll create a function that will update the second spinner with associated values.
firstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
createSecondSpinnerByFirst(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
});
private void createSecondSpinnerByFirst(Integer position) {
List<String> secValues = new ArrayList<>();
switch (position) {
case 1:
// insert in secValues array the strings of this condition
break;
case 2:
// insert in secValues array the strings of this condition
break;
}
// usually I use Adapter
final SpinnerAdapter adapter = new SpinnerAdapter(this, secValues);
secndSpinner.setAdapter(adapter);
}
//Code of myAdapter
public class SpinnerAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> mValues;
public SpinnerAdapter(Context ctx, List<String> values) {
super(ctx, 0, values);
context = ctx;
mValues = values;
}
#Override
public int getCount() {
return mValues.size();
}
#Override
public Process getItem(int position) {
return mValues.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return returnLayoutSpinner(context, convertView, mValues.get(position));
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return returnLayoutSpinner(context, convertView, mValues.get(position));
}
}
//My function to return the adapter view
private View returnLayoutSpinner(Context context, View convertView, String value) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(
R.layout.spinner_items_view, null);
}
TextView txt = convertView.findViewById(R.id.txtSpinnerItem);
txt.setText(value, 25);
return convertView;
}
//spinner_items_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/txtSpinnerItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|left"
android:padding="13dp"
android:textColor="#android:color/black"
android:textSize="16sp">
</TextView>
private void fillDiplomaDivision() {
//add this line in your code and it solve
divisionArray.clear();
divisionArray.add("Select Subject:-");
divisionArray.add("Science");
divisionArray.add("CTEVT");
}

Check item selected on two spinners?

I have two spinners on my layout as below:
public class DemoActivity extends Activity {
private static final String STATE_SCALE = "state-scale";
private static final String STATE_CENTER_X = "state-center-x";
private static final String STATE_CENTER_Y = "state-center-y";
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
String text1 = spinner1.getSelectedItem().toString();
Spinner spinner3 = (Spinner) findViewById(R.id.spinner3);
String text3 = spinner3.getSelectedItem().toString();
if (text1.equals("Harris Academy"))
Harris(spinner1);
if (text1.equals("Harris Academy") && text3.equals("Ground Floor")) {
Toast.makeText(getBaseContext(), text3, Toast.LENGTH_LONG).show();
try {
SubsamplingScaleImageView imageView =
(SubsamplingScaleImageView) findViewById(id.imageView);
imageView.setImageAsset("DSC00277.png");
if (savedInstanceState != null &&
savedInstanceState.containsKey(STATE_SCALE) &&
savedInstanceState.containsKey(STATE_CENTER_X) &&
savedInstanceState.containsKey(STATE_CENTER_Y)) {
imageView.setScaleAndCenter(savedInstanceState.getFloat(STATE_SCALE),
new PointF(savedInstanceState.getFloat(STATE_CENTER_X),
savedInstanceState.getFloat(STATE_CENTER_Y)));
}
} catch (IOException e) {
Log.e(DemoActivity.class.getSimpleName(), "Could not load asset", e);
}
}
}
}
This works fine when the app starts it gets the value of spinner 1 and spinner 3 and then does something depending on the values.
How do I extend it so that when I select an item on either spinner it does something based on the new values?
To get updated value as user select item from spinner,
You have to implement spinner's onItemSelectedListner
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// Do your stuff here for spinner1
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// Do your stuff here for spinner3
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
If you want to manipulate views or data on the selection of item in Spinner you need to implement
ItemSelectedListener to the particular Spinner.
Sample Code:
// in onCreate() or where you want to bind this Views with XML views
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner3 = (Spinner) findViewById(R.id.spinner3);
// mItemSelectedListener Object of OnItemSelectedListener to handle Item Selection to Spinners.
spinner1.setOnItemSelectedListener(mItemSelectedListener);
spinner3.setOnItemSelectedListener(mItemSelectedListener);
}
// Creating an Object of Anonymous Class so no need to create another instance for same class
// OutSide of onCreate() method.
OnItemSelectedListener mItemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (view.getId()) {
case R.id.spinner1:
// Manipulates Views at selection of item in Spinner1
break;
case R.id.spinner3:
// Manipulates Views at selection of item in Spinner3
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};

How to get values of the Spinners displayed in ListView?

I have been trying to solve this simple problem for two days now without success. I know a similar question have been asked before (like here:
How do you get the selected value of a Spinner? ), but I haven't been able to solve this yet.
So, I have created a simple app which contains a spinner and a custom ListView. The spinner (containing values 1,2,3,4,5..) creates more spinners (which contain Player names) to the ListView (eg. choosing 4 creates four spinners). Currently, the program works fine except that I don't know how to get the selected values of the spinners in ListView when clicking a button in Action Bar? I tried to use getItemAtPosition and getSelectedXXX() methods but I always tend to the get values from a single spinner I recently selected.
I am not sure do I have to invoke the methods in the Spinner's setOnItemSelectedListener(), or can I call the values from outside the SpinnerAdapter class.
Here is the custom Spinner class
public class PlayerAdapter extends ArrayAdapter<String> {
public PlayerAdapter(ArrayList<String> mPlayers) {
super(getActivity(), 0, mPlayers);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_players, null);
}
Spinner mSpinnerPlayer = (Spinner) convertView
.findViewById(R.id.spinner_player);
ArrayAdapter<Player> spinnerAdapterPlayer = new ArrayAdapter<Player>(getActivity(), android.R.layout.simple_spinner_item, mPlayers);
spinnerAdapterPlayer.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerPlayer.setAdapter(spinnerAdapterPlayer);
mSpinnerPlayer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
//Should I use getItemAtPosition or getSelectedXXX methods here?
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
return convertView;
}
}
}
Here is the Fragment which inflates the layout creates the first spinner (sorry about the formatting and code style)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
//gets player names from a database, such as "Player 1", "Player 2" etc..
//this is container of the spinners displayed in the listview
mPlayers = PlayerDB
.get(getActivity())
.getPlayers();
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_menu, parent, false);
listView = (ListView) view.findViewById(R.id.listView1);
mSpinnerNumOfPlayers = (Spinner) view.findViewById(R.id.spinner_numOfPlayers);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter
.createFromResource(this.getActivity(),
R.array.numberOfPlayers_array,
android.R.layout.simple_spinner_item);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerNumOfPlayers.setAdapter(spinnerAdapter);
mSpinnerNumOfPlayers.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String position = parent.getItemAtPosition(pos).toString();
mArray = new ArrayList<String>();
posInt = Integer.parseInt(position);
for (int i = 0; i < posInt; i++) {
mArray.add("" + i);
}
PlayerAdapter adapter = new PlayerAdapter(mArray);
listView.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
}
);
return view;
}
// ActionBar
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_start:
//when "start" button is clicked the spinner values are saved into an ArrayList
This method will retuns you the selected ite from the spinner..
spinner.getSelectedItem().toString()

Android Spinner OnItemSelect doesnt work

I have three different Spinner objects (two of them have a custom layout, one - spMode - is standard).
When the OkayButton is pressed, a Toast should be displayed with 3 Numbers: the SpinnerItemNumber of Mode, Color1 and Color2. But Mode is 0 each time the button is pressed. The others work fine. Just Mode is showing that item 0 is selected even if I select Item 2 or 3 in the App.
Here is the relevant code; any ideas why?
public class NewTimer extends Activity implements OnItemSelectedListener,OnClickListener
{
Button btnOkay;
EditText etTime;
int mode, minutes, color1, color2;
String[] strings = {"","",
"", "", "", ""};
int arr_images[] = { R.drawable.yellow,
R.drawable.orange, R.drawable.red,
R.drawable.blue, R.drawable.green, R.drawable.white};
public void onClick(View v)
{
if (v == btnOkay)
{
Toast.makeText(v.getContext(), Integer.toString(mode) + Integer.toString(color1) + Integer.toString(color2), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newtimer);
Spinner spColor1 = (Spinner)findViewById(R.id.spColor1);
spColor1.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor1.setOnItemSelectedListener(this);
Spinner spColor2 = (Spinner)findViewById(R.id.spColor2);
spColor2.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor2.setOnItemSelectedListener(this);
etTime = (EditText) findViewById(R.id.etTime);
btnOkay = (Button) findViewById(R.id.btnOkay);
btnOkay.setOnClickListener(this);
Spinner spMode = (Spinner) findViewById(R.id.spMode);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spMode_items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMode.setAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent,
View v, int pos, long id)
{
switch (parent.getId())
{
case R.id.spMode:
mode = pos;
break;
case R.id.spColor1:
color1 = pos;
break;
case R.id.spColor2:
color2 = pos;
break;
}
}
public void onNothingSelected(AdapterView<?> parent)
{
}
public class MyAdapter extends ArrayAdapter
{
public MyAdapter(Context context, int textViewResourceId,
String[] objects)
{
super(context, textViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater=getLayoutInflater();View row=inflater.inflate(R.layout.row, parent, false);
TextView label=(TextView)row.findViewById(R.id.color);
label.setText(strings[position]);
ImageView icon=(ImageView)row.findViewById(R.id.image);
icon.setImageResource(arr_images[position]);
return row;
}
}
}
You never set the setOnItemSelectedListener for that spinner:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newtimer);
Spinner spColor1 = (Spinner)findViewById(R.id.spColor1);
spColor1.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor1.setOnItemSelectedListener(this);
Spinner spColor2 = (Spinner)findViewById(R.id.spColor2);
spColor2.setAdapter(new MyAdapter(NewTimer.this, R.layout.row, strings));
spColor2.setOnItemSelectedListener(this);
etTime = (EditText) findViewById(R.id.etTime);
btnOkay = (Button) findViewById(R.id.btnOkay);
btnOkay.setOnClickListener(this);
Spinner spMode = (Spinner) findViewById(R.id.spMode);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spMode_items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMode.setAdapter(adapter);
spMode.setOnItemSelectedListener(this); }
public void onItemSelected(AdapterView<?> parent,
View v, int pos, long id) {
switch (parent.getId())
{
case R.id.spMode:
mode = pos;
break;
case R.id.spColor1:
color1 = pos;
break;
case R.id.spColor2:
color2 = pos;
break;
} }

Categories