Save spinner state even moved to another activity with Android - android

I want to save my spinner state even when I move to a different activity and come back to the page with the spinner, the state should be the same. I have no idea how to do it, I saw some examples on other threads on stack overflow but I don't understand them.
Here's my code:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
index = arg0.getSelectedItemPosition();
// storing string resources into Array
lang_list = getResources().getStringArray(R.array.language_list);
Toast.makeText(getBaseContext(), "You have selected : " + lang_list[index],
Toast.LENGTH_SHORT).show();
choice = spinner.getSelectedItem().toString();
// edit_cate.setText(choice);
final ImageView country_flag = (ImageView)findViewById(R.id.country);
String s=((TextView)arg1).getText().toString();
if(s.equals("English"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.eng_spinner));
if(s.equals("German"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.german_spinner));
if(s.equals("French"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.french_spinner));
if(s.equals("Spanish"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.spanish_spinner));
}
Thanks for the help.

You need to save state of your spinner so this would be helpful to you.
1.) Apply this after creating spinner object
spinner.setSelection(getPersistedItem());
2.) Create these methods according to you to save the state of your spinner selected item
private int getPersistedItem() {
String keyName = makePersistedItemKeyName();
return PreferenceManager.getDefaultSharedPreferences(this).getInt(keyName, 0);
}
protected void setPersistedItem(int position) {
String keyName = makePersistedItemKeyName();
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(keyName, position).commit();
}
private String makePersistedItemKeyName() {
return currentUserName + "_your_key";
}
3.) Set its state as the spinner selection changed:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View view, int position, long itemId) {
setPersistedItem(position);
} #Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });

Related

How to access listview items generated by arrayadapter

I have tied my application to Firebase database and after being able to display them I also want to be able to select them and access their textview values. However .getValue() does not work for views. I know that my code is very messy and my selector is only working one way, but can you help me to find out what is going on. I will add a screenshot to make things more clear. At the moment when clicking on one of the items int num = Integer.parseInt(text) gives an error and the app will crash because the value I get from view is "Android.widget...", not what I want to get.
Screenshot pic:
Orders.java
public class Orders extends ActionBarActivity {
public final static String TOTAL_SUM = "com.nordscript.checkmate.SUM";
// Declare the UI components
private ListView foodList;
// Declare an ArrayAdapter that we use to join the data set and the ListView
// is the way of type safe, means you only can pass Strings to this array
//Anyway ArrayAdapter supports only TextView
private ArrayAdapter arrayAdapter;
private Firebase ref;
private Orders activ;
private ArrayList<String> dishes;
public int total;
#Override
protected void onCreate(Bundle savedInstanceState) {
activ = this;
dishes = new ArrayList<String>(20);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
// Initialize the UI components
foodList = (ListView)findViewById(R.id.listView1);
// Create a reference to a Firebase location
ref = new Firebase("https://xxxxxxxxxx.firebaseio-demo.com/Restaurants/Restaurant 2/Tables/Table 2/Orders");
// Read data and react to changes
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
Map s = snapshot.getValue(Map.class);
dishes.add(snapshot.getName() + " " + ((Map)snapshot.getValue(Map.class)).get("Price"));
Log.i("Test", dishes.toString());
arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());
// By using setAdapter method, you plugged the ListView with adapter
foodList.setAdapter(arrayAdapter);
}
#Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { }
#Override public void onChildRemoved(DataSnapshot snapshot) {
Map s = snapshot.getValue(Map.class);
dishes.remove(snapshot.getName() + " " + ((Map)snapshot.getValue(Map.class)).get("Price"));
Log.i("Test", dishes.toString());
arrayAdapter = new ArrayAdapter(activ, android.R.layout.simple_list_item_1, dishes.toArray());
// By using setAdapter method, you plugged the ListView with adapter
foodList.setAdapter(arrayAdapter);
}
#Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { }
#Override
public void onCancelled(FirebaseError arg0) { }
});
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = view.toString();
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.orders, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void toPayment(View view) {
Intent pay = new Intent(this, PaymentMethod.class);
pay.putExtra(TOTAL_SUM, total);
startActivity(pay);
}
}
What i understand from your question : Suppose when you click on 3rd item i.e "pudding 8", you want this value "pudding 8"(textview value). right??
If that so than you just have to get values from your ArrayList which you pass to the adapter on first place with the help of position attribute inside your setOnItemClickListener like this :
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = dishes.get(position);
// do what you want to do with this value.
}
});
Change your onClickListener() like that:
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = (String)parent.getItemAtPosition(position);
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
Or you can use SimpleAdapter for displaying string and integer values separately using two textviews in a separate xml layout. Using that you can get values on onclick() in a better way.
You need to gettext of that particular view, view.getText().toString();
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setBackgroundColor(Color.GREEN);
String text = view.getText().toString();
text.replaceAll("[^\\d.]", "");
int num = Integer.parseInt(text);
total += num;
}
});
It may help you, but it is bad way:
foodList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) arrayAdapter.getItem(position);
String[] split = item.split(" ");
int num = Integer.parseInt(split[1]);
total += num;
}
});
But it is very urge...
As for me, you need to extends Adapter, to collect into it your custom items, and after clicking gets it and takes integer value you need.
I know this might become a little too late but, hope this
helps someone who was looking for similar solution to Custom ArrayAdapter with multiple values.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListItems item = (ListItems) parent.getItemAtPosition(position);
System.out.println("Item: "+item.getName());
}
});

