android - EditText 值无法在警报对话框中更新
问题描述
我正在尝试editText
在弹出对话框中添加用户编写笔记/任务但editText
单击“添加”按钮后无法保存中的值,消息未显示在ListView
. 这是代码:
public class MainActivity extends AppCompatActivity {
private ListView listView;
public static ArrayList<String> notes = new ArrayList<>();
public static CustomAdapter arrayAdapter;
private CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
ListView listView = (ListView) findViewById(R.id.listView);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
SharedPreferences sharedPreferences =
getApplicationContext().getSharedPreferences
("com.example.assignment2", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>)
sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Empty");
} else {
notes = new ArrayList(set);
}
arrayAdapter = new CustomAdapter
(this, R.layout.simplerow, notes);
listView.setAdapter(arrayAdapter);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final EditText input = new EditText(MainActivity.this);
AlertDialog ad = new AlertDialog.Builder(MainActivity.this)
.setTitle("Add Task")
.setMessage("Enter Message")
.setIcon(android.R.drawable.ic_input_add)
.setView(input)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String task = input.getText().toString();
notes.add(task);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences =
getApplicationContext().getSharedPreferences
("com.example.assignment2",
Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(notes);
sharedPreferences.edit().putStringSet("notes", set).commit();
}
})
.setNegativeButton("Cancel", null)
.create();
ad.show();
}
});
对话框看起来像这样。我期待消息将被保存并在单击“添加”按钮后显示在这里 有人愿意帮忙吗?:( notes是一个ArrayList。
解决方案
在Activity的onCreate方法中移动这行颂歌。
private SharedPreferences sharedPreferences;
在 onCreate
sharedPreferences = getApplicationContext()
.getSharedPreferences("com.example.assignment2",
Context.MODE_PRIVATE);
推荐阅读
- hibernate - Hibernate 从 manyTomany 关系中删除实体
- javascript - 如何使用纯 JavaScript 获取数组中所有选中的复选框?
- java - 无法运行基于 Java 10 的 Spring Initializer 创建的基于 Maven 的 Spring 项目
- stackexchange-api - 如何获得徽章授予时间的时间戳?
- javascript - 我如何使它成为多个匹配项?
- python-3.x - Pygame 无法在屏幕上方绘制
- ssl - 如何从 cert9 生成 cert7.db。使用 certutil
- c - C:将整数值翻转为布尔值
- c# - 我的套接字服务器例程可以工作吗?
- java - Spring mvc - 初始加载页面问题