0
我正在做一个页面,3个按钮“保存”,这将保存文本,“VIew”将显示刚刚保存的文本,“干净”将清理保存的数据。按钮保存和查看Android
当我运行下面的代码,应用程序发生冲突并停止运行,但它没有显示任何错误 我应该改变什么?
谢谢!
public class MainActivity extends Activity implements View.OnClickListener {
EditText editTextName;
final String PREFS_NAME = "AOP_PREFS";
public static final String PREFS_KEY = "AOP_PREFS_String";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText)findViewById(R.id.editText);
Button saveButton = (Button)findViewById(R.id.save);
Button viewButton = (Button)findViewById(R.id.show);
Button cleanButton = (Button)findViewById(R.id.clear);
saveButton.setOnClickListener(this);
viewButton.setOnClickListener(this);
cleanButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.save) {
String name = editTextName.getText().toString();
SharedPreferences.Editor editor;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //Step 1
editor = settings.edit(); // Step 2
editor.putString(PREFS_KEY, name); // Step 3
editor.commit(); // Step 4
}
if (v.getId() == R.id.show) {
SharedPreferences settings;
String name;
SharedPreferences setting = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
name = setting.getString(PREFS_KEY, null); //2
TextView textview1 = (TextView) findViewById(R.id.textView);
textview1.setText(name);
}
if (v.getId() == R.id.clear) {
SharedPreferences settings;
SharedPreferences.Editor editor;
SharedPreferences set = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = set.edit();
editor.clear();
editor.commit();
}
}
检查logcat的 – Aakash
清理项目,清洁你的logcat,并在明显的,如果你不是以前添加它添加活动。 –
你应该在'manifest.xml'文件中检查你的'MainActivity.java'(也是'package name'),并检查你的按钮和编辑文本是否在你的'activity_main.xml'中有相同的id –