我正在尝试在弹出对话框中添加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();
}
});
对话框看起来像this。 我期望该消息将被保存并在单击“添加”按钮后显示here 有人愿意帮助吗? :( 笔记是一个 ArrayList 。
答案 0 :(得分:0)
在Activity的onCreate方法中移动这行颂歌。
private SharedPreferences sharedPreferences;
在onCreate
sharedPreferences = getApplicationContext()
.getSharedPreferences("com.example.assignment2",
Context.MODE_PRIVATE);