I am overriding onResume method to load previos state of my activity where it was ie spinner's last selected item etc. However the same code works fine for some activities but for some it causes crash as when i remove this onResume from them, Activity doesnt crash.
Here's the code
#Override
protected void onResume() {
super.onResume();
sp1 = (Spinner)findViewById(R.id.spinner);
sp2=(Spinner)findViewById(R.id.spinner1);
sp3=(Spinner)findViewById(R.id.spinner2);
sp4=(Spinner)findViewById(R.id.spinner3);
sp5=(Spinner)findViewById(R.id.spinner4);
TextView tx=(TextView)findViewById(R.id.upgradeResult) ;
SharedPreferences prefs = getSharedPreferences("restore_defensiveBuildings_state", Context.MODE_PRIVATE);
int spinner1Indx = prefs.getInt("spinner1_indx", 0);
int spinner2Indx = prefs.getInt("spinner2_indx", 0);
int spinner3Indx = prefs.getInt("spinner3_indx", 0);
int spinner4Indx = prefs.getInt("spinner4_indx", 0);
int spinner5Indx = prefs.getInt("spinner5_indx", 0);
sp1.setSelection(spinner1Indx);
sp2.setSelection(spinner2Indx);
sp3.setSelection(spinner3Indx);
sp4.setSelection(spinner4Indx);
sp5.setSelection(spinner5Indx);
tx.setText(""+totalAirBombUpgradeCost);
}
This is how i loaded items to the adapter
Spinner sp1;
Spinner sp2;
Spinner sp3;
Spinner sp4;
Spinner sp5;
TextView tx;
Button sbmt;
String levels[]={"Level 1",
"Level 2",
"Level 3",
"Level 4"
};
int[] images={R.drawable.giant_bomb_1and2,
R.drawable.giant_bomb_1and2 ,
R.drawable.giant_bomb_3and4,
R.drawable.giant_bomb_3and4
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_giant_bomb);
//// initialize all your visual fields
// if (savedInstanceState != null) {
// sp1.setSelection(savedInstanceState.getInt("MySpinner1", 0));
// // do this for each of your text views
// }
sbmt=(Button)findViewById(R.id.submit);
tx=(TextView)findViewById(R.id.upgradeResult);
sp1=(Spinner)findViewById(spinner);
sp2=(Spinner)findViewById(R.id.spinner1);
sp3=(Spinner)findViewById(R.id.spinner2);
sp4=(Spinner)findViewById(R.id.spinner3);
sp5=(Spinner)findViewById(R.id.spinner4);
SpinnerAdapterGiant adapter=new SpinnerAdapterGiant(this,levels,images);
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
sp3.setAdapter(adapter);
sp4.setAdapter(adapter);
sp5.setAdapter(adapter);
And this is the error
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
EDIT: When i remove onResume(), everything works fine app doesn't crash, just that it doesn't load activity's previous state.
Because in array you put only 4 value and there 5 spinner so in 5th spinner error occur.
Your are trying to access the 5th element in an array of size 4. Your levels and images array have only for element but you have 5 spinners
Increase your array size to 5.
Related
I have a weird bug which I'm not sure why it's happening,
I have 2 activities: activity A and activity B.
When the app starts, it initializes a spinner once. I go to the second activity and then go back <-
onRestart() of the Activity A will be called. My problem is that even though I clear my spinner and reinitialize it in onRestart() it keeps reading the values.
For example, if spinner has 1/2 when you go to activity B then back to activity A, spinner has = 1/2/1/2.
I find this weird because when I just set the spinner adapter to null and comment out my initialize of spinner when I go back to activity A from activity B, my spinner is empty.
here is my code:
#Override public void onRestart() {
super.onRestart();
Spinner location = findViewById(R.id.spinnerLocation);
location.setAdapter(null);
initSpinner();// if this is commented out spinner is cleared, if not commented the same valus are added again
}
here is code for initSpinner(reads from shared prefs) this is not the problem
public void initSpinner(){
Spinner location = findViewById(R.id.spinnerLocation);
location.setAdapter(null);
SharedPreferences prefs = this.getSharedPreferences("Locations", Context.MODE_PRIVATE); //preffilename
SharedPreferences.Editor editor = prefs.edit();
editor.putString("1","St. Catharines");
editor.putString("2","Toronto");
editor.putString("3","Niagara Falls");
editor.commit();
int s = prefs.getAll().size();
for(int f=0;f<25;f++) {
if (prefs.getString(String.valueOf(f + 1), null) != null) {
DefaultLocations.add(prefs.getString(String.valueOf(f + 1), null));
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, DefaultLocations);
//set the spinners adapter to the previously created one.
location.setAdapter(adapter);
}
do
DefaultLocations.clear() before for loop inside initSpinner() method it may not clear when u adding new values
TextView tvRes;
Button btn;
String fgpa;
int maxGrade[]=new int[] {4,3,3,3,3,3,2,2,2};
double rcvdGrade[]=new double[9];
double[] fres=new double[9];
int ssp1;
double sumRes=0,sumPoints=0;
double fail=0;
Spinner sp1,sp2,sp3,sp4,sp5,sp6,sp7,sp8,sp9;
ArrayAdapter<CharSequence> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp1 = findViewById(R.id.sp1);
sp2 = findViewById(R.id.sp2);
sp3 = findViewById(R.id.sp3);
sp4 = findViewById(R.id.sp4);
sp5 = findViewById(R.id.sp5);
sp6 = findViewById(R.id.sp6);
sp7 = findViewById(R.id.sp7);
sp8 = findViewById(R.id.sp8);
sp9 = findViewById(R.id.sp9);
btn=findViewById(R.id.btn);
tvRes=findViewById(R.id.tvRes);
adapter=ArrayAdapter.createFromResource(this,R.array.grades,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
sp3.setAdapter(adapter);
sp4.setAdapter(adapter);
sp5.setAdapter(adapter);
sp6.setAdapter(adapter);
sp7.setAdapter(adapter);
sp8.setAdapter(adapter);
sp9.setAdapter(adapter);
ssp1=sp1.getSelectedItemPosition();
if(ssp1==0){
rcvdGrade[0]=10;
}
if (ssp1=='1'){
rcvdGrade[0]=9;
}
if(ssp1=='2'){
rcvdGrade[0]=8;
}
if(ssp1=='3'){
rcvdGrade[0]=7;
}
if(ssp1=='4'){
rcvdGrade[0]=6;
}
if(ssp1=='5'){
rcvdGrade[0]=5;
}
if(ssp1=='6'){
fail=0;
}
I am new to programming. I am trying to get a Spinner position and by using that value, I will assign a value to a variable from which I can calculate a percentage. But this code always selects the first condition and sets the value to 10. I cannot figure out what's wrong with this code. Help me, guys. Also, if you have any suggestions or improvements with this code, please let me know, friends. Thanks in advance.
Extra: I also tried using the getSelectedItemPosition(); function directly on the if statement and also tried to get the values by comparing the text in the Spinner but it gives me the same (always selects the first condition) result.
Your code is running as soon as the activity is created. That means it gets the position of the spinner as soon as it's made, which will always be position zero. That code will not run again to give you a different value. You need to set up an OnItemSelectedListener so the value will change every time you change the position of the spinner.
private AdapterView.OnItemSelectedListener spinnerListener =
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Called anytime a spinner dropdown item is clicked
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
Then in your onCreate() method write this:
sp1.setOnItemSelectedListener(spinnerListener);
This is only applying to sp1, but if you set all the spinners with this same listener, know that the parameter parent in the listener is the spinner that changed. If you need to know which spinner changed, use the setTag() and getTag() methods.
In onCreate():
sp1.setTag("sp1");
sp2.setTag("sp2");
// set Listeners, etc
In your onItemSelected()
if (parent.getTag().equals("sp1")) //It was sp1 that changed
// do stuff
else if (parent.getTag().equals("sp2")) //sp2 changed
// do other stuff
EDIT: As per your request, here is a combination of the above:
// Previous declarations
int ssp1;
double sumRes=0,sumPoints=0;
double fail=0;
Spinner sp1,sp2,sp3,sp4,sp5,sp6,sp7,sp8,sp9;
ArrayAdapter<CharSequence> adapter;
private AdapterView.OnItemSelectedListener spinnerListener =
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int position = parent.getSelectedItemPosition(); // also equal to the parameter position
if (parent.getTag().equals("sp1")) // sp1 was changed this time
// Change rcvdGrade[0] as you please
else if (parent.getTag().equals("sp2")) // sp2 changed
// Change rcvdGrade[1] as you please
else if (parent.getTag().equals("sp3")) //etc
//etc
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// This is required to make the listener happy, but leave it blank
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp1 = findViewById(R.id.sp1);
sp2 = findViewById(R.id.sp2);
sp3 = findViewById(R.id.sp3);
// others set, adapters set, etc
sp1.setTag("sp1");
sp2.setTag("sp2");
sp3.setTag("sp3");
// etc
sp1.setOnItemSelectedListener(spinnerListener);
sp2.setOnItemSelectedListener(spinnerListener);
sp3.setOnItemSelectedListener(spinnerListener);
// etc
}
I'm not here to write all your code, but I hope this helps you understand this better. If not, please look up tutorials for the OnItemSelectedListener because that is what you want to best work with spinners. If you are certain you want to use OnClickListener, then set that to a button instead.
the question is quite obvious but still nothing worked for me. In my application i'm selecting value from spinner and wanna to let spinner to show selected value after restarting application. to store spinner value i'm using shared preferences But when restarts application logcat shows null pointer error. Here's code
String options[]={"-Select-", "Domino's","Pizza Hut", "Pizza Bite"};
Spinner spin;
int formatposition;
fSpinner = (Spinner)findViewById(R.id.fSpinner);
ArrayAdapter<String> adp = new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_spinner_dropdown_item,options);
fSpinner.setAdapter(adp);
To store spinner selected value:
Editor editee = preferences.edit();
editee.putInt("lastindex", spin.getSelectedItemPosition());
editee.commit();
To restore shared preferences when application restarts
protected void onCreate(Bundle savedInstanceState) //onCreate is called when the activity is starting
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS); //view that shows items in a vertically scrolling list
btnaddnew = (Button)findViewById(R.id.btnaddnew);
btnaddnew.setOnClickListener(this);
formatposition = preferences.getInt("lastindex", 0);
spin.setSelection(formatposition);
}
How could array find index without name of array??
Try this one to solve:-
spinposition = preferences.getInt("lastindex", 0);
spin.setSelection(spinposition);
I am to android coding and have what I hope will be a simple question. I have an app that has a demographics page, with various spinners (although I will only use 1 for this example). The spinners are already populated, but the user can save them once they have made their choice so every time they open this app the previous choices are there.
My code to load the values into the spinner is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_demographics);
// Show the Up button in the action bar.
setupActionBar();
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
int ageValue = prefs.getInt("Age", 0);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//set the default according to value
spinner.setSelection(ageValue);
}
and then my code to save the data is
public void submitDemo(View view) {
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
int ageValue = spinner.getSelectedItemPosition();
//save the current data from the spinner
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("Age", ageValue);
editor.commit();
finish();
}
I'm not bothered about capturing the value when they change the spinner, just simply at the end. I know it's probably something simple that I'm missing, but if anyone can help I would greatly appreciate it
First, set an adapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.your_string_array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
If setSelection(value) doesn't work try with
spinner.setSelection(ageValue, true);
This will "animate" the selection, i.e. scroll it to the selected position.
Hi I am trying to save some values in my activity but I'm having a problem when I save it with onSaveInstanceState and restore with onRestoreInstanceState, I am saving an int years and it saves the first time the screen changes orientation, the spinner repopulates and sets it at the last value , but not when I switch back the orientation again.
My orientation is set to landscape in my manifest, and I have the two save and restore method overridden but it doesn't seem to work, do I need to do something in onPause aswell?
here is my code:
int years;//global variable
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinnerYears = (Spinner) findViewById(R.id.spinYears);//Spinner
final ArrayAdapter <Integer> adapter = new ArrayAdapter <Integer>(this,android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
for(int i=0;i<=100;i++)
{
adapter.add(i);
}
spinnerYears.setAdapter(adapter);
years = spinnerYears.getSelectedItemPosition();
}//onCreate
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("MyInt", years);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Spinner spinnerYears = (Spinner) findViewById(R.id.spinYears);//Spinner
final ArrayAdapter <Integer> adapter = new ArrayAdapter <Integer> (this, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
for(int i=0;i<=100;i++)
{
adapter.add(i);
}
spinnerYears.setAdapter(adapter);
TextView tvYears = (TextView) findViewById(R.id.tvYears);//spinner Tv
tvYears.setVisibility(TextView.GONE);
int myInt = savedInstanceState.getInt("MyInt");
spinnerYears.setSelection(myInt);//
Toast.makeText(getBaseContext(), "Restored int"+myInt, Toast.LENGTH_LONG).show();
}
Because you don't handle the event of changing orientation, so everytime you change orientation, your program (or Activity) is re-created, which means the onCreate() method is called always; which leads to a result that onSaveInstanceState() and onRestoreInstanceState() never being called.
It's being explained here in Android Documentation: http://developer.android.com/reference/android/app/Activity.html#ConfigurationChanges
In order to fix this, in AndroidManifest.xml , adding this attribute:
android:configChanges="orientation"
to avoid Activity restarted and, well, good luck with that!
In onRestoreInstanceState(), you never assign the value back the the variable years. You assign it to an int and then disregard it. So when onSaveInstanceState() is called, years hasn't been set yet and it saves that unset value (0).
If you change your getInt() line towards the bottom to be:
years = savedInstanceState.getInt("MyInt");
spinnerYears.setSelection(years);
it should start working. Good Luck!