Sunteți pe pagina 1din 10

Projeto TechBox | Database

Database
Projeto TechBox | Database

http://www.ibm.com/developerworks/xml/library/x-
androidstorage/index.html

Iniciando o DBHelper
private SQLiteDatabase db;
private static final int DATABASE_VERSION = 1;
private static final String DB_NAME = "sample.db";
private static final String TABLE_NAME = "friends";

public DBHelper(Context context) {


super(context, DB_NAME, null, DATABASE_VERSION);
db = getWritableDatabase();
}

Criando uma Tabela


@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "
(_id integer primary key autoincrement,
" + " fid text not null, name text not null) ");
}

Adicionando uma Linha


public void insert(String id, String name) {
db.execSQL("INSERT INTO friends('fid',
'name') values ('" + id + "', '" + name + "')");
}

Apagando uma Tabela


public void clearAll() {
db.delete(TABLE_NAME, null, null);
}
Projeto TechBox | Database

Select All retorna um ArrayList


public Cursor cursorSelectAll() {
Cursor cursor = this.db.query(
TABLE_NAME, // Table Name
new String[] { "fid", "name" }, //
Columns to return
null, // SQL WHERE
null, // Selection Args
null, // SQL GROUP BY
null, // SQL HAVING
"name"); // SQL ORDER BY
return cursor;
}

Select All retorna um cursor


