我正在开发一个应用程序并希望保存我的复选框选项的 obe 状态,但是当我尝试使用 SharedPreferences 类(第一次使用它)时,我得到一个空指针异常。我已经进行了几个小时的故障排除,但找不到解决方案。任何人都可以看看这个并告诉我有什么问题吗?完整的代码要长得多,但这是给我空指针异常的公园。我知道它与 SharedPreferences 有关。
package us.mattmccoy.meanfind;
//import java.util.Arrays;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
//saved data stuff needed
SharedPreferences preferences = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
Editor edit = preferences.edit();
//private data using saved data
String autoclearKEY = "us.mattmccoy.meanfind.AUTOCLEAR";
boolean autoclear = preferences.getBoolean(autoclearKEY, false);
//normal private data
final Context con1 = this;
int dividend;String dataFixed;boolean tb;
private CheckBox myCBox, acBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerBoxes();
if(autoclear == true){
acBox.setChecked(true);
}else{
acBox.setChecked(false);
}
}
//check box listeners
public void addListenerBoxes(){
//instantiate boxes
acBox = (CheckBox) findViewById(R.id.chex2);
acBox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//is acBox checked?
if (((CheckBox) v).isChecked()) {
edit.putBoolean(autoclearKEY, true).commit();
}else{
edit.putBoolean(autoclearKEY, false).commit();
}
}
});
myCBox = (CheckBox) findViewById(R.id.chex);
}
错误信息: