我有一个保存按钮,可以加载一个要求保存名称的对话框界面。当你点击完成它应该创建一个带有一些字符串的共享偏好,但它只是说不幸的是程序已经停止。我怎样才能解决这个问题?哦,我只是想把它放在那里,我是Android的新手。我正在学习所有这些东西,因为我制作了应用程序。
public void save(View view){
LayoutInflater li = LayoutInflater.from(Calculate.this);
View pView = li.inflate(R.layout.prompt, null);
AlertDialog.Builder adb = new AlertDialog.Builder(Calculate.this);
adb.setView(pView);
final EditText name = (EditText) findViewById(R.id.etPrompt);
adb.setCancelable(false);
adb.setPositiveButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
n = name.getText().toString();
try {
details = getSharedPreferences(n,MODE_PRIVATE);
editor = details.edit();
editor.putString("ebp", ebp.getText().toString());
editor.putString("fb", fb.getText().toString());
editor.putString("sv", sv.getText().toString());
editor.putString("pv", pv.getText().toString());
editor.putString("sl", sl.getText().toString());
editor.putString("cl", cl.getText().toString());
editor.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog ad = adb.create();
ad.show();
}
logcat的
05-18 20:54:28.300: E/AndroidRuntime(16575): FATAL EXCEPTION: main
05-18 20:54:28.300: E/AndroidRuntime(16575): java.lang.NullPointerException
05-18 20:54:28.300: E/AndroidRuntime(16575): at com.TBJsoft.enclosurecalculator.Calculate$1.onClick(Calculate.java:103)
05-18 20:54:28.300: E/AndroidRuntime(16575): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
05-18 20:54:28.300: E/AndroidRuntime(16575): at android.os.Handler.dispatchMessage(Handler.java:99)
05-18 20:54:28.300: E/AndroidRuntime(16575): at android.os.Looper.loop(Looper.java:137)
05-18 20:54:28.300: E/AndroidRuntime(16575): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-18 20:54:28.300: E/AndroidRuntime(16575): at java.lang.reflect.Method.invokeNative(Native Method)
05-18 20:54:28.300: E/AndroidRuntime(16575): at java.lang.reflect.Method.invoke(Method.java:511)
05-18 20:54:28.300: E/AndroidRuntime(16575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-18 20:54:28.300: E/AndroidRuntime(16575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-18 20:54:28.300: E/AndroidRuntime(16575): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
您需要使用Activities context
访问SharedPreferences
内的AlertDialog
。因此,您可以在AlertDialog
之外初始化它们,也可以将其更改为
details = Caluclate.this.getSharedPreferences(n,MODE_PRIVATE); // assuming that Calculate is the name of your `Activity`
如果这没有帮助那么请发布logcat,以便我们知道它崩溃的地方
修改强>
更改
final EditText name = (EditText) findViewById(R.id.etPrompt);
到
final EditText name = (EditText) pView.findViewById(R.id.etPrompt);