3

SimpleCursorAdapter として作成された ListAdapter を使用する ListView を更新しようとしています。

これは、ListView に入力する onCreate で Cursor と ListAdapter を作成するための私のコードです。

tCursor = db.getAllEntries();       

ListAdapter adapter=new SimpleCursorAdapter(this,
                R.layout.row, tCursor,
                new String[] columns,
                new int[] {R.id.rowid, R.id.date});

setListAdapter(adapter);

次に、別の方法でデータベースにデータを追加しますが、ListView を更新する方法がわかりません。stackoverflow および他の場所に関する同様の質問は、notifyDataSetChanged() および requery() の使用について言及していますが、どちらも ListAdapter または SimpleCursorAdapter のメソッドではありません。

4

4 に答える 4

5

新しいアダプタを作成し、setListAdapterを再度呼び出すことで、ListViewを更新できます。

他の方法でadapter2という名前を付けました。

tCursor = db.updateQuery();       

ListAdapter adapter2=new SimpleCursorAdapter(this,
                R.layout.row, tCursor,
                columns,
                new int[] {R.id.rowid, R.id.date});

setListAdapter(adapter2);

なぜこれが必要なのかわかりませんが、今のところは機能します。誰かがより良い解決策を持っているなら、私はそれを試してみるつもりです。

于 2011-02-25T05:23:55.173 に答える
0

メソッドnotifyDataSetChangedSimpleCursorAdapter親クラスから取得されBaseAdapterます。親が実装ListAdapterしており、それを に渡すことができるはずですListView

試す:

tCursor = db.getAllEntries();       

BaseAdapter adapter=new SimpleCursorAdapter(this,
            R.layout.row, tCursor,
            new String[] columns,
            new int[] {R.id.rowid, R.id.date});

setListAdapter(adapter);


その後、使用できるはずですnotifyDataSetChanged

于 2011-02-25T05:09:26.653 に答える
0

同じクラスの他のメソッドからアクセスする必要がある場合は、アダプタをクラス変数として定義できます。changeCursor()その後、呼び出して ListView を更新できます。

public class mainActivity extends AppCompatActivity {
    // Define the Cursor variable here so it can be accessed from the entire class.
    private SimpleCursorAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_coordinator_layout)

        // Get the initial cursor
        Cursor tCursor = db.getAllEntries();       

        // Setup the SimpleCursorAdapter.
        adapter = new SimpleCursorAdapter(this,
            R.layout.row,
            tCursor,
            new String[] { "column1", "column2" },
            new int[] { R.id.rowid, R.id.date },
            CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        // Populate the ListAdapter.
        setListAdapter(adapter);
    }

    protected void updateListView() {
        // Get an updated cursor with any changes to the database.
        Cursor updatedCursor = db.getAllEntries();

        // Update the ListAdapter.
        adapter.changeCursor(updatedCursor);
    }
}

リスト ビューを別のクラスのメソッドから更新する必要がある場合は、public static代わりにアダプター変数を宣言する必要があります。

public static SimpleCursorAdapter adapter;
于 2016-06-28T23:55:52.137 に答える
0

その場合、クラスAdapterを拡張して custom を使用することをお勧めします。BaseAdapter

于 2011-02-25T03:54:12.323 に答える