Tuesday, October 28, 2014

Android SQLite Example

 Stress out to find a good example of `How to Android SQLite` had leaded me
to collect piece-by-piece. The result a working apk that uses SQLite as database. The example below is from |1| but with little changes

MainActivity.java

package com.example.webview2;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

 // Constants
 public static final String DATABASE_NAME = "highscores.db";
 public static final String HIGH_SCORE_TABLE = "highscore";
 public static final String COLUMN_ID = "ID";
 public static final String COLUMN_SCORE = "SCORE";
 public static final String COLUMN_NAME = "NAME";

 public static SQLiteDatabase scoreDB;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  final EditText editTextName = (EditText) findViewById(R.id.editTextName);
  final EditText editTextScore = (EditText) findViewById(R.id.editTextHighScore);
  final WebView webview = (WebView) findViewById(R.id.webview);


  // initial the database

  Button saveHighScore = (Button) findViewById(R.id.buttonSaveHighScore);

  OnClickListener clickListener = new OnClickListener() {

   @Override
   public void onClick(View v) {

    // First get the values from the EditText
    String name = editTextName.getText().toString();
    int score = 0;

    try {
     score = Integer
       .parseInt(editTextScore.getText().toString());
    } catch (NumberFormatException e) {
     return;
    }

    // Add the values
    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME, name);
    values.put(COLUMN_SCORE, score);
    scoreDB.insert(HIGH_SCORE_TABLE, null, values);


    // Retrieve the new list of scores
    readData(webview);

   }
  };

  saveHighScore.setOnClickListener(clickListener);

  initDB();

  readData(webview);
 }

  public void initDB()
  {
    scoreDB = openOrCreateDatabase(DATABASE_NAME,
      SQLiteDatabase.CREATE_IF_NECESSARY
        | SQLiteDatabase.OPEN_READWRITE, null);

    scoreDB.execSQL("CREATE TABLE IF NOT EXISTS " + HIGH_SCORE_TABLE + " ("
      + COLUMN_ID + " INTEGER PRIMARY KEY, " + COLUMN_NAME
      + " VARCHAR, " + COLUMN_SCORE + " INT)");
  }
 
 public void readData(WebView webview){

    Cursor c = scoreDB.query(HIGH_SCORE_TABLE, new String[] {
      COLUMN_NAME, COLUMN_SCORE }, null, null, null, null,
      COLUMN_SCORE + " DESC ");

    StringBuilder builder = new StringBuilder();
    builder.append("

High Scores

"); c.moveToFirst(); for(int i=c.getCount()-1; i>=0; i--) { // Get the data builder.append(" "); // Move the cursor c.moveToNext(); } builder.append("
"); builder.append(c.getString(0)); builder.append(""); builder.append(c.getString(1)); builder.append("
"); webview.loadData(builder.toString(), "text/html", "UTF-8"); // Close the cursor c.close(); } @Override protected void onResume() { super.onResume(); initDB(); } @Override protected void onPause() { super.onPause(); if (scoreDB.isOpen()) { scoreDB.close(); } } }

For some of you who new to Android development then you could
continue to below instructions. For those who needs quick snippet
hope the code above will help.

1. Linux OS, i am using Fedora19 64bit. If you are using
    winOS or MaxOS you need to consult the manual from the
    Android Developer Website
2. Android SDK dan NDK 64bit, i don't use ADT (Eclipse) so excuse me
    if the next instructions are Command Line related.
3. Follow this official Android Developer tutorial on how to build an apk
4. Once a project created, then simply copy-paste the code above
    MainActivity.java located under /src///MainActivity.java
    Wheren subX and SubY depends how you defined your package during
    project creation
5. $ android 
    The syntax above is to run the android manager and do some updates.
    Make sure the build tools for your API is installed. If you don't then
    `no build tools` error will address you that the build tools needs to be
    installed via the android manager.
6. $ ant debug
    I assumed the build process will successful. If error like
    no build tools or whatever, indicates that you have not installed the build
    tools as stated at #5
7. $ android avd
    To run the emulator, but you need to set the arm images using the android
    manager
8. $ adb install -r bin/yourapp-debug.apk
    There will be upload indicator shown. The command line above was
    taken from here and thank you the easy way of install/uninstall
9. Your apk supposed to be in the emulator by this point.

Internet references
|1| Android and SQLite
|2| Android Developer Data Storage

No comments: