Saturday, October 18, 2014

6a. Java: Generic Type Interface

In this tutorial we will learn how to create an Interface that serves any type of object using Java Generic Types introduced in Java 1.5.


Step 1: Create interface


Note you can put it in any package, but this Interface is NOT your project specific, it is not even Android specific.


package com.cyberwalkabout.database;
import java.util.List;
/**
 * Created by uki on 10/11/14.
 * This interface simply assures that we don't forget to implement most important methods.
 * We are using Generic TYPE T as we don't know what objects we will be using in the database.
 * The TYPE T could stand for any object e.g. Book, Person, Address, etc.
 * You could add more methods of your own, or better method parameters.
 */
public interface DatabaseCrud<T> {
   /**
    * Saves an object to the database.
    */
   public void create(T object);
   /**
    * This methods reads one record by id.
    * Please notice it returns Generic Type T.
    */
   public T read(int dbRecordId);
   /**
    * fetches all objects that match the String searchText
    */
   public List<T> fetch(String searchText);
   /**
    * Update given object in the database.
    */
   public int update(T object);
   /**
    * Deletes given object from the database.
    */
   public void delete(T object);
}

Step 2: Implement the Interface in your specific database wrapper code

public class BookSqlHelper extends SQLiteOpenHelper implements DatabaseCrud<Book> {



Make sure you auto-copy JavaDocs from the Interface:



Step 3: Implement your generated methods



The IDE automatically generates method stubs like this:

    /**
     * Deletes given object from the database.
     *
     * @param object
     */
    @Override
    public void delete(Book object) {
     
    }



Now, you only have to fill in the blanks, note I changed name of the object from object to book:

    /**
     * Inserts a Book object to the database.
     * Please note that the Interface uses Generic Type T:
     * public void create(T object);
     */
    @Override
    public void create(Book book) {
        Log.w(TAG + "save()", book.toString());
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(FIELD__TITLE, book.getTitle());
        values.put(FIELD__AUTHOR, book.getAuthor());
        values.put(FIELD__ISBN, book.getIsbn());
        values.put(FIELD__LOCATION, book.getLocation());
        db.insert(TABLE_BOOKS, null, values);
        db.close();
    }