Two for the price of one in this tutorial, actually. We're going to learn about SQLite databases and menus. I'm hoping you'll at least be slightly familiar with databases already, though SQLite is really quite simple. You can pick up the basics, of which we'll be using in this tutorial, at the following links: It may look a little intimidating, but once you get to grips with it, it's actually quite close to English.
We won't be creating the most sexy application, but databases are an important aspect of a lot of software design, including android.

Let's get to it. As usual, we're creating a package:
package dreamincode.tutorials.dic_tut4;

...and we'll import the usual suspects.
import android.app.Activity; import android.os.Bundle;
Now there's quite a lot that we're going to import that hasn't already been covered, but do not panic. I'll explain it all as we go along, and it's honestly nothing to worry about. First up, a ListView. This is just another widget, and it's... well, it's a list.
import android.widget.ListView;
Next, we'll import the stuff related to the menu. We'll be using a Menu, and a couple of MenuItems.
import android.view.Menu; import android.view.MenuItem;
The next bits are related to the database. The first is self-explanatory, it's a database. The second is a Cursor. A cursor is a way we can store temporary results from a table in memory. (We select stuff into it, explained a little later... keep reading!)
import android.database.sqlite.SQLiteDatabase; import android.database.Cursor;
And finally, we're going to import an ArrayList to add our results into, and an ArrayAdapter to basically plug our ArrayList into the list. Again, this will be explained later, at this point all we really have is an overview.
import android.widget.ArrayAdapter; import java.util.ArrayList;
On to the main part of the code, now.
public class dic_tut4 extends Activity {
ListView list;
SQLiteDatabase db;
private static final int MENU_ADD = Menu.FIRST;
private static final int MENU_QUIT = Menu.FIRST + 1;
You'll see why we use these a little later. This is where it gets a little different. I'll give you one method at a time, and talk through each line.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.list = new ListView(this);
setContentView(this.list);
this.db = this.openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null);
this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)");
this.update_list();
}
So, the start is nothing new. Nothing to worry about here. Then we initialise the list. Nothing new here, either. It's exactly the same as when we created a dynamic layout in part 3. Then we do some new things with our database. First we use openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null);
-- this creates a database if it doesn't exist, or opens it if it does.
-- parameter 1 is the name of the database we're looking to create/open.
-- parameter 2 is the mode, doesn't require much explanation at this point. (Don't want to give you an information overload)
-- parameter 3, you don't even need to worry about. If you're interested, do some digging on CursorFactory.
Then another new line: this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)");
-- this will create a table if it doesn't already exist
-- it will add a single field into the table, called value. It is of type REAL, which is just like a double in Java.
And finally, this.update_list(); ... this is actually a custom method we'll be writing to query the database and populate the list. More info later, for now let's focus on the menu.
Creating a menu
Simple stuff actually. We use onCreateOptionsMenu(), which is called when the user hits the menu button.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ADD, 0, "Add").setIcon(android.R.drawable.ic_menu_add);
menu.add(0, MENU_QUIT, 0, "Quit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return super.onCreateOptionsMenu(menu);
}
We're simply adding 2 items: "Add", and "Quit". We also set the icons for them using some default android resources. If you want a full list, this site is pretty cool.
The next method we'll be using is onOptionsItemSelected(), which is called when the user selects an item in the menu. We use the IDs we assigned in onCreateOptionsMenu() MENU_ADD and MENU_QUIT to decide what to do.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case MENU_ADD:
db.execSQL("INSERT INTO table_of_dics(value) VALUES(" + String.valueOf(Math.random()) + ")");
this.update_list();
break;
case MENU_QUIT:
this.db.close();
this.finish();
}
return super.onOptionsItemSelected(item);
}
So, we're using a switch() to find the ID of the menu item which called this method. If it's add, we're going to perform some SQL and insert a random value into the table. Then we'll update the list, just like we did in onCreate(). (Remember, we're defining this method ourselves later)
If the user selected the "Quit" option, we'll simple close the database and finish the activity.
NOTE: The SQL used here, INSERT INTO will insert a random value into the table. Remember to refer to the links at the beginning if you get stuck on the SQL.
Lastly, we're going to define our method for updating the list. It's quite simple, but the code is quite different to what we've done so far. If you've ever done any database work through software/web before, you may notice a few similarities here. We basically execute the query. Then loop through each row in the result, adding it into an ArrayList. Lastly, we set the adapter for the list to display the arraylist we created. The code looks a tad complex, but it's really quite simple:
private void update_list() {
ArrayList<String> db_results = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null);
while(cursor.moveToNext()) {
db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value"))));
}
cursor.close();
this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, db_results));
}
I'll break this one up:
ArrayList<String> db_results = new ArrayList<String>(); -- create an ArrayList, where we'll store the results to display in the list.
Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null); -- create a cursor based on the query (this select statement will return all the values stored in the table, and order them)
while(cursor.moveToNext()) { -- while there is still something in the cursor to read (while we still have another row to read)
db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value")))); -- add the value from the row into the arraylist we created.
} -- this is self explanatory, really.
cursor.close(); -- close the cursor: we're done with it now. We have all our results in the ArrayList, which we can now set as the adapter:
this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, db_results)); -- set the adapter.
- parameter 1: the activity we want it for
- parameter 2: the layout type (we can add multiple widgets to a list item, but simple_list_item_1 is a default in android: simply a single TextView.
- parameter 3: the arraylist which we created and populated earlier.
And that's it! Don't forget to close off your class
}
Complete code:
package dreamincode.tutorials.dic_tut4;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.view.Menu;
import android.view.MenuItem;
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
public class dic_tut4 extends Activity {
ListView list;
SQLiteDatabase db;
private static final int MENU_ADD = Menu.FIRST;
private static final int MENU_QUIT = Menu.FIRST + 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.list = new ListView(this);
this.registerForContextMenu(this.list);
this.db = this.openOrCreateDatabase("dic_tut5", MODE_PRIVATE, null);
this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)");
this.update_list();
setContentView(this.list);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ADD, 0, "Add").setIcon(android.R.drawable.ic_menu_add);
menu.add(0, MENU_QUIT, 0, "Quit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case MENU_ADD:
db.execSQL("INSERT INTO table_of_dics(value) VALUES(" + String.valueOf(Math.random()) + ")");
this.update_list();
break;
case MENU_QUIT:
this.db.close();
this.finish();
}
return super.onOptionsItemSelected(item);
}
private void update_list() {
ArrayList<String> db_results = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null);
while(cursor.moveToNext()) {
db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value"))));
}
cursor.close();
this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, db_results));
}
}
Complete project:
dic_tut4.zip (28.67K)
Number of downloads: 1671
Enjoy!
This post has been edited by gabehabe: 08 October 2009 - 12:10 PM









MultiQuote










|