Bine ati venit pe ItAssistant. Aceasta noua serie de tutoriale isi propune sa va familiarizeze cu Sistemul de Operare Android astfel incat sa puteti sa scrieti singuri aplicatii pentru propriul SmartPhone, si de ce nu, aplicatia sa ajunga in top pe Android Market.
Inainte de a incepe trebuie sa cunoasteti destul de bine limbajul de programare Java si conceptele Programarii Orientata Obiect; puteti sa aruncati o privire peste tutorialele noastre avansate: Invata Java
Android – Stocarea Datelor
In Android exista mai multe moduri in care puteti sa stocati datele:
- Shared Preferences – stocheaza doar date in forma key-value (datele care sunt salvate pot fi de tipul: String, boolean, float, int, long)
- Stocare interna – folosirea memorie device-ului
- Stocare externa – folosirea unui dispozitiv extern, de obicei un SD Card.
- Baza de date – folosirea unei baze de date SQLite
Puteti de asemenea sa aveti deja date predefinite, dar cand Read Only. Acestea se pot gasi in:
- directorul Assets
- directorul res/raw
Android – Baza de date – SQLite
SQLite este o baza de date open source integrata in Android. De asemenea SQLite suporta sintaxa SQL, tranzactii si ocupa foarte putina memorie (aproximativ 250 KByte).
Cateva tipuri suportate de SQLite sunt:
- TEXT – similar cu String din Java
- INTEGER – similar cu Long din Java
- REAL – similar cu Double din Java
- BLOB
- NULL
Mai multe informatii despre SQLite puteti gasi aici: http://www.sqlite.org
SQLite in Android
SQLite este integrata in fiecare dispozitiv Android si nu necesita nici o configurare speciala pentru a putea fi folosita, managementul bazei de date fiind facut de platforma Android.
Daca aplicatia voastra creaza o baza de date aceasta va fi salvata in directorul: DATA/data/APP_NAME/databases/FILENAME (unde APP_NAME este numele aplicatie voastre).
Pentru a lucra cu baza de date va trebui in majoriteatea cazurilor sa suprascrieti 2 clase:
- SQLiteOpenHelper – este responsabila cu crearea bazei de date si eventual upgradarea ei. Aveti disponibile metode ca: onCreate() sau onUpgrade()
- SQLiteDatabase – este responsabila cu manipularea datelor din baza de date. Aveti disponibile metode ca: insert(), update() sau delete()
Functia query()
Cu aceasta functie puteti sa executati anumite query-uri asupra bazei de date. Sintaxa functiei este urmatoarea:
database.query(dbName, int[] columnNames, String whereClause, String[] selectionArgs, String[] groupBy, String[] having, String[] orderBy);
Paramentrii sunt explicati in tabelul urmator (bineinteles ca anumiti parametri pot sa lipseasca fiind inlocuiti cu null).
| Parametru | Comentarii |
|---|---|
| String dbName | Numele tabelei asupra careia se va executa query-ul |
| int[] columnNames | O lista cu coloanele care vor fi intoarse de query. Daca acest parametru este null, atunci vor fi intoarse toate coloanele |
| String whereClause | Filtrare dupa clauza WHERE |
| String[] selectionArgs | Puteti pune ? in clauza WHERE, aceste placeholdere vor fi inlocuite cu valorile din array-ul selectionArgs |
| String[] groupBy | Filtru pentru gruparea valorilor intoarse |
| String[] having | Filtru pentru clauza HAVING |
| String[] orderBy | Coloanele tabelei care vor fi folosite pentru ordonarea datelor |
Dupa interogarea bazei de date veti obtine un Cursor care puncteaza catre un rand din rezultatul intors de query; Functii specifice unui Cursor sunt:
- getCount() – numarul de randuri intoarse de query
- moveToFirst() – muta cursorul pe primul rand intors
- moveToNext() – muta cursorul pe urmtatorul rand
- get*() – functii de acces a datelor din coloane
Exemplu complet de utilizare SQLite
MySQLiteHelper.java
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class MySQLiteHelper extends SQLiteOpenHelper { public static final String TABLE_COMMENTS = "comments"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_COMMENT = "comment"; private static final String DATABASE_NAME = "commments.db"; private static final int DATABASE_VERSION = 1; // Database creation sql statement private static final String DATABASE_CREATE = "create table " + TABLE_COMMENTS + "( " + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_COMMENT + " text not null);"; public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS" + TABLE_COMMENTS); onCreate(db); } }
Comment.java
public class Comment { private long id; private String comment; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } // Will be used by the ArrayAdapter in the ListView @Override public String toString() { return comment; } }
CommentsDataSource.java
import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class CommentsDataSource { // Database fields private SQLiteDatabase database; private MySQLiteHelper dbHelper; private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_COMMENT }; public CommentsDataSource(Context context) { dbHelper = new MySQLiteHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public Comment createComment(String comment) { ContentValues values = new ContentValues(); values.put(MySQLiteHelper.COLUMN_COMMENT, comment); long insertId = database.insert(MySQLiteHelper.TABLE_COMMENTS, null, values); // To show how to query Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null); cursor.moveToFirst(); return cursorToComment(cursor); } public void deleteComment(Comment comment) { long id = comment.getId(); System.out.println("Comment deleted with id: " + id); database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID + " = " + id, null); } public List<Comment> getAllComments() { List<Comment> comments = new ArrayList<Comment>(); Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Comment comment = cursorToComment(cursor); comments.add(comment); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return comments; } private Comment cursorToComment(Cursor cursor) { Comment comment = new Comment(); comment.setId(cursor.getLong(0)); comment.setComment(cursor.getString(1)); return comment; } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/group" android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add New" android:onClick="onClick"/> <Button android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete First" android:onClick="onClick"/> </LinearLayout> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
TestDatabaseActivity.java
import java.util.List; import java.util.Random; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; public class TestDatabaseActivity extends ListActivity { private CommentsDataSource datasource; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); datasource = new CommentsDataSource(this); datasource.open(); List<Comment> values = datasource.getAllComments(); // Use the SimpleCursorAdapter to show the // elements in a ListView ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values); setListAdapter(adapter); } // Will be called via the onClick attribute // of the buttons in main.xml public void onClick(View view) { @SuppressWarnings("unchecked") ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter(); Comment comment = null; switch (view.getId()) { case R.id.add: String[] comments = new String[] { "Cool", "Very nice", "Hate it" }; int nextInt = new Random().nextInt(3); // Save the new comment to the database comment = datasource.createComment(comments[nextInt]); adapter.add(comment); break; case R.id.delete: if (getListAdapter().getCount() > 0) { comment = (Comment) getListAdapter().getItem(0); datasource.deleteComment(comment); adapter.remove(comment); } break; } adapter.notifyDataSetChanged(); } @Override protected void onResume() { datasource.open(); super.onResume(); } @Override protected void onPause() { datasource.close(); super.onPause(); } }
Link-uri utile
Related posts:
- Invata Sistemul de Operare Android – Partea 12
- Invata Sistemul de Operare Android – Partea 2
- Invata Sistemul de Operare Android – Partea 7
- Invata Sistemul de Operare Android – Partea 9
- Invata Sistemul de Operare Android – Partea 6