converting selected spinner value to defined int variable : android

I have an android program in which there is a spinner. i am getting the selected spinner value. i am able to send it as json too.
The problem is i want to send 1 if option1 is selected , 2 if option two is selected and so on.
Is there a method the selected value is converted to int value of my choice before i send it as json ?
the code is
public void addItemsOnSpinner1() {
s1 = (Spinner) findViewById(R.id.spinnerL);
List<String> list = new ArrayList<String>();
list.add("Casual");
list.add("Earned");
list.add("Compensatory");
list.add("Without Pay");
list.add("Sick Leave");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(dataAdapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
// Toast.makeText(getBaseContext(), s5.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
final String SelectedLeave = s1.getSelectedItem().toString();
balanceLeavesLeft();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
the 3rd param is the position of selected item of your spinner:
It's arg2 in your code
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
// Toast.makeText(getBaseContext(), s5.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
final String SelectedLeave = s1.getSelectedItem().toString();
balanceLeavesLeft();
}
--> So you just need print out: (arg2+1)
tauitdnmd, answer is good but, the best way should be that you have an Entity class Opion as example and you have the string value for it and the int value of the selected row :) that's how is done usually.
public class YourOptionClass {
private String optionName;
private int optionValue;
//construktor
//getter and setter
//to string
}
And you populate your spinner with this class.
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3){
int option = YourAdapterClass.getItem(pos).getOptionValue();
}

How to maintain spinner selected state in android

