How to maintain spinner selected state in android - 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);
}
}

Related

Passing Value from Spinner setonItemSelectedListener

I am trying to get the position of a spinner item and pass it into another method. To achieve this I have declared a spinner in MainActivity and set onItemSelectedListener method(to get the position based on user click). Now I want to pass the value from the onItemselectedListener method to another method getItem(). But the value recieved at getItem() is always null. I have attached my code for further reference.
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String[]array={"I","Me","Myself"};
String abc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner= (Spinner) findViewById(R.id.spinner);
spinnerAdapter adapter=new spinnerAdapter(MainActivity.this,android.R.layout.simple_spinner_dropdown_item);
adapter.addAll(array);
adapter.add("Select Here");
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount());
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
abc= String.valueOf(spinner.getSelectedItemPosition()+1);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
getitem();
}
public void getitem()
{
Log.e("MSG",abc);
}
}
From Android dev website:
Responding to User Selections
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
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
}
}
From parent.getItemAtPosition(pos) you can then get the string value and pass it to another activity if you wish.

Save spinner state even moved to another activity with 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
} });

Set Text based on list item click

I am having a layout consisting of ListView and a label. Look at the image below.
I implemented listview using base adapter in a seperate .java file.
Could anyone suggest me how can i set text to the label on click of list item?
EDITED :
The text of the label should be number of list items clicked.
Suppose i clicked a button in a list item, the label should be set to 1.
Similarly in the next attempt if i clicked another list item's button it should be set to 2 and so.. on..
Sir,
What you are saying is this, you have your adapter in one class and the activity in another file. Well you could do this, to update the textview.
pass the context to the activity, and if its in the adapter you are maintaining the count then once the count has been updated,
then, assume you have this method in the activity
public void updateTextView(int count) {
// enter your code here to set the count in the textview
}
and from the baseAdapter call the above method like this:
if(mContext != null) {
((YourActivity)mContext).updateTextView(mCount);
}
and the textview in the activity will be updated!
I hope it helps.
In your OnItemClickListener call adapter.getItem(int position) to retrieve the object from the collection backing your BaseAdapter. From there, you should be able to retrieve any fields you need.
Edit:
Your edit clears up the question. Updated answer:
private int mCounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ListView listView = getYourListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCounter++;
updateTextView();
}
});
if(savedInstanceState != null) {
mCounter = savedInstanceState.getInt("counter", 0);
}
updateTextView();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter", mCounter);
}
private void updateTextView() {
// TextView textView = getYourTextView();
textView.setText(String.valueOf(mCounter));
}
Just OnItemClickListener in your ListView then in the onClick you will get a value arg2 which is the position of the item which is clicked.
Just get that value from the ArrayList from which you are displaying the ListView and show it...
Hope this is what you need if I have not misunderstood your question.
try this code
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String itemText=(String) arg0.getItemAtPosition(arg2);
yourLable.setText(itemText);
}
});
In onListItemClick call list.getItemAtPosition(position) to retrieve item text
then set this text to textview1.setText(listText).
First Implement your onItemClickListener, where you will get int arg2 parameter, which is position, so get that position and do your stuff whatever you want like below.
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
LABLE.setText(""+arg2);
}
});
Check this code
public class ListA extends ListActivity {
private TextView selection;
private static final String[] items={"Item 1", "Item 2", "Item 3"};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
selection=(TextView)findViewById(R.id.selection);
}
#Override
public void onListItemClick(ListView parent, View v, int position,
long id) {
selection.setText(position);
}
}

How can I click a button to launch an ItemSelected event of spinner control?

I have a spinner control with setOnItemSelectedListener in my app, when I select an item of the spinner, the event onItemSelected will be launched.
Now I hope to click a button to launch the onItemSelected event, how can I do? Thanks!
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
//Do Business Logic
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Just call the following from your button listener:
spinnerFolder.getOnItemSelectedListener().onItemSelected(spinnerFolder, spinnerFolder.getSelectedView(), spinnerFolder.getSelectedItemPosition(), spinnderFolder.getSelectedItemId());
That's all :-)
The third parameter (int arg2) of onItemSelected for your spinner is the position, so you can get the current selection by
String selection = (String) mSpinnerAdapter.getItem(position);
or use mSpinner.getItemAtPosition(position) if you don't have a custom adapter.
Store the current selection somewhere and pick it up in the onClickListener for your button.
When you populate the spinner with some data, you will have some sort of list objects (Strings, custom object, whatever) in the SpinnerAdapter, you'll keep a reference to that list, let's call it: private List<Object> dataList = ...
First of all I would create a method that would handle the specific data object:
protected void doBusinessLogic(Object myObj) {
// do the things that make you happy
}
Then call this from listener as:
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// args2 is the position from backed data list
doBusinessLogic(dataList.get(args2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Then from button listener you would call above method again, but the object index you would get is from spinnerFolder.getSelectedItemPosition();:
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int dataIndex = spinnerFolder.getSelectedItemPosition();
doBusinessLogic(dataList.get(index));
}
});

Adding OnItemSelectedListener to Spinner

I have a button and a spinner (originally hidden). When user presses a button, spinner gets populated with items and becomes visible. Now I would like to add OnItemSelectedListener to the spinner. and I have tried many tutorials with no luck.
This is my OnCreate function
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button load_routes = (Button)findViewById(R.id.load_routes);
Spinner routes = (Spinner)findViewById(R.id.routes_list);
load_routes.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
load_routes(v);
}
});
routes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View v, int position, long id)
{
Log.v("routes", "route selected");
}
public void onNothingSelected(AdapterView<?> arg0)
{
Log.v("routes", "nothing selected");
}
});
}
This is my load_routes function
private void load_routes(View v)
{
Spinner routes = (Spinner)findViewById(R.id.routes_list);
List<String> routes_list = RouteParser.get_routes();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, routes_list);
routes.setAdapter(adapter);
TableRow list_of_routes_row = (TableRow)findViewById(R.id.list_of_routes_row);
list_of_routes_row.setVisibility(View.VISIBLE);
}
This set up does not work. The only way I got this to work is when I setup my listener as routes.setOnItemSelectedListener(this) Then I implement OnItemSelectedListener and include the functions neccessary. But I have multiple spinners and need to create separate listeners for different spinner. Any help will be appreciated. Thanks!
final String[] s2 = getResources().getStringArray(R.array.capteur_size);
final EditText ed = (EditText) findViewById(R.id.editTextCoC);
spinnerCoC = (Spinner) findViewById(R.id.spinnerCoC);
spinnerCoC.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ed.setText(s2[arg2]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Declare your Spinner as field instantiate the listener once you do findViewById and use it wherever you want.

Categories

Resources