2016-01-20 101 views
0

我實現了CursorAdapter,但無法在數據庫中添加新記錄時更新listview光標適配器Android

我的代碼是

光標獲取數據庫中的數據

// TodoDatabaseHandler is a SQLiteOpenHelper class connecting to SQLite 
TodoDatabaseHandlerhandler = new TodoDatabaseHandler(this); 
// Get access to the underlying writeable database 
SQLiteDatabase db = handler.getWritableDatabase(); 
// Query for items from the database and get a cursor back 
Cursor todoCursor = db.rawQuery("SELECT * FROM todo_items", null); 

ListView控件初始化

// Find ListView to populate 
ListView lvItems = (ListView) findViewById(R.id.lvItems); 
// Setup cursor adapter using cursor from last step 
TodoCursorAdapter todoAdapter = new TodoCursorAdapter(this, todoCursor); 
// Attach cursor adapter to the ListView 
lvItems.setAdapter(todoAdapter); 

CursorAdapter類。

public class TodoCursorAdapter extends CursorAdapter { 
    public TodoCursorAdapter(Context context, Cursor cursor, int flags) { 
     super(context, cursor, 0); 
    } 

    // The newView method is used to inflate a new view and return it, 
    // you don't bind any data to the view at this point. 
    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
     return LayoutInflater.from(context).inflate(R.layout.item_todo, parent, false); 
    } 

    // The bindView method is used to bind all data to a given view 
    // such as setting the text on a TextView. 
    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
     // Find fields to populate in inflated template 
     TextView tvBody = (TextView) view.findViewById(R.id.tvBody); 
     TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority); 
     // Extract properties from cursor 
     String body = cursor.getString(cursor.getColumnIndexOrThrow("body")); 
     int priority = cursor.getInt(cursor.getColumnIndexOrThrow("priority")); 
     // Populate fields with extracted properties 
     tvBody.setText(body); 
     tvPriority.setText(String.valueOf(priority)); 
    } 
} 
+0

你有什麼問題? –

+0

當我添加新的記錄listview不更新 – Yash

回答

1

試試這個,

public void updateList(){ 
    // Get access to the underlying writeable database 
    SQLiteDatabase db = handler.getWritableDatabase(); 
    // Query for items from the database and get a cursor back 
    Cursor newCursor= db.rawQuery("SELECT * FROM todo_items", null); 

    // here updated records are added in your cursor 
    todoAdapter.changeCursor(newCursor); 

} 

有了這個,你將門更新的結果。

相關問題