Null Pointer Exception on Shared Preferences on a Spinner control [duplicate] - android

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.

Related

Spinner not getting selected value

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();
}
});

Loading SharedPreferences in another activity

Here's the problem. In my second class, I'm trying to load the SharedPreferences. Below I'll also include my first class.
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
When I test it, my debug log always prints -1. It won't load my shared preferences. What am I doing wrong?
I've tried the other answers on here and every tutorial, but they aren't working. Here is my code to set up and save my spinner preferences. I've checked this and it's working.
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
Here it's called in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
You are passing wrong String in getSharedPreferences(String, int).
preferences = getSharedPreferences("Selection", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
Give this a try.
I hope it helps.
Make sure your SharedPreference key is same in both the class or even throughout the whole App.
While saving do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
preferences.edit().putInt("grammerOption", 1).apply();
While Getting data from prefs do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
int option = preference.getInt("grammerOption", -1);
PS,
Key for preference(which is MY_PREFS here) must be the same.

How save state of checkbox? if is enabled or disabled

I'm making an app that have a lot of checkbox. I wanted save the states of these but only could save if these are checked, but now I want save if is enabled or disabled, since some checkbox active states to other checkbox. How can i do that?
...
if (view.equals(contador11)){
if(contador11.isChecked()){
contador14.setEnabled(true);
}else{
contador14.setEnabled(false);
}
}
if (view.equals(contador12)){
if(contador12.isChecked()){
contador13.setEnabled(true);
contador26.setEnabled(true);
}else{
contador13.setEnabled(false);
contador26.setEnabled(false);
}
}
if (view.equals(contador7)){
if(contador7.isChecked()){
contador15.setEnabled(true);
}else{
contador15.setEnabled(false);
}
}
...
I'm not following your code exactly, but assuming you want to save all of them at the same time, you could save code by just putting them in a list or something. Here's an example.
private SharedPreferences prefs;
private CheckBox[] contadors;
private CheckBox contador1, contador2, contador3, contador4, contador5, contador6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
contador1 = (CheckBox) findViewById(R.id.contador1);
contador2 = (CheckBox) findViewById(R.id.contador2);
contador3 = (CheckBox) findViewById(R.id.contador3);
contador4 = (CheckBox) findViewById(R.id.contador4);
contador5 = (CheckBox) findViewById(R.id.contador5);
contador6 = (CheckBox) findViewById(R.id.contador6);
}
public void clickContador(View view) { // Just for testing
CheckBox contador = (CheckBox) view;
view.setEnabled(false);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveContadors();
}
#Override
protected void onResume() {
super.onPostResume();
contadors = new CheckBox[]{contador1, contador2, contador3, contador4, contador5, contador6};
loadContadors();
}
private void saveContadors() {
SharedPreferences.Editor editor = prefs.edit();
for (int i = 0; i < contadors.length; i++)
editor.putBoolean("contador" + i, contadors[i].isEnabled());
editor.apply();
}
private void loadContadors() {
for (int i = 0; i < contadors.length; i++)
contadors[i].setEnabled(prefs.getBoolean("contador" + i, true));
}
<CheckBox
android:id="#+id/contador1"
android:onClick="clickContador"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
To put the state of your CheckBox, we can use SharedPreferences:
CheckBox contador = (CheckBox) findViewById(R.id.contador1);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
if (contador.isChecked()) {
prefs.edit().putBoolean("key", true).commit(); // put true value
}else{
prefs.edit().putBoolean("key", false).commit(); // put false value
}
To get the value you saved back:
boolean myContador = prefs.getBoolean("key", false);
if (myContador == true) {
// do your thing
}else{
// the value is false, do something
}

Call and set Global variable

I'm trying to create a global variable that I can referece anywhere. I need to be able to set the variable depending on the selection the user makes from the ListAdapter onclick. I just can't figure out how to code this. I also need to use that variable for if statements. Sorry I am new to this :)
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_flavor);
String[] select_flavor_list = {"Kansas City", "Memphis", "Texas", "North Carolina", "South Carolina","Alabama"};
ListAdapter FlavorListAdapter = new ArrayAdapter<String>(this, R.layout.row_layout_flavor, R.id.flavor_text_view,
select_flavor_list);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(FlavorListAdapter);
//For list view selection, begin here...
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
GlobalClass flavorPref = ((GlobalClass)getApplicationContext());
flavorPref.setFlavorPreference(String a) = String.valueOf(adapterView.getItemAtPosition(position));
if (flavorPref.equals("Kansas City")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "test " + flavorPref,
Toast.LENGTH_LONG).show();
}
else if (flavorPicked.equals("Memphis")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "test " + flavorPref,
Toast.LENGTH_LONG).show();
}
}
});
}
This is the Global class I created:
public class GlobalClass extends Application {
public String flavorPreference;
public String getFlavorPreference(){
return flavorPreference;
}
public void setFlavorPreference(String a){
flavorPreference = a;
}
}
You can use android shared preference to this kind of usage
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
Insert or Update Value
editor.putString("key_name", "string value");
Get Value
pref.getString("key_name", null);

how can I save my spinner input?

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.

Categories

Resources