TestDatabase.java


The class TestDatabase.java is the main class of this application. It includes the following four methods: The program is explained line-by-line as follows:
import java.util.List;
A List is a collection which maintains an ordering for its elements. Every element in the List has an index. Each element can thus be accessed by its index, with the first index being zero.

import java.util.Random;
This class provides methods that return pseudo-random values.

import android.app.ListActivity;
ListActivity hosts a ListView object that can be bound to different data sources, typically either an array or a Cursor holding query results.

import android.widget.ArrayAdapter;
ListView gets the data to display via an adapter. An Adapter extends BaseAdapter and is responsible for providing the data model for the list and for converting the data into the fields of the list.
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( );
  }
}