SQLite DB を操作するには、SQLiteOpenHelper から拡張できます。ここに最初のステップのいくつかがあります。クラスの作成と DB の操作:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class DBHelper extends SQLiteOpenHelper {
public static interface CONTACT extends BaseColumns {
String TABLE_NAME = "human";
String FIRST_NAME = "first_name";
String LAST_NAME = "last_name";
}
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
private static final String DATABASE_NAME = "someDataBase";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_TABLE_CONTACT = CREATE_TABLE + CONTACT.TABLE_NAME + " (" + CONTACT._ID
+ " INTEGER PRIMARY KEY," + CONTACT.FIRST_NAME + " TEXT, " + CONTACT.LAST_NAME + " TEXT);";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_CONTACT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS " + CONTACT.TABLE_NAME);
onCreate(db);
}
public Cursor getAllContacts() {
return getReadableDatabase().query(CONTACT.TABLE_NAME, null, null, null, null, null, null);
}
public void insertContact(String firstName, String lastName) {
final ContentValues values = new ContentValues();
values.put(CONTACT.FIRST_NAME, firstName);
values.put(CONTACT.LAST_NAME, lastName);
getWritableDatabase().insert(CONTACT.TABLE_NAME, null, values);
}
}
ListView を使用したシンプルなレイアウト:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="垂直" >
<ListView
android:id="@+id/testList"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
そしてそれを使用するアクティビティ:
import java.util.Random;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity {
private DBHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
//useless part to insert some data
Random rand = new Random();
for (int i = 0; i < 20; i++) {
db.insertContact("" + i, "" + rand.nextInt(100));
}
Cursor allContacts = db.getAllContacts();
ListView testList = (ListView) findViewById(R.id.testList);
testList.setAdapter(new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, allContacts,
new String[] { DBHelper.CONTACT.FIRST_NAME, DBHelper.CONTACT.LAST_NAME }, new int[] {
android.R.id.text1, android.R.id.text2 }));
}
}