extends SQLiteOpenHelper to Manage your database
/* Copyright (c) 2008-2009 -- CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app.test;
import java.util.HashMap;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
class Provider extends ContentProvider {
private static final String DATABASE_NAME = "constants.db";
private static final int CONSTANTS = 1;
private static final int CONSTANT_ID = 2;
private static final UriMatcher MATCHER;
private static HashMap<String, String> CONSTANTS_LIST_PROJECTION;
public static final class Constants implements BaseColumns {
public static final Uri CONTENT_URI = Uri
.parse("content://com.commonsware.android.constants.Provider/constants");
public static final String DEFAULT_SORT_ORDER = "title";
public static final String TITLE = "title";
public static final String VALUE = "value";
}
static {
MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
MATCHER.addURI("com.commonsware.android.constants.Provider",
"constants", CONSTANTS);
MATCHER.addURI("com.commonsware.android.constants.Provider",
"constants/#", CONSTANT_ID);
CONSTANTS_LIST_PROJECTION = new HashMap<String, String>();
CONSTANTS_LIST_PROJECTION.put(Provider.Constants._ID,
Provider.Constants._ID);
CONSTANTS_LIST_PROJECTION.put(Provider.Constants.TITLE,
Provider.Constants.TITLE);
CONSTANTS_LIST_PROJECTION.put(Provider.Constants.VALUE,
Provider.Constants.VALUE);
}
public String getDbName() {
return (DATABASE_NAME);
}
public int getDbVersion() {
return (1);
}
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
Cursor c = db
.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table' AND name='constants'",
null);
try {
if (c.getCount() == 0) {
db.execSQL("CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, value REAL);");
ContentValues cv = new ContentValues();
cv.put(Constants.TITLE, "Gravity, Death Star I");
cv.put(Constants.VALUE, SensorManager.GRAVITY_DEATH_STAR_I);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Earth");
cv.put(Constants.VALUE, SensorManager.GRAVITY_EARTH);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Jupiter");
cv.put(Constants.VALUE, SensorManager.GRAVITY_JUPITER);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Mars");
cv.put(Constants.VALUE, SensorManager.GRAVITY_MARS);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Mercury");
cv.put(Constants.VALUE, SensorManager.GRAVITY_MERCURY);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Moon");
cv.put(Constants.VALUE, SensorManager.GRAVITY_MOON);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Neptune");
cv.put(Constants.VALUE, SensorManager.GRAVITY_NEPTUNE);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Pluto");
cv.put(Constants.VALUE, SensorManager.GRAVITY_PLUTO);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Saturn");
cv.put(Constants.VALUE, SensorManager.GRAVITY_SATURN);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Sun");
cv.put(Constants.VALUE, SensorManager.GRAVITY_SUN);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, The Island");
cv.put(Constants.VALUE, SensorManager.GRAVITY_THE_ISLAND);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Uranus");
cv.put(Constants.VALUE, SensorManager.GRAVITY_URANUS);
db.insert("constants", getNullColumnHack(), cv);
cv.put(Constants.TITLE, "Gravity, Venus");
cv.put(Constants.VALUE, SensorManager.GRAVITY_VENUS);
db.insert("constants", getNullColumnHack(), cv);
}
} finally {
c.close();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.w("Constants",
"Upgrading database, which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS constants");
onCreate(db);
}
}
private SQLiteDatabase db;
@Override
public boolean onCreate() {
db = (new DatabaseHelper(getContext())).getWritableDatabase();
return (db == null) ? false : true;
}
@Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(getTableName());
if (isCollectionUri(url)) {
qb.setProjectionMap(getDefaultProjection());
} else {
qb.appendWhere(getIdColumnName() + "="
+ url.getPathSegments().get(1));
}
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = getDefaultSortOrder();
} else {
orderBy = sort;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), url);
return c;
}
@Override
public String getType(Uri url) {
if (isCollectionUri(url)) {
return (getCollectionType());
}
return (getSingleType());
}
@Override
public Uri insert(Uri url, ContentValues initialValues) {
long rowID;
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
if (!isCollectionUri(url)) {
throw new IllegalArgumentException("Unknown URL " + url);
}
for (String colName : getRequiredColumns()) {
if (values.containsKey(colName) == false) {
throw new IllegalArgumentException("Missing column: " + colName);
}
}
populateDefaultValues(values);
rowID = db.insert(getTableName(), getNullColumnHack(), values);
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(getContentUri(), rowID);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
throw new SQLException("Failed to insert row into " + url);
}
@Override
public int delete(Uri url, String where, String[] whereArgs) {
int count;
long rowId = 0;
if (isCollectionUri(url)) {
count = db.delete(getTableName(), where, whereArgs);
} else {
String segment = url.getPathSegments().get(1);
rowId = Long.parseLong(segment);
count = db.delete(
getTableName(),
getIdColumnName()
+ "="
+ segment
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), whereArgs);
}
getContext().getContentResolver().notifyChange(url, null);
return count;
}
@Override
public int update(Uri url, ContentValues values, String where,
String[] whereArgs) {
int count;
if (isCollectionUri(url)) {
count = db.update(getTableName(), values, where, whereArgs);
} else {
String segment = url.getPathSegments().get(1);
count = db.update(
getTableName(),
values,
getIdColumnName()
+ "="
+ segment
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), whereArgs);
}
getContext().getContentResolver().notifyChange(url, null);
return count;
}
private boolean isCollectionUri(Uri url) {
return (MATCHER.match(url) == CONSTANTS);
}
private HashMap<String, String> getDefaultProjection() {
return (CONSTANTS_LIST_PROJECTION);
}
private String getTableName() {
return ("constants");
}
private String getIdColumnName() {
return ("_id");
}
private String getDefaultSortOrder() {
return ("title");
}
private String getCollectionType() {
return ("vnd.android.cursor.dir/vnd.commonsware.constant");
}
private String getSingleType() {
return ("vnd.android.cursor.item/vnd.commonsware.constant");
}
private String[] getRequiredColumns() {
return (new String[] { "title" });
}
private void populateDefaultValues(ContentValues values) {
Long now = Long.valueOf(System.currentTimeMillis());
Resources r = Resources.getSystem();
if (values.containsKey(Provider.Constants.VALUE) == false) {
values.put(Provider.Constants.VALUE, 0.0f);
}
}
private String getNullColumnHack() {
return ("title");
}
private Uri getContentUri() {
return (Provider.Constants.CONTENT_URI);
}
}
public class Test extends ListActivity {
private static final int ADD_ID = Menu.FIRST + 1;
private static final int EDIT_ID = Menu.FIRST + 2;
private static final int DELETE_ID = Menu.FIRST + 3;
private static final int CLOSE_ID = Menu.FIRST + 4;
private static final String[] PROJECTION = new String[] {
Provider.Constants._ID, Provider.Constants.TITLE,
Provider.Constants.VALUE };
private Cursor constantsCursor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,
PROJECTION, null, null, null);
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row,
constantsCursor, new String[] { Provider.Constants.TITLE,
Provider.Constants.VALUE }, new int[] { R.id.title,
R.id.value });
setListAdapter(adapter);
registerForContextMenu(getListView());
}
@Override
public void onDestroy() {
super.onDestroy();
constantsCursor.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, ADD_ID, Menu.NONE, "Add").setIcon(R.drawable.icon)
.setAlphabeticShortcut('a');
menu.add(Menu.NONE, CLOSE_ID, Menu.NONE, "Close")
.setIcon(R.drawable.icon).setAlphabeticShortcut('c');
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ADD_ID:
add();
return (true);
case CLOSE_ID:
finish();
return (true);
}
return (super.onOptionsItemSelected(item));
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
.setIcon(R.drawable.icon).setAlphabeticShortcut('d');
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
delete(info.id);
return (true);
}
return (super.onOptionsItemSelected(item));
}
private void add() {
LayoutInflater inflater = LayoutInflater.from(this);
View addView = inflater.inflate(R.layout.add_edit, null);
final DialogWrapper wrapper = new DialogWrapper(addView);
new AlertDialog.Builder(this)
.setTitle(R.string.add_title)
.setView(addView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
processAdd(wrapper);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ignore, just dismiss
}
}).show();
}
private void delete(final long rowId) {
if (rowId > 0) {
new AlertDialog.Builder(this)
.setTitle(R.string.delete_title)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
processDelete(rowId);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ignore, just dismiss
}
}).show();
}
}
private void processAdd(DialogWrapper wrapper) {
ContentValues values = new ContentValues(2);
values.put(Provider.Constants.TITLE, wrapper.getTitle());
values.put(Provider.Constants.VALUE, wrapper.getValue());
getContentResolver().insert(Provider.Constants.CONTENT_URI, values);
constantsCursor.requery();
}
private void processDelete(long rowId) {
Uri uri = ContentUris.withAppendedId(Provider.Constants.CONTENT_URI,
rowId);
getContentResolver().delete(uri, null, null);
constantsCursor.requery();
}
class DialogWrapper {
EditText titleField = null;
EditText valueField = null;
View base = null;
DialogWrapper(View base) {
this.base = base;
valueField = (EditText) base.findViewById(R.id.value);
}
String getTitle() {
return (getTitleField().getText().toString());
}
float getValue() {
return (new Float(getValueField().getText().toString())
.floatValue());
}
private EditText getTitleField() {
if (titleField == null) {
titleField = (EditText) base.findViewById(R.id.title);
}
return (titleField);
}
private EditText getValueField() {
if (valueField == null) {
valueField = (EditText) base.findViewById(R.id.value);
}
return (valueField);
}
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, ConstantsBrowser"
/>
</LinearLayout>
//add_edit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:text="Display Name:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<EditText
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:text="Value:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<EditText
android:id="@+id/value"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
</LinearLayout>
</LinearLayout>
//row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="@+id/value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
//strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ConstantsBrowser</string>
<string name="ok">OK</string>
<string name="cancel">Cancel</string>
<string name="add_title">Add Constant</string>
<string name="delete_title">Delete Constant: Are You Sure?</string>
</resources>
Related examples in the same category