I am have 2 spinners that are set to initial values. I then expect the user to select new values. I am then trying to get those values. However, getSelectedItem() only returns the initial value - the change is not saved, even though the new selection shows up in the spinner:
Spinner spinner1 = (Spinner) view.findViewById(R.id.lessonTypeSpinner);
Spinner weatherConditionS = (Spinner) view.findViewById(R.id.weatherConditionSpinner);
spinner1.setSelection(hmlessonType.get(lessonType));
weatherConditionS.setSelection(hmWeatherCondition.get(weatherCondition));
Button update = (Button) view.findViewById(R.id.updateButton);
final String lessonTypeCopy = spinner1.getSelectedItem().toString();
final String weatherConditionCopy = weatherConditionS.getSelectedItem().toString();
pref = this.getActivity().getSharedPreferences(this.PREF_FILENAME, 0);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor edit = pref.edit();
edit.putString("lessonType", lessonTypeCopy);
edit.putString("weatherCondition", weatherConditionCopy);
edit.apply();
}
});
Get the values inside onClick() method.
You should change it like this:
Spinner spinner1 = (Spinner) view.findViewById(R.id.lessonTypeSpinner);
Spinner weatherConditionS = (Spinner) view.findViewById(R.id.weatherConditionSpinner);
spinner1.setSelection(hmlessonType.get(lessonType));
weatherConditionS.setSelection(hmWeatherCondition.get(weatherCondition));
Button update = (Button) view.findViewById(R.id.updateButton);
pref = this.getActivity().getSharedPreferences(this.PREF_FILENAME, 0);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String lessonTypeCopy = spinner1.getSelectedItem().toString();
final String weatherConditionCopy = weatherConditionS.getSelectedItem().toString();
SharedPreferences.Editor edit = pref.edit();
edit.putString("lessonType", lessonTypeCopy);
edit.putString("weatherCondition", weatherConditionCopy);
edit.apply();
}
});
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am making an app to save a name and using a Spinner control, but it keeps giving me a Null Pointer Exception.
It says:
Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putInt(java.lang.String, int)' on a null object reference
at com.example.shubham.theroster.MainActivity.onItemSelected
Here is the MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText editText;
SharedPreferences prefs;
SharedPreferences.Editor editor;
CheckBox box1, box2;
Spinner spinner;
int spinnerData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("settings", MODE_PRIVATE);
editText = (EditText) findViewById(R.id.editText);
box1 = (CheckBox) findViewById(R.id.checkBox);
box2 = (CheckBox) findViewById(R.id.checkBox2);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
spinnerElement();
loadDataPreference();
}
public void save(View v) {
editor = prefs.edit();
// 1. Name
editor.putString("name", editText.getText().toString());
//2. checkbox
if (box1.isChecked()) {
// steady=true;
editor.putString("status", "Not Steady");
} else if (box2.isChecked()) {
//notSteady=true;
editor.putString("status", "Steady");
}
/*CheckBox cb = (CheckBox) findViewById(checkBox);
boolean bCheckBox = cb.isChecked();
editor.putInt("", bCheckBox ? 1 : 0);*/
editor.commit();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
public void loadDataPreference() {
String str = prefs.getString("name", "");
editText.setText(str);
String status = prefs.getString("status", "");
if (status.equals("Steady")) {
box2.setChecked(true);
} else {
box1.setChecked(true);
}
Toast.makeText(MainActivity.this, status, Toast.LENGTH_LONG).show();
spinner.setSelection(prefs.getInt("spinnerStatus", 0));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
editor.putInt("spinnerStatus", position);
Toast.makeText(MainActivity.this, parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void spinnerElement() {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.color_arrays, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
The editor object you are using for editing data is null, just write
editor = prefs .edit();
below
prefs = getSharedPreferences("settings", MODE_PRIVATE);
in your onCreate() method and everything will be on track. You are initializing your editor in a particular method which is making things ambiguous for you.
I want to save values in ArrayList with SharedPreference. Then, I want to call values in ArrayList from another class, but it is not saving. How can I do this? With SharedPreferences? To save File? Or create Sqlite? Thank you for helping.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button saveButton = (Button)findViewById(R.id.button);
final Button delButton = (Button)findViewById(R.id.delButton);
final ListView listView = (ListView)findViewById(R.id.listView);
final EditText editText = (EditText)findViewById(R.id.editText);
final ArrayList<String> arrayList = new ArrayList<String>();
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("numbers", arrayList.toString());
editor.commit();
String arrayString = sharedPref.getString("numbers", null);
final ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
saveButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String str = editText.getText().toString();
Integer cout = listView.getCount()+ 1;
String str1 = cout.toString().concat("."+str);
arrayList.add(listView.getCount(), str1);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
editText.setText(" ");
}
});
delButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
arrayList.remove(arrayList.size()-1);
arrayAdapter.notifyDataSetChanged();
}
});
}
I think you can not do this editor.putString("numbers", arrayList.toString()); because object.toString() does not convert the ArrayList to String it just make something weird like "#Object3223rw", take a look to this post instead Save ArrayList to SharedPreferences
Save list:
editor.putString("List", TextUtils.join(",", myList));
Get list:
String serialized = sharedPref.getString("List", null);
myList = Arrays.asList(TextUtils.split(serialized, ","));
An observation that works on a List not ArrayList because asList return List. Tofasio's answer does not work if you have duplicate strings that works with set.
My understanding is to use SharedPreference only to save simple key-value pairs (bool, float, int, long and string) and not as a data storage. If you need to save more complex data objects (including lists and arrays), you'll need to serialize/deserialize and save on disk.
http://developer.android.com/guide/topics/data/data-storage.html
There is probably a simple answer for this: when my alert box shows, I try to store the contents of a EditText in a string but, the string is always empty.
contents = inputElement.getText().toString();
code:
public class MainActivity extends Activity {
EditText inputElement;
Spinner spinner;
MySQLiteAdapters adapter;
MySQLiteHelper helper_ob;
AlertDialog dialog;
List<String> lables;
String contents;
ArrayAdapter<String> dataAdapter;
public static final String PREFS = "examplePrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button) findViewById(R.id.start);
//start.setVisibility(View.GONE);
spinner = (Spinner) findViewById(R.id.spinner1);
inputElement = new EditText(this);
adapter = new MySQLiteAdapters(getApplicationContext());
lables = adapter.getAllLabels();
exmaplePrefs = getSharedPreferences(PREFS, 0);
editor = exmaplePrefs.edit();
final AlertDialog firstTimeUse = new AlertDialog.Builder(this)
.setView(inputElement)
.setTitle("TITLE")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null).create();
firstTimeUse.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = firstTimeUse.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contents = inputElement.getText().toString();
if (contents.matches("")){
showAlertbox("You Must Enter a Team");
}else{
adapter.insertTeamDetails(contents);
List<String> lables = adapter.getAllLabels();
dataAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, lables);
spinner.setAdapter(dataAdapter);
lables.add("Add New Team...");
firstTimeUse.dismiss();
}
}
});
}
});
if (lables.isEmpty())
{
firstTimeUse.show();
}
else{
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
lables.add("Add New Team...");
}
Thanks in advance
You create a new instance of inputElement in onCreate:
inputElement = new EditText(this);
So the text in it is always empty as you don't add it to the layout.
Instantiate it from the layout using findViewById or add it to the layout in the code.
SetView(View view) takes view element, I am not sure how you are adding EditText there. You can add edit text in layout file itself something like this:
and declare in onCreate something like this:
inputElement = (EditText) findViewById(R.id.EditTextPassword);
You can get string like this:
inputElement.getText().toString();
I'm wondering if there is some trick to get the spinner updated from an edittext and onClick, before it gets committed to the database and retrieve from there? The list and the spinnerAdapter are set for retrieving values from database, so I'm aware that this question might be stupid.
I was thinking of this logic: enter some text to edittext, click ok, then temporary update the spinner with this text, before it goes to database, then do some other stuff in the activity and last commit everything to database. When you then close and open your activity again, the temporary value is lost, but the spinner gets populatet with the same value, but this time from database.
here is some code:
public class Vnos extends Activity {
//... some values
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
final List<VnosiDB> spinerItems = datasource.getAllNiz();
final ArrayAdapter<VnosiDB> spinnerAdapter = new ArrayAdapter<VnosiDB>(
this, android.R.layout.simple_spinner_item, spinerItems);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
String nizIzSpinerja = spinner.getItemAtPosition(
spinner.getSelectedItemPosition()).toString();
nizDB = nizIzSpinerja;
// nov niz
novNiz = (TextView) findViewById(R.id.dodaj);
novNiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(Vnos.this,
android.R.style.Theme_Holo_Dialog);
dialog.setContentView(R.layout.nov_niz);
TextView okNov = (TextView) dialog.findViewById(R.id.okNovNiz);
okNov.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText inputNiz = (EditText) dialog
.findViewById(R.id.niz);
dialog.dismiss();
nizDB = inputNiz.getText().toString();
spinnerAdapter.notifyDataSetChanged();
}
});
dialog.show();
}
});
// ...some other code...
//...
//.. then, here I commit everything to database...
shrani = (TextView) findViewById(R.id.shrani);
shrani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vnosDB = (int) System.currentTimeMillis();
datasource.createVnos(zacetekDB, razlikaDB, nizDB, deloDB,
postavkaDB, dodatekDB, opisDB, vnosDB);
datasource.close();
Toast test = Toast.makeText(Vnos.this, "Vnos " + deloDB
+ " uspešen!", Toast.LENGTH_LONG);
test.show();
startActivity(new Intent("com.sandpit.jazstudent.URE"));
finish();
}
});
}
}
you are using ArrayAdapter, which is loaded by List<VnosiDB>. I assume that VnosiDB represents a record from the database. Why don't you just put a temporary record in this list when you need it?
List<VnosiDB> spinerItems = new ArrayList<VnosiDB>();
VnosiDB tempRec = new VnosiDB();
//set some values to the properties if you need to
spinnerItems.add(tempRec);
//populate the spinner with the temp record
I've create one spinner and I want to save all of spinner input when i close my application. How can I do? I think shared preferences can help me but i don't know how can use it!
This is my code:
private Spinner spinner;
private EditText Text;
private ArrayAdapter<String> adapter;
private Button addButton;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Text = (EditText) findViewById(R.id.et);
final List<String> planets = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.clienti_arrays)));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, planets);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
addButton = (Button) findViewById(R.id.add_new);
addButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
addNewSpinnerItem();
Collections.sort(planets);
}
});
}
protected void addNewSpinnerItem()
{
String textHolder = "" + Text.getText().toString();
adapter.add(textHolder);
}
public int compare(String s1, String s2) { return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
Thanks a lot for your help..
Override onPause() of Activity to save selected values in Shared Preferences when your application going to close as:
#Override
public void onPause()
{
// get Spinner Slected text here
String selectedtext = spinner.getSelectedItem().toString();
//Create SharedPreferences to store selected value
SharedPreferences spinnerPrefs = this.getSharedPreferences("spinnerPrefs",
MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = spinnerPrefs.edit();
prefsEditor.putString("spinner_selectedtext", selectedtext);
prefsEditor.commit();
super.onPause();
}
and to retrieve values saved in SharedPreferences :
SharedPreferences spinnerPrefs = this.getSharedPreferences("spinnerPrefs",
MODE_WORLD_READABLE);
String selectedtext = spinnerPrefs.getString("spinner_selectedtext",
"nothing_selected");
I detail how to do this in this post. Each time you enter an item in the edittext, it saves it to the spinner which holds the x last items you enter. The memory stays until you uninstall the app or manually clear the data.