2016-01-20 69 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); 

} 

有了这个,你将门更新的结果。

相关问题