Thursday, October 16, 2014

8a. Android: populating ListView from the Databse

In this tutorial we will expand on the previous example showing basic SQLite CRUD methods. We will populate a list with results from the database.


Step 1: Create content for your database. 

We will use a separate object that provides the books, this way we keep our activity clean.

package com.chicagoandroid.cit299.week7.bookshelf;

import com.chicagoandroid.cit299.week7.bookshelf.model.Book;

import java.util.ArrayList;
import java.util.List;

/**
* Created by uki on 10/16/14.
* This class creates fake list of books,
* however it could import them from an XML file
* or fetch them from the Internet API.
*/
public class MockBookBuilder {

/**
* This is a static method that returns a list of mock books.
*/
public static List<Book> createBooks() {
Book book;
List<Book> books = new ArrayList<Book>();

// Create a new "empty" book with no properties.
book = new Book();

book.setAuthor("Reto Meier");
book.setTitle("Professional Android 4 Application Development");
book.setIsbn("1118102274");
book.setLocation("");
books.add(book);

// Create a new "empty" book with no properties.
book = new Book();

book.setAuthor("Paul Deitel, at al.");
book.setTitle("Android for Programmers An App-Driven Approach");
book.setIsbn("0-13-357092-4");
book.setLocation("");
books.add(book);

return books;
}
}

Step 2: adjust Activity onCreate() to populate ListView


import com.cyberwalkabout.activity.v7.actionbar.listview.ListViewSwipeActivity;

/**
* This class extends https://github.com/UkiDLucas/ListViewSwipeActivity
*/
public class MainActivity extends ListViewSwipeActivity {
private final static String TAG = MainActivity.class.getSimpleName();

/**
* UI element that displays books found.
*/
ListView booksListView;
/**
* bookIndexCards will help us keep track where is each book in the ListView.
*/
Map<Integer, Integer> bookIndexCards = new HashMap<Integer, Integer>();

/**
* Wrapper around Book database operations.
*/
BookSqlHelper bookDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
booksListView = (ListView) findViewById(R.id.booksListView);

bookDatabase = new BookSqlHelper(this);
addNewBooksToDatabase();
}

@Override
protected void onResume() {
super.onResume();
displayAllDataBaseBooks();
}

Step: 


   private void addNewBooksToDatabase() {
      String tag = TAG + ".addNewBooksToDatabase()";
      List<Book> fetchedBooks;
      // We save all books, one-by-one to database.
      for (Book book : MockBookBuilder.createBooks()) {
         // Comparing Books by only Title is not the best idea, it may lead to unexpected results.
         fetchedBooks = bookDatabase.fetch(book.getTitle());
         if (fetchedBooks.size() > 0) {
            Log.i(tag, "Found this book in the database, not adding!");
         }
         else {
            Log.i(tag, "New book, adding: " + book.toString());
            bookDatabase.save(book);
         }
      }
   }


Step: 

   private void displayAllDataBaseBooks() {
      List<String> resultList = new ArrayList<String>();
      List<Book> databaseBooks = bookDatabase.fetchAll();
      bookIndexCards.clear();
      int index = 0;
      for (Book book : databaseBooks) {
         bookIndexCards.put(index, book.getId());
         resultList.add(book.toString());
         index++;
      }
      final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, resultList);
      booksListView.setAdapter(adapter);
   }