I just wanna maintain spinner selected state in android.I've an activity A which retrieves data from webservice & popped into spinner.After select any one item from that and goes to another activity B.Once back to activity A.,i need to show selected item on spinner without go to web call again.
My Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinner = (Spinner) findViewById(R.id.spinner);
if(spinnerFlag=1){
spinner.setSelection(index);
}
else{
//Web call for spinner data
}
...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int arg2, long arg3) {
String seletcedProductName = parent.getSelectedItem()
.toString();
spinnerFlag=0;
index=arg2;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Thanks.
Just save the index in SharedPreferences on activity stop, retrieve it when you return to that activity.
Shared Preferences at Android Developer
You can save selected index of spinner in static variable, initialized with -1, and onResume check the value of that variable, if it's not -1, then set the selected index of spinner with it.
static int position=-1;
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int arg2, long arg3) {
String seletcedProductName = parent.getSelectedItem()
.toString();
spinnerFlag=0;
index=arg2;
position=arg2;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
#Override
protected void onResume() {
super.onResume();
if(position!=-){
spinner.setSelection(index);
}
}

How to get spinner control selected id

I've a spinner control that I connected it via a dataadapter and I get the data through it .
in the class, I want to get the selected spinner control's id .
How can I do that ?
I've used this code but when I run it , it says there's a problem and it closed .
Toast toast=Toast.makeText(MainActivity.this,sp.getSelectedItemId(),5000);
toast.setGravity(Gravity.CENTER,100, 0);
toast.show();
I tried getSelectedItemId and getSelectedItemPosition but non of them worked .
Here the answer for your question
ArrayAdapter<String> adpt = new ArrayAdapter<String>this,android.R.layout.simple_spinner_item, strType);
adpt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnType.setAdapter(adpt);
spnType.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
int intItemType = spnType.getSelectedItemPosition();
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
This the line getting selected position of the spinner
int intItemType = spnType.getSelectedItemPosition();
Try this
//Spinner OnItemClick Event here
payfeeTabStudentNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String spinnerSelectedValue = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Please let me know your problem is resolved or not.

Spinner item gets automatically selected upon entering activity. How do I avoid this?

I have a spinner in my Android app, and its onItemSelected() event automatically gets triggered upon entering the activity.
How do I avoid this?
We can use a flag, and just enable it when the spinner is really touched.
private boolean isSpinnerTouched = false;
spinner.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
isSpinnerTouched = true;
return false;
}
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View arg1,
int arg2, long arg3) {
if (!isSpinnerTouched) return;
// do what you want
}
});
To add on Jerry Abraham, You should clear selection before enabling setOnItemSelectedListener
Spinner mSpinner=(Spinner)findViewById(R.id.mySpinner);
int initialSelectedPosition=mSpinner.getSelectedItemPosition();
mSpinner.setSelection(initialSelectedPosition, false); //clear selection
mSpinner.setOnItemSelectedListener(this); //set listener after clearing section
I have solved this issue,
You can avoid this issue by not setting any default values to the spinner
int initialposition=spinner.getSelectedItemPosition();
spinner.setSelection(initialposition, false);
This will avoid entering into onItemSelected()
There are no any way to avoid this.
You may add some flag, indicating readiness of your application and use it in your onItemSelected() method to decide, what to do in each case.
Well, you can add a dummy selection to the initial adapter, and ignore position number in the setOnItemSelectedListener. It's not pretty but it works. See this code for setting up the items for an array adapter.
List<String> names = new ArrayList<String>();
names.add("");
names.addAll(realValues);
Then in your setOnItemSelectedListener you can do this:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
if (position > 0)
{
String name = names.get(position - 1);
}
else
{
Log.d(TAG, "selected nothing or perhaps the dummy value");
}
}
I have found a solution for this problem and posted it here (with code sample):
Spinner onItemSelected() executes when it is not suppose to
Simple and easy is this...
validate with a boolean to see if is first time...
Spinner mySpinner = (Spinner)findViewById(R.id.spinner_xml_pro);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(isSpinnerInitial){ // globar var boolean isSpinnerInitial = false;
//do something
}else
isSpinnerInitial=true;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Check this with spinner.post(new Runnable()...)
or this other my source
I think that you can use spinner position which is a better approach in my opinion.
Create a global variable where you store the spinner position, in onItemSelected method the position is provided you can compare them, if they are the same do not make an action.
private int spinnerPosition; \\ Global variable
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
if(spinnerPosition != position){
// Do whatever you like
// Do not forget to save the new position
spinnerPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
You can avoid it by ignoring the first click by,
private boolean isSpinnerInitial = true; //As global variable
public void onItemSelected(xxx xxx, xxx xxx, xxx xxx, xxx xxx) {
if(isSpinnerInitial) {
isSpinnerInitial = false;
return;
}
// Write your code here
}

Categories

Resources