来自 AlertDialog 的 ArrayAdapter notifyDataSetChanged 不起作用

ArrayAdapter notifyDataSetChanged from AlertDialog doesn't work

我在列表视图中显示我的 SQLite 数据库中的项目。为了添加项目,我使用了 AlertDialog。在 ALertDialog 中,我将项目保存在我的数据库中,并使用数据库中的数据刷新列表 (userLists)。然后我使用 notifyDataSetChanged 但视图没有改变。

public class MediUserListsFragment extends Fragment {

    private MediDAO mediDAO;
    private ListView listView;
    private List<UserList> userLists;
    private ArrayAdapter<UserList> adapter;

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        getActivity().setTitle("Medikamenten Listen");

        final View view =  inflater.inflate(R.layout.fragment_medi_user_list, container, false);

        setHasOptionsMenu(true);

        mediDAO = new MediDAO(getContext());

        userLists = mediDAO.getAllUserList();

        listView = (ListView) view.findViewById(R.id.list_view);

        adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1, userLists);
        listView.setAdapter(adapter);

        Button newLstBtn = (Button) view.findViewById(R.id.new_list_button);
        newLstBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View alertLayout = inflater.inflate(R.layout.dialog_medi_list_new, null);
                final EditText newLstName = (EditText) alertLayout.findViewById(R.id.newListName);
                AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
                alert.setTitle("Neue Liste");
                alert.setView(alertLayout);
                alert.setCancelable(false);
                alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                alert.setPositiveButton("Erstellen", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mediDAO.newUserList(newLstName.getText().toString());
                        userLists = mediDAO.getAllUserList();
                        adapter.notifyDataSetChanged();
                    }
                });
                AlertDialog dialog = alert.create();
                dialog.show();
            }
        });

        return view;
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_medi_abc, menu);
    }
}

在您的 setPositiveButton 中,尝试以下操作。

userLists.clear();
userLists.addAll(mediDAO.getAllUserList());                      
adapter.notifyDataSetChanged();

当您执行 userLists = mediDAO.getAllUserList(); 时,适配器会丢失原始数据对象的引用(即 userLists)。使用 userLists.addAll(),适配器知道它创建的数据对象已更改,因此,notifyDataSetChanged 发现要通知的更改。