add
and delete
are defined in the file main.xml
.
comments
with three elements nextInt(int n)
returns a pseudo-random uniformly distributed integer in the half-open range [0, n)
.
CommentsDataSource
is this application’s DAO (data access object), which provides an abstract interface to a database.
The method createComment
, which adds a new comment to the database and returns the comment, is implemented as follows:
public Comment createComment( String comment ) { ContentValues values = new ContentValues( ); values.put( MySQLiteHelper.COLUMN_COMMENT, comment ); long insertId = database.insert( MySQLiteHelper.TABLE_COMMENTS, null, values ); Cursor cursor = database.query( MySQLiteHelper.TABLE_COMMENTS, allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null ); cursor.moveToFirst( ); return cursorToComment( cursor ); }
src/main/java/com/example/wenchen/sqlitedemo/TestDatabase.java |
package com.example.wenchen.sqlitedemo; import java.util.List; import java.util.Random; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; public class TestDatabase extends ListActivity { private CommentsDataSource datasource; @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.main ); datasource = new CommentsDataSource( this ); datasource.open( ); List<Comment> values = datasource.getAllComments( ); // Use the SimpleCursorAdapter to show the elements in a ListView. ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>( this, android.R.layout.simple_list_item_1, values ); setListAdapter( adapter ); } // Will be called via the onClick attribute of the buttons in main.xml. public void onClick( View view ) { @SuppressWarnings( "unchecked" ) ArrayAdapter<Comment> adapter = ( ArrayAdapter<Comment> ) getListAdapter( ); Comment comment = null; int id = view.getId( ); if ( id == R.id.add ) { String[ ] comments = new String[ ] { "Cool", "Very nice", "Hate it" }; int nextInt = new Random( ).nextInt( 3 ); // Save the new comment to the database. comment = datasource.createComment( comments[nextInt] ); adapter.add( comment ); } else if ( id == R.id.delete ) { if ( getListAdapter( ).getCount( ) > 0 ) { comment = (Comment) getListAdapter( ).getItem( 0 ); datasource.deleteComment( comment ); adapter.remove( comment ); } } adapter.notifyDataSetChanged( ); } @Override protected void onResume( ) { datasource.open( ); super.onResume( ); } @Override protected void onPause( ) { datasource.close( ); super.onPause( ); } } |