public ArrayList<Friend> listSelectAll() {
ArrayList<Friend> list = new
ArrayList<Friend>();
Cursor cursor = this.db.query(TABLE_NAME,
new String[] { "fid", "name" }, null, null, null,
null, "name");
if (cursor.moveToFirst()) {
do {
Friend f = new Friend();
f.id = cursor.getString(0);
f.name = cursor.getString(1);
list.add(f);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Projeto TechBox | Database

Usando o SQLite
http://android10.org/index.php/articlesdatastorage/231-using-the-sqlite-
database-with-listview
1 public class DatabaseHelper extends SQLiteOpenHelper {
2
3 public DatabaseHelper(Context context) {
4 super(context, "CursorDemo", null, 1);
5 }
6
7 @Override
8 public void onCreate(SQLiteDatabase db) {
9 db.execSQL("CREATE TABLE IF NOT EXISTS names ("
10 + BaseColumns._ID
11 + " INTEGER PRIMARY KEY AUTOINCREMENT, first VARCHAR, last
12 db.execSQL("INSERT INTO names (first, last) VALUES ('John', 'Doe')");
13 db.execSQL("INSERT INTO names (first, last) VALUES ('James', 'Kirk')");
14 }
15
16 @Override
17 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
18 // Steps to upgrade the database for the new version ...
19 }
20 }

1. Criar uma instncia de SQLiteOpenHelper e abrir o banco


com getReadableDatabase ou getWritableDatabase
2. getReadableDatabase e getWritableDatabase oferecem
um SQLiteDatabase
3. SQLiteDatabase possui vrios mtodos para se obter um Cursor
4. Utilizar um CursorAdapter baseado em um Cursor.
1 public class SQLiteDemo extends ListActivity {
2 private static final int DIALOG_ID = 100;
3 private SQLiteDatabase database;
4 private CursorAdapter dataSource;
5 private View entryView;
6 private EditText firstNameEditor;
7 private EditText lastNameEditor;
8
9 private static final String fields[] = { "first", "last", BaseColumns._ID };
10
11 @Override
12 public void onCreate(Bundle savedInstanceState) {
13 super.onCreate(savedInstanceState);
14 DatabaseHelper helper = new DatabaseHelper(this);
15 database = helper.getWritableDatabase();
16 Cursor data = database.query("names", fields, null, null, null, null, null);
17
18 dataSource = new SimpleCursorAdapter(this,
19 R.layout.row, data, fields, new int[] { R.id.first, R.id.last });
20
21 setListAdapter(dataSource);
22 }
Projeto TechBox | Database

23 }

Para atualizar a interface quando a base for alterada, utilizar o


mtodo requery
1 ContentValues values = new ContentValues();
2 values.put("first", firstNameEditor.getText().toString());
3 values.put("last", lastNameEditor.getText().toString());
4 database.insert("names", null, values);
5 dataSource.getCursor().requery();

http://android10.org/index.php/articlesdatastorage/235-creating-and-
using-databases-in-android-one

O banco de dados criado em /data/data/<package_name>/databases

O mtodo onCreate() executa o comando de criao do banco, caso ele


no exista

O mtodo onUpgrade() invocado quando uma nova verso for instalada


Verifica-se o DATABASE_VERSION
1 public class DBAdapter
2 {
3 public static final String KEY_ROWID = "_id";
4 public static final String KEY_ISBN = "isbn";
5 public static final String KEY_TITLE = "title";
6 public static final String KEY_PUBLISHER = "publisher";
7 private static final String TAG = "DBAdapter";
8 private static final String DATABASE_NAME = "books";
9 private static final String DATABASE_TABLE = "titles";
10 private static final int DATABASE_VERSION = 1;
11 private static final String DATABASE_CREATE =
12 "create table titles (_id integer primary key autoincrement, "
13 + "isbn text not null, title text not null, "
14 + "publisher text not null);";
15
16 private final Context context;
17 private DatabaseHelper DBHelper;
18 private SQLiteDatabase db;
19
20 public DBAdapter(Context ctx)
21 {
22 this.context = ctx;
23 DBHelper = new DatabaseHelper(context);
24 }
25
26 private static class DatabaseHelper extends SQLiteOpenHelper
27 {
28 DatabaseHelper(Context context)
29 {
30 super(context, DATABASE_NAME, null, DATABASE_VERSION);
31 }
32
Projeto TechBox | Database

33 @Override
34 public void onCreate(SQLiteDatabase db)
35 {
36 db.execSQL(DATABASE_CREATE);
37 }
38
39 @Override
40 public void onUpgrade(SQLiteDatabase db, int oldVersion,
41 int newVersion)
42 {
43 Log.w(TAG, "Upgrading database from version " + oldVersion
44 + " to "
45 + newVersion + ", which will destroy all old data");
46 db.execSQL("DROP TABLE IF EXISTS titles");
47 onCreate(db);
48 }
49 }
50
51 public DBAdapter open() throws SQLException
52 {
53 db = DBHelper.getWritableDatabase();
54 return this;
55 }
56
57 public void close()
58 {
59 DBHelper.close();
60 }
61
62 public long insertTitle(String isbn, String title, String publisher)
63 {
64 ContentValues initialValues = new ContentValues();
65 initialValues.put(KEY_ISBN, isbn);
66 initialValues.put(KEY_TITLE, title);
67 initialValues.put(KEY_PUBLISHER, publisher);
68 return db.insert(DATABASE_TABLE, null, initialValues);
69 }
70
71 public boolean deleteTitle(long rowId)
72 {
73 return db.delete(DATABASE_TABLE, KEY_ROWID +
74 "=" + rowId, null) > 0;
75 }
76
77 public Cursor getAllTitles()
78 {
79 return db.query(DATABASE_TABLE, new String[] {
80 KEY_ROWID,
81 KEY_ISBN,
82 KEY_TITLE,
83 KEY_PUBLISHER},
84 null, null, null, null, null);
85 }
86
87 public Cursor getTitle(long rowId) throws SQLException
88 {
89 Cursor mCursor =
90 db.query(true, DATABASE_TABLE, new String[] {
91 KEY_ROWID,
92 KEY_ISBN,
93 KEY_TITLE,
94 KEY_PUBLISHER },
95 KEY_ROWID + "=" + rowId,
Projeto TechBox | Database

96 null, null, null, null, null);


97 if (mCursor != null) {
98 mCursor.moveToFirst();
99 }
100 return mCursor;
101 }
102
103 public boolean updateTitle(long rowId, String isbn,
104 String title, String publisher)
105 {
106 ContentValues args = new ContentValues();
107 args.put(KEY_ISBN, isbn);
108 args.put(KEY_TITLE, title);
109 args.put(KEY_PUBLISHER, publisher);
110 return db.update(DATABASE_TABLE, args,
111 KEY_ROWID + "=" + rowId, null) > 0;
112 }
113 }

Usando o Database
1 public class DatabaseActivity extends Activity {
2 @Override
3 public void onCreate(Bundle savedInstanceState) {
4 super.onCreate(savedInstanceState);
5 setContentView(R.layout.main);
6 DBAdapter db = new DBAdapter(this);
7 }
8 }

Adicionando um Ttulo
1 @Override
2 public void onCreate(Bundle savedInstanceState) {
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.main);
5
6 DBAdapter db = new DBAdapter(this);
7
8 db.open();
9 long id;
10 id = db.insertTitle(
11 "0470285818",
12 "C# 2008 Programmer's Reference",
13 "Wrox");
14 id = db.insertTitle(
15 "047017661X",
16 "Professional Windows Vista Gadgets Programming",
17 "Wrox");
18 db.close();
19 }
Projeto TechBox | Database

Buscando todos os Ttulos


1 public class DatabaseActivity extends Activity {
2 @Override
3 public void onCreate(Bundle savedInstanceState)
4 {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.main);
7 DBAdapter db = new DBAdapter(this);
8
9 db.open();
10 Cursor c = db.getAllTitles();
11 if (c.moveToFirst())
12 {
13 do {
14 DisplayTitle(c);
15 } while (c.moveToNext());
16 }
17 db.close();
18 }
19 }

Implementao do mtodo DisplayTitle


1 public void DisplayTitle(Cursor c)
2 {
3 Toast.makeText(this,
4 "id: " + c.getString(0) + "\n" +
5 "ISBN: " + c.getString(1) + "\n" +
6 "TITLE: " + c.getString(2) + "\n" +
7 "PUBLISHER: " + c.getString(3),
8 Toast.LENGTH_LONG).show();
9 }

Consultando um nico Ttulo


1 @Override
2 public void onCreate(Bundle savedInstanceState) {
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.main);
5 DBAdapter db = new DBAdapter(this);
6
7 db.open();
8 Cursor c = db.getTitle(2);
9 if (c.moveToFirst())
10 DisplayTitle(c);
11 else
12 Toast.makeText(this, "No title found",
13 Toast.LENGTH_LONG).show();
14 db.close();
15 }
Projeto TechBox | Database

