簡體   English   中英

如何在更改連接的SimpleCursorAdapter的數據時更新Android ListActivity

[英]how to update an Android ListActivity on changing data of the connected SimpleCursorAdapter

我有以下代碼。 我想要實現的是單擊一個條目時更新顯示的列表,以便可以遍歷該列表。 我在stackoverflow上找到了兩種未注釋的方法來執行此操作,但是都沒有用。 我還得到了在數據更新上創建新的ListActivity的建議,但這聽起來像浪費資源嗎?

編輯:我自己找到了解決方案。 您需要做的就是調用“ SimpleCursorAdapter.changeCursor(new Cursor);”。 沒有通知,UI-Thread中沒有任何東西。

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MyActivity extends ListActivity {
    private DepartmentDbAdapter mDbHelper;
    private Cursor cursor;
    private String[] from = new String[] { DepartmentDbAdapter.KEY_NAME };
    private int[] to = new int[] { R.id.text1 };
    private SimpleCursorAdapter notes;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.departments_list);
    mDbHelper = new DepartmentDbAdapter(this);
    mDbHelper.open();

    // Get all of the departments from the database and create the item list
    cursor = mDbHelper.fetchSubItemByParentId(1);
    this.startManagingCursor(cursor);

    // Now create an array adapter and set it to display using our row
    notes = new SimpleCursorAdapter(this, R.layout.department_row, cursor, from, to);
    this.setListAdapter(notes);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        // get new data and update the list
        this.updateData(safeLongToInt(id));
    }

    /**
     * update data for the list
     * 
     * @param int departmentId id of the parent department
     */
    private void updateData(int departmentId) {     
        // close the old one, get a new one
        cursor.close();
        cursor = mDbHelper.fetchSubItemByParentId(departmentId);

    // change the cursor of the adapter to the new one
    notes.changeCursor(cursor);
    }

    /**
     * safely convert long to in to save memory
     * 
     * @param long l the long variable
     * 
     * @return integer
     */
    public static int safeLongToInt(long l) {
    if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (l + " cannot be cast to int without changing its value.");
    }
    return (int) l;
    }

}

數據更改時,您需要通知ListVIew。

adapter.notifyDataSetChanged();

在你的情況下。

notes.notifyDataSetChanged();

希望這可以幫助您...

首先,每次打開新光標時,關閉前一個光標並進行管理。

其次,您更改了光標,但是您的光標適配器如何知道呢? 沒有。 您可以創建可以更改其光標的適配器,也可以在新光標周圍創建一個新的SimpleCursorAdapter並將其插入列表。

但是您說對了,您不應該重新創建列表小部件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM