关闭对话框片段后如何从数据库刷新列表视图?

How to refresh listview from database after dismissing a dialog fragment?

我有一个列表视图,其中包含存储在数据库中的项目。单击每个项目时,会弹出一个对话框片段,其中包含用于编辑和删除的按钮。单击删除时,该项目将从数据库中删除,并且对话框片段被关闭。但是,在列表视图所在的主 activity 上,数据没有更新。它仍然显示我删除的项目。请问有什么帮助吗?

以下是代码片段:

/*******MainActivity*********/

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private ListView taskListView;
    private DataModel data;
    private DatabaseHandler db = new DatabaseHandler(this);
    private SimpleCursorAdapter adapter;
    private Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        taskListView = (ListView) findViewById(R.id.task_list_view);

        refreshListView();

    }

    private void showPopupDialog(String[] taskDetails) {
        FragmentManager fm = getSupportFragmentManager();
        PopupFragment pf = PopupFragment.newInstance(taskDetails);
        pf.show(fm,"activity_popup_fragment");
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        int currentPosition;
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.edit:
                Toast.makeText(this,"Task Completed",Toast.LENGTH_LONG).show();
                return true;
            case R.id.delete:
                Toast.makeText(this,"Task Deleted",Toast.LENGTH_LONG).show();
                db.deleteTask((int)info.id);
                refreshListView();
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    protected void refreshListView() {

        cursor = db.queueAllTasks();
        String[] from = new String[] {"taskName","taskDesc","taskDate","taskTime","id"};
        int[] to = new int[] {R.id.text};
        adapter = new SimpleCursorAdapter(this, R.layout.row_item, cursor, from, to);
        taskListView.setAdapter(adapter);
        taskListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Cursor cursor = (Cursor) taskListView.getItemAtPosition(i);
                String taskDetails[] = {cursor.getString(cursor.getColumnIndexOrThrow("taskName")),
                                        cursor.getString(cursor.getColumnIndexOrThrow("taskDesc")),
                                        cursor.getString(cursor.getColumnIndexOrThrow("taskDate")),
                                        cursor.getString(cursor.getColumnIndexOrThrow("taskTime")),
                                        cursor.getString(cursor.getColumnIndexOrThrow("id"))};
                showPopupDialog(taskDetails);
            }
        });

        registerForContextMenu(taskListView);

    }

/***********PopupFragment***********/

public class PopupFragment extends DialogFragment {

    TextView name, desc, reminder;
    String remindAt;
    Button delBtn, editBtn;
    DatabaseHandler db;

    public PopupFragment() {

    }

    public static PopupFragment newInstance(String[] taskDetails) {

        PopupFragment frag = new PopupFragment();
        Bundle args = new Bundle();
        args.putString("TaskName", taskDetails[0]);
        args.putString("TaskDesc", taskDetails[1]);
        args.putString("TaskDate", taskDetails[2]);
        args.putString("TaskTime", taskDetails[3]);
        args.putInt("TaskId", Integer.parseInt(taskDetails[4]));
        frag.setArguments(args);
        return frag;

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_popup_fragment,container);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        name = (TextView) view.findViewById(R.id.popTaskName);
        desc = (TextView) view.findViewById(R.id.popTaskDesc);
        delBtn = (Button) view.findViewById(R.id.del_btn);
        editBtn = (Button) view.findViewById(R.id.edit_btn);
        reminder = (TextView) view.findViewById(R.id.popTaskRemind);
        db = new DatabaseHandler(getActivity());
        remindAt = "Remind me on "+getArguments().getString("TaskDate") +" at "+ getArguments().getString("TaskTime");

        name.setText(getArguments().getString("TaskName"));
        desc.setText(getArguments().getString("TaskDesc"));
        reminder.setText(remindAt);
        delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                db.deleteTask(getArguments().getInt("TaskId"));
                getDialog().dismiss();
                Toast.makeText(getContext(),"Task Deleted",Toast.LENGTH_LONG).show();
            }
        });

        editBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(),EditTask.class);
                intent.putExtra("TaskId", getArguments().getInt("TaskId"));
                intent.putExtra("TaskName", getArguments().getString("TaskName"));
                intent.putExtra("TaskDesc", getArguments().getString("TaskDesc"));
                intent.putExtra("TaskDate", getArguments().getString("TaskDate"));
                intent.putExtra("TaskTime", getArguments().getString("TaskTime"));
                startActivity(intent);
            }
        });
    }

提前致谢!

您可以从您的片段中回调到 main activity 以更新数据。添加一个 public 方法到你的 MainActivity:

public void onUpdate()
{
   refreshListView();
}

当您删除内容时,在您的片段中,在您的点击侦听器中使用以下内容:

       public void onClick(View view) {
            db.deleteTask(getArguments().getInt("TaskId"));
            getDialog().dismiss();
            Toast.makeText(getContext(),"Task Deleted",Toast.LENGTH_LONG).show();
             MainActivity activity = (MainActivity) getActivity();
             activity.onUpdate();
        }

为什么不直接使用 DialogFragment 上的内置监听器呢?你可以这样做:

PopupFragment pf = PopupFragment.newInstance(taskDetails);
pf.onDismiss(new DialogInterface() {
    @Override
    public void cancel() {

    }

    @Override
    public void dismiss() {
        refreshListView();
    }
});

然后从您的数据库中提取数据,将其传递给您的适配器,然后 notifyDataSetChanged() 将更新视图。

您可以在显示 PopupFragment 之前覆盖 MainActivity 和 setTargetFragment 中的 onActivityResult(int requestCode, int resultCode, Intent data) ,如下所示:

pf.setTargetFragment(这个,1);

在关闭对话框之前的片段对话框中,您必须调用 getTargetFragment().onActivityResult(/* parameters */) 然后关闭对话框。

最后在您的 activityResult 中调用 refreshListView()。