0
Spinnerコントロールを使用して名前を保存するアプリを作っていますが、Null Pointer Exceptionを与え続けます。Spinnerコントロールの共有環境設定でヌルポインタ例外が発生する
それは言う:
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
ここ
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);
}
}
また、[スタックトレースとは何ですか](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it- to-debug-my-application-errors) –