【问题标题】:Problem with refreshing listview from a dialog window从对话框窗口刷新列表视图的问题
【发布时间】:2025-11-22 00:50:02
【问题描述】:

我有一个列表视图和我的 CursorAdapter 实现。作为一个 我的列表项的一部分我有一个删除按钮。当用户按下 按钮我显示一个对话框,要求确认,如果用户按下 好的,我从数据库中删除了该项目。问题在于刷新 列表视图。我尝试调用 cursor.requery() 和 mAdapter.notifyDataSetChanged() (单独或两者),但事实并非如此 帮助。重新查询清除列表并重新出现(没有丢失 item) 重新进入活动后。 notifyDataSetChanged 确实 什么都没有(该项目仍在列表中),并且在重新之后再次正常 进入活动。我已经设法使这个工作后 重新加载整个数据库:

 //in the dialog:
{
DBAdapter db = new DBAdapter( getApplicationContext() );
db.open();

db.deleteTitle( rowid );

db.close();

//cursor.requery();
//mAdapter.notifyDataSetChanged();

fillData();
}


private void fillData() {

                try{
                db.open();
                cursor = db.getAllTitles();
                startManagingCursor(cursor);

                 mAdapter = new MyIDsListCursorAdapters(this, R.layout.myidsrow,
cursor, columns, to);

                setListAdapter(mAdapter);
                db.close();
             }catch (SQLException e){
                showDatabaseErrorDialog ();
             }
         }

但是重新加载整个数据库似乎是一项非常昂贵的任务,我 很确定一定有更好的方法来做到这一点。

我还有另一个问题 - 我的列表视图项是由 相对布局。但是布局似乎忽略了所有“垂直” 属性,例如 alignParentBottom 或 centerVertical。我见过一个 谷歌 I/O 和 Romain Guy,他回答了一个类似的问题 说我们应该将父 ViewGroup 后跟 false 传递给 膨胀功能,但这仍然不能解决我的问题。不知道 这里发生了什么。我通过将我的物品放在一些下面来解决这个问题 其他人并使用边距/填充,但我不太喜欢 该解决方案。

【问题讨论】:

  • 你能在这里发布你的适配器实现吗?

标签: android database listview dialog refresh


【解决方案1】:

不推荐使用重新查询。 在我的实现中,我只是重新创建光标,这似乎工作。这是我的代码位。就我而言,我使用上下文菜单来标记列表视图中的项目,但基本方法应该适合您。

    private Cursor fetchCursor(){
    Intent intent = getIntent();
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        return mDbHelper.fetchSpellSearch(query);
    } else {
        return mDbHelper.fetchAllSpells();
    }
}

@Override  
public boolean onContextItemSelected(MenuItem item) {  
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
      case 0:
          mDbHelper.updateFavorite(info.id, 1);
          new bgRequery().execute();
          return true;
      case 1:
          mDbHelper.updateFavorite(info.id, 0);
          new bgRequery().execute();
          return true;
      default:
          return super.onContextItemSelected(item);
      }
}

private class bgRequery extends AsyncTask<Void, Integer, Void> {
    @Override
    protected Void doInBackground(Void... voids ) {
        mSpellCursor = fetchCursor();
        return null;
    }

【讨论】: