我正在创建一个应用程序来保存名称并使用Spinner控件,但它一直给我一个Null Pointer Exception。
它说:
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);
}
}
答案 0 :(得分:1)
您用于编辑数据的编辑器对象为null,只需写入
editor = prefs .edit();
下面
prefs = getSharedPreferences("settings", MODE_PRIVATE);
在您的onCreate()
方法中,所有内容都将按计划进行。您正在使用特定方法初始化编辑器,这会使您的内容变得模棱两可。