Atualizando um Ttulo
1 @Override
2 public void onCreate(Bundle savedInstanceState) {
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.main);
5 DBAdapter db = new DBAdapter(this);
6
7 db.open();
8 if (db.updateTitle(1,
9 "0470285818",
10 "C# 2008 Programmer's Reference",
11 "Wrox Press"))
12 Toast.makeText(this, "Update successful.",
13 Toast.LENGTH_LONG).show();
14 else
15 Toast.makeText(this, "Update failed.",
16 Toast.LENGTH_LONG).show();
17
18 Cursor c = db.getTitle(1);
19 if (c.moveToFirst())
20 DisplayTitle(c);
21 else
22 Toast.makeText(this, "No title found",
23 Toast.LENGTH_LONG).show();
24 db.close();
25 }

Apagando um Ttulo
1 @Override
2 public void onCreate(Bundle savedInstanceState) {
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.main);
5 DBAdapter db = new DBAdapter(this);
6
7 db.open();
8 if (db.deleteTitle(1))
9 Toast.makeText(this, "Delete successful.",
10 Toast.LENGTH_LONG).show();
11 else
12 Toast.makeText(this, "Delete failed.",
13 Toast.LENGTH_LONG).show();
14 db.close();
15 }

Atualizando o Banco
1 public class DBAdapter
2 {
3 public static final String KEY_ROWID = "_id";
4 public static final String KEY_ISBN = "isbn";
5 public static final String KEY_TITLE = "title";
Projeto TechBox | Database

6 public static final String KEY_PUBLISHER = "publisher";


7 private static final String TAG = "DBAdapter";
8
9 private static final String DATABASE_NAME = "books";
10 private static final String DATABASE_TABLE = "titles";
11
12 private static final int DATABASE_VERSION = 2;
13
14 private static final String DATABASE_CREATE =
15 "create table titles (_id integer primary key autoincrement, "
16 + "isbn text not null, title text not null, "
17 + "publisher text not null);";
18 }

S-ar putea să vă placă și