I am using the same spinner to all the activities in my app. Let's say, items in spinner are English, Finnish, Polish, blah.. When I select Finnish in one activity, the dropdown of spinner gets close and Finnish can be seen on the spinner. But when I go to the next activity it does not show the Finnish anymore, instead, it shows English (item) at the top. Is there any method to make appear the item on the spinner that has been selected to all the activities. Or, should not change unless it has not been changed.
In BaseActivity;
int currentLanguage = spinner.getSelectedItemPosition();
SharedMemory.getInstance().setCurrentPosition(currentLanguage);
Log.i("SET POSITION", Integer.toString(currentLanguage));
In other activity to save the state of item position;
int position = SharedMemory.getInstance().getCurrentPosition();
Base_Activity.spinner.setSelection(position);
Log.i("GET POSITION", Integer.toString(position));
I managed to set the selected language to set it in SharedMemory which is Singleton class.
But how can I still get the same currentLanguage in all the activities. I am not able to get it when I change the activity.
Note: this spinner is in action bar in Base_Activity class where all the other activities are extended this class.
Thank you.
Finally, I managed to solve my problem. Before I was trying to do stuffs inside spinner.setOnItemSelectedListener() method, which was really wrong.
In my BaseActivity;
Configuration conf = getResources().getConfiguration();
//creating the position of the language in spinner from arraylist
int currentLanguage = Arrays.asList(language_codes).indexOf(
conf.locale.getLanguage());
spinner.setSelection(currentLanguage);
This allows me the selected item of spinner remain on the top always when I even change the activities. Hope this might help others. :)
That is because the spinner in the other activity is different from the one in the first activity.
You will have to pass the current selection of the spinner as argument to the second activity and set the other spinners selection to that position.
In BaseActivity:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("pos", spinner.getSelectedItemPosition());
startActivity(intent);
In second Activity:
spinner.setSelection(getIntent().getIntExtra("pos", 0));
The singleton class should probably look like this:
public class SharedMemory {
public static SharedMemory sharedMem = new SharedMemory();
private String valueSelected; // or position here
public SharedMemory getInstance() {
return sharedMem;
}
public String getCurrentLanguage() {
Log.i("tag","valueSelected: " + valueSelected);
return valueSelected;
}
public void setCurrentLanguage(String currLang) {
valueSelected = currLang;
Log.i("tag","valueSelected: " + valueSelected);
}
}
EDIT:
onItemSelectedListener(...) {
if(ShareMemory.getInstance().getCurrentLanguage().equalsIgnoreCase("0")) {
// then set the value to 0
}else {
// set the value still but then set the gui also
}
}
// in the onResume or onCreate method
write the following:
spinner.setSelection(ShareMemory.getInstance().getCurrentLanguage());
Using Log print the values in the singleTon class, and also the onItemSelected listener of the spinner.
Related
I have a method to add favorites from a search list.
This code allows to click on listview and call listener accordingly weather it is search listview or mytour Listview.
holder.imgaddFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tourList.get(position).getFav().equalsIgnoreCase("0")) {
listener.onFavourited(tourList.get(position), true);
holder.imgaddFavourite.setImageResource(R.drawable.faved);
} else {
listener.onFavourited(tourList.get(position), false);
holder.imgFavourite.setImageResource(R.drawable.not_faved);
}
}
});
Below is the code for mytourList which works perfectly:
#Override
public void onFavourited(final Tour tour, final boolean fav) {
new SetFavourite(new SetFavourite.OnFavouriteSet() {
#Override
public void onFavouriteSet(Boolean response) {
int index = listTour.indexOf(tour);
tour.setFav(fav ? "1" : "0");
listTour.set(index, tour);
}
}, fav).execute(tour.getId(), application.getUser().getUid());
}
This code persist favourite state and got no problem.
Below is my code for adding favorites for search items list.
public void onFavourited(final Tour tour, final boolean fav) {
int index = searchOptions.getSearchedTours().indexOf(tour);
tour.setFav(fav ? "1" : "0");
searchOptions.getSearchedTours().get(index).setFav(fav ? "1" : "0");
searchOptions.getSearchedTours().set(index, tour);
}
I am able to click on and add it to favorites, but if I open another tab and reopen that list again, the state is lost. I guess it is cause it's not saving state globally. I've searched for similar answers but none of them helped.
Any help would be appreciated.
You are storing the state of wheather an item is favourite or not in a Boolean variable which is not a persistent storage. It will not be same when you close and reopen the app.
You should store the favourite items on SharedPreferences or in SQL Database which are persistent storage. In that way you can add and remove the data anytime you want, and it will be persisted.
Hope this helps, if you have any doubt, do let me know.
I think you are using ViewPager to handle fragments and always create new fragment when page changed. Therefore state cannot be retained. Try below method in the adapter of ViewPager:
Add variable to keep your desired fragment.
SearchTourFragment searchTourFragment = null;
In getItem(), create your desired fragment only when it is null.
if(searchTourFragment == null){
searchTourFragment = SearchTourFragment.newInstance();
}
return searchTourFragment;
Avoid deleting your desired fragment by override destroyItem().
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
if(position != POSITION_OF_SEARCHTOURFRAGMENT) container.removeView((View)object);
}
This is trying to keep your desired fragment from page change. But if you start another Activity and then back, the fragment may not be retained. Hope that helps!
I am developing an app where i need to set spinner values dynamically based on previous screen values. My code...
Main.java.
String[] values = {"All","Only Walk-in","Only Phone","Only Web","Walkin-phone","Walkin-web","phone-web"};
/*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,apttypes);
spinner.setAdapter(adapter);*/
But here what i want is from previous screen i am getting some value (like spinner postion). based on that i need to set spinner value to display...
Means from previous screen if i got values =0 means,
i need to set spinner value to display "All" from values array at top.
If i got value= 5 means,
i want to set spinner value to display as "Walkin-web"
How can i do that. can anyone help me with this...
Pass the value in from the previous Activity using extras in the Intent you use to launch it. Then when you've read the value call
int position = getIntent().getIntExtra( "name", defaultValue );
spinner.setSelection( position );
Which will move the spinner to the index you selected.
Use following array code and create new array adapter each time
String[] str=new String[maxsize-4];
you can implement onItemClick event on Spinner like this and setSelection(position)
//Spinner OnItemClick Event here
payfeeTabStudentNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
payfeeTabStudentNameSpinner.setSelection(position);
spinnerSelectedValue = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Inside your First Activity A.java
public static String Position = YOUR_SPINNER1.getSelectedItem().toString();
Inside your Second Activity B.java
if(A.Position.equals("0")){
//Set your adapter accordingly
}else if(A.Position.equals("1")){
//Set your adapter accordingly
}
You can assign the Spinner's Position using the following code..
Spinner s1;
-----------
-----------
int position=valueFromPrevious;
s1.setSelection(position);
-----------
-----------
pass the values from previous activity using Extras and then when u want use it in your current activity follow this:
If u get String value then typecast it into interger by parseInt method...
String strtext4 = getIntent().getStringExtra("qualification");
then
int position = Integer.parseInt(strtext4);
after this just set it to your spinner
qualificationspinner.setSelection(position);
I am using a spinner in my application. After selecting an index in spinner I open
a new activity and then come back to the first. Now my spinner is showing the previous selected value and if I select the same index again nothing happens.
The doc says onItemSelectedListener invokes iff the index is different from the previous. And I can't set it to default(0) when i come back.
So is there any alternative solution to do this? Please help me. Thanks. Here is my code:
companyspin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) {
}
public void onItemSelected(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
Object o = companyspin.getSelectedItem();
network = CheckNetworkStateReceiver.isOnline(context);
selectCompany = o.toString().trim();
Data.homeCommunityValue = arg2;
setCompanyList(arg2);
flagCatageory = false;
try {
tracker.trackEvent("Home", // Category
"Drop Down Selection", // Action
selectCompany, // Label
arg2); // Value
} catch (Exception e) {
e.printStackTrace();
}
}
});``
You start the new activity as soon as it's selected in the spinner ?
Just grab the data from the spinner you need for your activity in the onItemSele.... listener.
Set
mySpinner.setSelection(your_position)
before your new activity starts. If you want it to stay the on the same value in the spinner, a Button to activate your selection seems easier, and less error-prone for the user depending on what the selection do.
EDIT:
The selection is still the same afterwards so the callback will never fire. You can put a placebo object at position(0) with some info text "Choose here..." which you can return to after a valid selection, with setSelection. Just add a check in the listener if it's a valid choice or the placebo.
Since you want 1st item to be selected when you return to your main activity, you can try
companyspin.setSelection(0);
in onCreate() of main activity.
I've listed some items in list that extends Activity and the list are listed using Custom Adapter. My question is, this is my xml File I've added some items to this spinner. How can i get the spinner values to next layout. Anyone knows then please tell me? Advance thanks.
I'm not clear on what you're actually asking here, but as a guess there are two possible things you're asking
How to get the currently selected value out of the Spinner
How to set the same value to a spinner in the next layout
1.
Is simple enough
((Spinner)findViewById(R.id.spinner1)).getSelectedItem()
Will return the object selected by your spinner.
Is slightly more complex, you'll need to determine what index in the data supplied corresponds to the result you get from getSelectedItem(), for example if you had an array of Strings then you could search through until you found the index and then set it on the new spinner.
For example:
String[] options = new String[] {"One","Two","Three","Four"};
String val = (String)((Spinner)findViewById(R.id.spinner1)).getSelectedItem();
//.......pass this to a layout/activity etc.........
for (int i=0; i<options.length; i++)
{
if (options[i].equals(test))
{
((Spinner)findViewById(R.id.spinner2).setSelection(i);
break;
}
}
But your best bet would be to try and explain more clearly what you're asking.
first you have to select data from spinner using
spinnerobject.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id)
{
Spinner spinnerobject = (Spinner) findViewById(R.id.Spinner02);
string value = (String)spinnerobj.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
then u hava to use intent for sending it to next activity..
Use
Intent.putExtra(..):
intent.putExtra("keyName", "somevalue");
This method is overloaded and takes various types as second argument: int, byte, String, various arrays..
To get the data out use appropriate getXYZExtra(). For String this is:
getStringExtra(String keyName)
First thing :: you can pass value from one activity to second activity not one layout to second
second :: if you need to pass value from one activity to second use
first activity::
activity.putExtra("lastpage", lastscore5);
*here lastpage is key which unique for aplication
second activity::
Intent i1 = getIntent();
var = i1.getIntExtra("lastpage", 1);
I'm in a trouble managing a spinner, so may I ask for your help ?
I have a spinner with its adapter.
I initialize the spinner with a list of values when starting my activity.
Then I force the selected value to be the one used in the object that I manage.
Once the screen is initialized :
When the user selects a value in the spinner, according to the selected value, I may continue (or not) to another activity for let the user choose a complementary and necessary value.
If the user "cancels" this second activity, I want to rollback the spinner to its previous selected value, and cancel some actions made in the meantime.
If the user goes to the end of the second activity, everything is fine and I want juste to refresh the spinner display with the datas selected in the second activity (I overload the getView method in the adapter to do this).
Overall, I can easily do all of this, however, when I force the selected value in the spinner at the begining of my activity, or whene returning back from the second activity by "Cancel", the change value event is catched and the second activity is triggered (the user did not click anything at all).
How would you allow the second activity to be lauched only if the change of the selected value in the spinner is due to a manual action from the user, and prevent that same second activity to be launched when the value of spinner is changed "in the code "?
I tried many solutions, as setting a boolean into the adapter that tells if the next event will be raised because of an "in the code" action.
Or also putting a boolean in the adapter that tells if the adapter has initialised itself, and I force that boolean to true on the forst change catched event.
But nothing that really works fine.
Thank you for your help.
Oliver
I've always solved that issue with boolean flags, it isnt pretty at all, but it works if you think it through.
The idea is more or less, create a global usable boolean and init with false, in the onSelectedItemListener() use that boolean to choose wether or not to trigger the action, the important thing to remember is to set it to true after the computer has selected it the first time automatically, and reset it to false in the onResume() method.
This isnt perfect but it should work.
Edit:
bool spinnerUsable1;
bool spinnerUsable2;
int positionSpinner;
public void onCreate(Bundle savedInstanceState){
spinnerUsable1 = false;
spinnerUsable2 = true;
if(savedInstanceState != null){
positionSpinner = savedInstanceState.getInt("posSpinner");
if(positionSpinner != 0) spinnerUsable2 = false;
}
//Declare your spinner, set the on item selected lister
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
boolean spinnerUsable = (spinnerUsable1 && spinnerUsable2);
if (!spinnerUsable1) {
spinnerUsable1 = true;
} else if (!spinnerUsable2) {
spinnerUsable2 = true;
}
if (spinnerUsable) {
//Action;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Nothing
}
});
}
Something like this should work.