Retrieve Object From Spinner Array And Set It - java

I'm trying retrieve an object from my spinner array and set it to a certain constant, in this case "EFFECT_AQUA"
My array
String[] spinnerValues = {"Aqua", "Mono", "Blackbird", "Negative"};
when the user clicks on the "Aqua" in the spinner I want the screen to change to Aqua.
My spinner is set and called
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
mySpinner.setAdapter(new MyAdapter(this,R.layout.custom_spinner,spinnerValues));
But not sure how should I approach. Seen many different answers but haven't found anything working.
I know my switch will come in this part
class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
}
Any help is appricated!!

If you want to retrieve an object from your spinner array on item click, you can easily do it with the position parameter in the method onItemSelected.
For example :-
class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String itemSelected = spinnerValues[position];
//Set this to a constant
}
}
Now if you select Aqua, then code will set the variable itemSelected to Aqua.
I hope this is what you need

final Spinner cardStatusSpinner1 = (Spinner)findViewById(R.id.text_interested);
String cardStatusString;
cardStatusSpinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
cardStatusString = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
put the code below to get the item first then you can manipulate by taking the values like aqua or any color.
spinner = (Spinner)findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,spinnerValues));
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
TextView tv = (TextView)view;
Toast.makeText(getApplicationContext(), tv.getText().toString(), 5000).show();
switch(tv.getText().toString()){
case "Aqua":{
//change the color to aqua
break;
}
case " ...":{
//
break;
}
//.... for all the option
}
}

Related

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");
}

Spinner Value to String

Been making my first app and slow progress is being made. Just wondering how I return a Spinner value to pass it as a string.
Here is my code:
First the event class:
public void event(){
calanderBtn = (Button)findViewById(R.id.eventBtn);
calanderBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(CalendarContract.Events.TITLE, "Home");
intent.putExtra(CalendarContract.Events.DESCRIPTION, "Cleaning : ");
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, "Home");
startActivity(intent);
}
});
}
Second the Spinner Class:
public void selectcleaning() {
spCleaning = (Spinner) findViewById(spinner);
adapterCleaningType = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cleaningType);
adapterCleaningType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCleaning.setAdapter(adapterCleaningType);
}
I'm trying to select the value from selectcleaning (Value is either Yes or No) and pass it in the descrption in the Calendar of the event class and I'm not sure what to do.
you can use this code to get the value
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
or get the value when spinner selected using OnItemSelectedListener (Android Doc)
public class SpinnerActivity extends Activity implements
OnItemSelectedListener {
#Override
protected void onStart() {
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
You should try using the Overrides for the spinner class as so:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}});
For your purposes 'int position' would equal 0 (yes) or 1 (no)
Try setting an on item selected listener. When an item is selected, you can store that value in a global variable. It gets the first item by default too.
spCleaning.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Value is current spinner item
globalStringVariable = (String) parent.getItemAtPosition(position);
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
// This is default, before you've selected anything.
// It gets the first value.
globalStringVariable = parent.getItemAtPositon(0);
}
});

Reading value from String Array populated using ListView

I've got a ListView which populates a list of quotes from a String Array, however onClick I require the selected <item> to be read to a String. This is the code I use:
ListView sample = (ListView)findViewById(R.id.Samplelist);
String[] backup = getResources().getStringArray(R.array.months);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, backup);
sample.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
#Override
public final void run()
{
String readItem;
finish();
}
});
}
sample.setAdapter(adapter);
}
And here sample.setAdapter(adapter) seems to be an error and is underlined with red.
Is there a way to get this done correct? Any help will be appreciated
If you look at layout of simple_list_item_1 then you can find id of textview is text1.
You can define OnItemClickListener to your listview like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = ((TextView) view.findViewById(R.id.text1)).getText().toString();
}
});
EDIT:
You can also try
String selectedItem = (String)parent.getItemAtPosition(position);
instead of
String selectedItem = ((TextView) view.findViewById(R.id.text1)).getText().toString();
Hope it helps!
You can try this approach:
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
String data=(String)parent.getItemAtPosition(position);
}
});
You may need to parse the text from View in OnItemClickListener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItemText = ((TextView)view).getText().toString();
}
});

Get previously selected item from- Spinner OnItemSelectedListener event

Is there a way that I can get the previously selected item from a ItemSelected event on a spinner? My first thought was to respond to the OnItemClickedEvent, but that method is not supported for spinners.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
MyItem current = (MyItem) parent.getItemAtPosition(position);
//MyItem previous = (MyItem) parent.getPrevious ... how
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
//do nothing
}
});
I'm aware I can just cache the previous value, but it seems like a common operation that there should be a method for.
Use a variable to track the previous item. It would likely be at member of the Activity.
MyItem previous, current;
...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
previous = current
current = (MyItem) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
//do nothing
}
});
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
int prev = comboValues.getSelectedItemPosition();
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
prev=position;
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
}
);
Note that nothing happens if you select an item you have already selected

Event click on ListView (extends ListActivity)

i have this code but i can't see the action when i click on a item from the list.
This code shows me the info on ArrayList profilesArrayList but i dont know how i check what item i am selecting form the listview. Anyone can help me?
profilesArrayList = new ArrayList<Profile>();
profilesArrayList = copyProfilesToArrayList();
ProfileAdapter adapter = new ProfileAdapter(
getApplicationContext(), R.layout.profiles_item, profilesArrayList);
listViewProfiles = (ListView)findViewById(android.R.id.list);
listViewProfiles.setAdapter(adapter);
listViewProfiles.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
switch(position) {
case 0:
Log.d("cardNumber", profilesArrayList.get(0).getCardNumber());
break;
If your container class for this code is the ListActivity, just override the onListItemClick for that class, rather than set it as an OnItemClickListener for the view. That works for me
public class ProfileList extends ListActivity
{
private ArrayList<Profile> profilesArrayList;
#Override
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
//populate your arraylist
setListAdapter ( new ArrayAdapter<Profile>() );
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Log.d("cardNumber", profilesArrayList.get(position).getCardNumber());
}
}
Try to use getSelectedItemPosition() and add INVALID_POSITION as one of your possible cases

Categories