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);
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
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.
I have an EditText and a save Button in my Activity, whatever text the user enters in the EditText, it should get saved when the user clicks on the save(add) Button.
And there is a Load Button whenever the user clicks on a load Button in the Activity the saved data should get displayed in a ListView.
Update: I want to save user entered data into an Array and populate the list view with the Array
here is the code:
ArrayList<String> namelist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namelist );
ListView list = (ListView) findViewById(R.id.listView);
list.setAdapter(adapter);
Button save = (Button) findViewById(R.id.button_save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText name = (EditText) findViewById(R.id.editText);
String n = name.getText().toString();
namelist.add(n);
name.setText(" ");
}
});
}
I got the answer folks! Thanks to every one! for your suggestions!
I have to use notifyDataSetChanged(); method to populate the Listview
As per your comment, I have to display all the saved data while the app is running! after the app is closed it may flush away
-- You can use static String inside your activity and you can load your edittext with the string when Load button is clicked
In my opinion, shared preferences is used for another things like username of login, password of login or somethings like that but It is NOT a good practice, use that to save data.
To save data, you can use SQLite or some ORM like GreenDao. Is the best and the fastest way to save and load data in local.
http://greendao-orm.com/documentation/how-to-get-started/
http://developer.android.com/training/basics/data-storage/databases.html
Don't store your values in SharedPreference.
use SQLite to store the data.
Get all the values in Array from SQLite and then display in Listview.
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!