SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
Android
Database
Perfect APK
Android Database Tutorial
Storing data is a basic and very common need in mobile apps. The Android application framework provides several storage options, one of which is SQLite
databases.
In this tutorial you will see a simple Android database example. The example is based on the Android ListView Tutorial and the Android AsyncTask Tutorial,
however these tutorials are not mandatory for the purpose of understanding the principles of proper Android database usage.
The usage of Android SQLite databases is simplified using the SQLiteOpenHelper class. In this example we will use the a SQLite database for storing the
number of user clicks on each of the ListView items from the Android ListView Tutorial, and each time the user return to the app, the list items will be
ordered according to his preferences.
Because loading data from the database and sorting it takes time, we will use an AsyncTask for loading and sorting in a background thread, as shown in
the Android AsyncTask Tutorial.
Please note that the icon set for this example was created by Design Deck.
The example for this tutorial is contains the following components:
● Entity Class - the class used for describing objects that are stored in the database.
● Database Helper - the SocialItemsDatabaseHelper that extends the SQLiteOpenHelper class.
● ListView Item - the class used for ListView items. This is the same class used in the Android ListView Tutorial.
● List Adapter - This class is based on the list adapter from the Android ListView Tutorial.
Entity Class
The SocialItem class below contains a String for the title and a long for the number of user clicks in the list item. It also implements the Comparable interface for sorting the
items:
1. public class SocialItem implements Comparable<SocialItem> {
2. public final String title; // the text for the ListView item title
3. private long numClicks; // the number of user clicks on this item
4.
5. public SocialItem(String title) {
6. this.title = title;
7. numClicks = 0;
8. }
9. public SocialItem(String title, long numClicks) {
10. this.title = title;
11. this.numClicks = numClicks;
12. }
Database Helper
the SocialItemsDatabaseHelper below extends the SQLiteOpenHelper and is used for send SQLite queries to the database for loading,
storing and updating data:
1. public class SocialItemsDatabaseHelper extends SQLiteOpenHelper {
2. // Database Version
3. private static final int DATABASE_VERSION = 1;
4. // Database Name
5. private static final String DATABASE_NAME = "database_tutorial";
6. // Table name
7. private static final String SOCIAL_ITEMS = "social_items";
8.
Database Helper
1. @Override
2. public void onCreate(SQLiteDatabase db) {
3. db.execSQL("CREATE TABLE " + SOCIAL_ITEMS + "("
4. + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
5. + COLUMN_TITLE + " TEXT UNIQUE NOT NULL,"
6. + COLUMN_NUM_CLICKS + " LONG NOT NULL" + ")");
7. }
8.
9. @Override
10. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
11. // simple database upgrade operation:
12. // 1) drop the old table
13. db.execSQL("DROP TABLE IF EXISTS " + SOCIAL_ITEMS);
14. // 2) create a new database
15. onCreate(db);
16. }
Database Helper
1. // retrieve all items from the database
2. public List<SocialItem> getAllItems() {
3. // initialize the list
4. List<SocialItem> items = new ArrayList<SocialItem>();
5. // obtain a readable database
6. SQLiteDatabase db = getReadableDatabase();
7. // send query
8. Cursor cursor = db.query(SOCIAL_ITEMS, new String[] {
9. COLUMN_TITLE,
10. COLUMN_NUM_CLICKS },
11. null, null, null, null, null, null); // get all rows
12.
13. if (cursor != null) {
14. // add items to the list
15. for(cursor.moveToFirst(); cursor.isAfterLast() == false; cursor.moveToNext()) {
16. items.add(new SocialItem(cursor.getString(0), Long.parseLong(cursor.getString(1))));
17. }
18.
19. // close the cursor
20. cursor.close();
21. }
22.
23. // close the database connection
24. db.close();
25. // return the list
26. return items;
Database Helper
1. /**
2. * Add items to the list
3. */
4. public void addItems(List<SocialItem> items) {
5. if(items != null && items.size() > 0) {
6. // obtain a readable database
7. SQLiteDatabase db = getWritableDatabase();
8.
9. for(SocialItem item : items) {
10. addItem(db, item);
11. }
12.
13. // close the database connection
14. db.close();
15. }
16. }
Database Helper
1. // update an existing item
2. public void updateItem(SocialItem item) {
3. if(item != null) {
4. // obtain a readable database
5. SQLiteDatabase db = getWritableDatabase();
6. // prepare values
7. ContentValues values = new ContentValues();
8. values.put(COLUMN_NUM_CLICKS, item.getNumClicks());
9. // send query for the row id
10. Cursor cursor = db.query(SOCIAL_ITEMS, new String[] {COLUMN_ID},
11. COLUMN_TITLE + "=?", new String[] {item.title},
12. null, null, null, null);
13.
14. if(cursor != null) {
15. if(cursor.moveToFirst()) {
16. // update the row
17. db.update(SOCIAL_ITEMS, values, COLUMN_ID + "=?",
18. new String[] {cursor.getString(0)});
19. }
20.
21. cursor.close();
22. }
23.
24. db.close(); // close the database connection
25. }
26. }
Database Helper
1. /**
2. * Add a new item
3. */
4. private void addItem(SQLiteDatabase db, SocialItem item) {
5. // prepare values
6. ContentValues values = new ContentValues();
7. values.put(COLUMN_TITLE, item.title);
8. values.put(COLUMN_NUM_CLICKS, item.getNumClicks());
9.
10. // add the row
11. db.insert(SOCIAL_ITEMS, null, values);
12. }
13. }
List Adapter
The SocialItemsListAdapter class below contains a list List of SocialItems and a HashMap for mapping the title to the icon:
1. public class SocialItemsListAdapter extends ArrayAdapter<ListViewItem> {
2. private List<SocialItem> mSocialItems;
3. private Map<String, Drawable> mIconsMap;
4.
5. public SocialItemsListAdapter(Context context, List<SocialItem> socialItems, Map<String, Drawable> iconsMap) {
6. super(context, R.layout.listview_item);
7. mSocialItems = socialItems;
8. mIconsMap = iconsMap;
9. }
10.
11. @Override
List Adapter
1. @Override
2. public View getView(int position, View convertView, ViewGroup parent) {
3. ViewHolder viewHolder;
4.
5. if(convertView == null) {
6. // inflate the GridView item layout
7. LayoutInflater inflater = LayoutInflater.from(getContext());
8. convertView = inflater.inflate(R.layout.listview_item, parent, false);
9.
10. // initialize the view holder
11. viewHolder = new ViewHolder();
12. viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
13. viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
14. viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
15. convertView.setTag(viewHolder);
16. } else {
17. viewHolder = (ViewHolder) convertView.getTag(); // recycle the already inflated view
18. }
19.
20. // update the item view
21. ListViewItem item = getItem(position);
22. viewHolder.ivIcon.setImageDrawable(item.icon);
23. viewHolder.tvTitle.setText(item.title);
24. viewHolder.tvDescription.setText(item.description);
25.
26. return convertView;
List Adapter
1. /**
2. * The view holder design pattern prevents using findViewById()
3. * repeatedly in the getView() method of the adapter.
4. *
5. * @see http://developer.android.com/training/improving-layouts/smooth-
scrolling.html#ViewHolder
6. */
7. private static class ViewHolder {
8. ImageView ivIcon;
9. TextView tvTitle;
10. TextView tvDescription;
11. }
DatabaseDemoFragment
The fragment that contains the ListView. This class uses an AsyncTask for loading the items from the database and sorting them according
to the user’s preferences:
1. public class DatabaseDemoFragment extends ListFragment {
2. // database helper
3. private SocialItemsDatabaseHelper mDatabaseHelper;
4.
5. // database items list
6. private List<SocialItem> mSocialItems;
7.
8. // list adapter
9. private SocialItemsListAdapter mAdapter;
10.
DatabaseDemoFragment
1. @Override
2. public void onCreate(Bundle savedInstanceState) {
3. super.onCreate(savedInstanceState);
4. // initialize the database helper
5. mDatabaseHelper = new SocialItemsDatabaseHelper(getActivity());
6.
7. // initialize the icons map
8. Map<String, Drawable> iconsMap = new HashMap<String, Drawable>();
9. Resources resources = getResources();
10. iconsMap.put(getString(R.string.aim), resources.getDrawable(R.drawable.aim));
11. :
12. iconsMap.put(getString(R.string.youtube), resources.getDrawable(R.drawable.youtube));
13.
14. // initialize the items list
15. mSocialItems = mDatabaseHelper.getAllItems();
16.
17. // initialize and set the list adapter
18. mSocialItems = new ArrayList<SocialItem>();
19. mAdapter = new SocialItemsListAdapter(getActivity(), mSocialItems, iconsMap);
20. setListAdapter(mAdapter);
21.
22. // start an AsyncTask for loading the items from the database
23. AsyncTask<String, Integer, List<SocialItem>> loader = new AsyncTask<String, Integer, List<SocialItem>>() {
24.
25.
DatabaseDemoFragment
1. @Override
2. protected List<SocialItem> doInBackground(String... params) {
3. List<SocialItem> items = mDatabaseHelper.getAllItems();
4.
5. if(items.size() == 0) {
6. for(String title : params) {
7. items.add(new SocialItem(title));
8. }
9.
10. mDatabaseHelper.addItems(items); // add the items to the database
11. }
12.
13. Collections.sort(items); // sort the list
14. return items;
15. }
16.
17. @Override
18. protected void onPostExecute(List<SocialItem> items) {
19. for(SocialItem item : items) {
20. mSocialItems.add(item);
21. mAdapter.notifyDataSetChanged();
22. }
23. }
24. };
25.
26. Set<String> set = iconsMap.keySet();
27. loader.execute(set.toArray(new String[set.size()]));
28. }
DatabaseDemoFragment
1. @Override
2. public void onViewCreated(View view, Bundle savedInstanceState) {
3. super.onViewCreated(view, savedInstanceState);
4. getListView().setDivider(null);
5. }
6.
7. @Override
8. public void onListItemClick(ListView l, View v, int position, long id) {
9. // retrieve the item
10. SocialItem item = mSocialItems.get(position);
11.
12. // update the clicks counter
13. item.increaseNumClicks();
14.
15. // notify the adapter
16. mAdapter.notifyDataSetChanged();
17.
18. // update the database
19. mDatabaseHelper.updateItem(item);
20. }
21. }

Más contenido relacionado

La actualidad más candente

android sqlite
android sqliteandroid sqlite
android sqliteDeepa Rani
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqliteArif Huda
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Khaled Anaqwa
 
Using sqlite database in android with sqlite manager browser add ons
Using sqlite database in android with sqlite manager browser add onsUsing sqlite database in android with sqlite manager browser add ons
Using sqlite database in android with sqlite manager browser add onsVincent Clyde
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core DataMake School
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?DicodingEvent
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOSMake School
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving DataAnuchit Chalothorn
 
Introduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the WorldIntroduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the Worldjkreibich
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...DicodingEvent
 
[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data StorageNikmesoft Ltd
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 

La actualidad más candente (20)

Android Database
Android DatabaseAndroid Database
Android Database
 
android sqlite
android sqliteandroid sqlite
android sqlite
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 
Database
DatabaseDatabase
Database
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Using sqlite database in android with sqlite manager browser add ons
Using sqlite database in android with sqlite manager browser add onsUsing sqlite database in android with sqlite manager browser add ons
Using sqlite database in android with sqlite manager browser add ons
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOS
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
Introduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the WorldIntroduction to SQLite: The Most Popular Database in the World
Introduction to SQLite: The Most Popular Database in the World
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
 
[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data Storage
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 

Destacado

FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)Nehemiah Tan
 
Getting Started With ANDROID
Getting Started With ANDROIDGetting Started With ANDROID
Getting Started With ANDROIDAmit Yadav
 
android app development training report
android app development training reportandroid app development training report
android app development training reportRishita Jaggi
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in AndroidPerfect APK
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for AndroidShinobu Okano
 
Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Eakapong Kattiya
 

Destacado (7)

FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)FYPJ - Cerebral Android App Development (Report)
FYPJ - Cerebral Android App Development (Report)
 
Getting Started With ANDROID
Getting Started With ANDROIDGetting Started With ANDROID
Getting Started With ANDROID
 
android app development training report
android app development training reportandroid app development training report
android app development training report
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in Android
 
(続) Effective SQLite for Android
(続) Effective SQLite for Android(続) Effective SQLite for Android
(続) Effective SQLite for Android
 
Sqlite Multiple Table
Sqlite Multiple TableSqlite Multiple Table
Sqlite Multiple Table
 
Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )
 

Similar a Android Database Tutorial

Android sq lite database tutorial
Android sq lite database tutorialAndroid sq lite database tutorial
Android sq lite database tutorialmaamir farooq
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docxbriancrawford30935
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsAhsanul Karim
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfConint29
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaalifha12
 
ACADGILD:: ANDROID LESSON
ACADGILD:: ANDROID LESSON ACADGILD:: ANDROID LESSON
ACADGILD:: ANDROID LESSON Padma shree. T
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSMin Ming Lo
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalDr. Ranbijay Kumar
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenSony Suci
 

Similar a Android Database Tutorial (20)

Android sq lite database tutorial
Android sq lite database tutorialAndroid sq lite database tutorial
Android sq lite database tutorial
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
 
Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
 
Unit - IV.pptx
Unit - IV.pptxUnit - IV.pptx
Unit - IV.pptx
 
Unit - IV (1).pptx
Unit - IV (1).pptxUnit - IV (1).pptx
Unit - IV (1).pptx
 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Save data in to sqlite
Save data in to sqliteSave data in to sqlite
Save data in to sqlite
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
F1
F1F1
F1
 
ACADGILD:: ANDROID LESSON
ACADGILD:: ANDROID LESSON ACADGILD:: ANDROID LESSON
ACADGILD:: ANDROID LESSON
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
 
ADO DOT NET
ADO DOT NETADO DOT NET
ADO DOT NET
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 

Último

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 

Último (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 

Android Database Tutorial

  • 2. Android Database Tutorial Storing data is a basic and very common need in mobile apps. The Android application framework provides several storage options, one of which is SQLite databases. In this tutorial you will see a simple Android database example. The example is based on the Android ListView Tutorial and the Android AsyncTask Tutorial, however these tutorials are not mandatory for the purpose of understanding the principles of proper Android database usage. The usage of Android SQLite databases is simplified using the SQLiteOpenHelper class. In this example we will use the a SQLite database for storing the number of user clicks on each of the ListView items from the Android ListView Tutorial, and each time the user return to the app, the list items will be ordered according to his preferences. Because loading data from the database and sorting it takes time, we will use an AsyncTask for loading and sorting in a background thread, as shown in the Android AsyncTask Tutorial. Please note that the icon set for this example was created by Design Deck. The example for this tutorial is contains the following components: ● Entity Class - the class used for describing objects that are stored in the database. ● Database Helper - the SocialItemsDatabaseHelper that extends the SQLiteOpenHelper class. ● ListView Item - the class used for ListView items. This is the same class used in the Android ListView Tutorial. ● List Adapter - This class is based on the list adapter from the Android ListView Tutorial.
  • 3. Entity Class The SocialItem class below contains a String for the title and a long for the number of user clicks in the list item. It also implements the Comparable interface for sorting the items: 1. public class SocialItem implements Comparable<SocialItem> { 2. public final String title; // the text for the ListView item title 3. private long numClicks; // the number of user clicks on this item 4. 5. public SocialItem(String title) { 6. this.title = title; 7. numClicks = 0; 8. } 9. public SocialItem(String title, long numClicks) { 10. this.title = title; 11. this.numClicks = numClicks; 12. }
  • 4. Database Helper the SocialItemsDatabaseHelper below extends the SQLiteOpenHelper and is used for send SQLite queries to the database for loading, storing and updating data: 1. public class SocialItemsDatabaseHelper extends SQLiteOpenHelper { 2. // Database Version 3. private static final int DATABASE_VERSION = 1; 4. // Database Name 5. private static final String DATABASE_NAME = "database_tutorial"; 6. // Table name 7. private static final String SOCIAL_ITEMS = "social_items"; 8.
  • 5. Database Helper 1. @Override 2. public void onCreate(SQLiteDatabase db) { 3. db.execSQL("CREATE TABLE " + SOCIAL_ITEMS + "(" 4. + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," 5. + COLUMN_TITLE + " TEXT UNIQUE NOT NULL," 6. + COLUMN_NUM_CLICKS + " LONG NOT NULL" + ")"); 7. } 8. 9. @Override 10. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 11. // simple database upgrade operation: 12. // 1) drop the old table 13. db.execSQL("DROP TABLE IF EXISTS " + SOCIAL_ITEMS); 14. // 2) create a new database 15. onCreate(db); 16. }
  • 6. Database Helper 1. // retrieve all items from the database 2. public List<SocialItem> getAllItems() { 3. // initialize the list 4. List<SocialItem> items = new ArrayList<SocialItem>(); 5. // obtain a readable database 6. SQLiteDatabase db = getReadableDatabase(); 7. // send query 8. Cursor cursor = db.query(SOCIAL_ITEMS, new String[] { 9. COLUMN_TITLE, 10. COLUMN_NUM_CLICKS }, 11. null, null, null, null, null, null); // get all rows 12. 13. if (cursor != null) { 14. // add items to the list 15. for(cursor.moveToFirst(); cursor.isAfterLast() == false; cursor.moveToNext()) { 16. items.add(new SocialItem(cursor.getString(0), Long.parseLong(cursor.getString(1)))); 17. } 18. 19. // close the cursor 20. cursor.close(); 21. } 22. 23. // close the database connection 24. db.close(); 25. // return the list 26. return items;
  • 7. Database Helper 1. /** 2. * Add items to the list 3. */ 4. public void addItems(List<SocialItem> items) { 5. if(items != null && items.size() > 0) { 6. // obtain a readable database 7. SQLiteDatabase db = getWritableDatabase(); 8. 9. for(SocialItem item : items) { 10. addItem(db, item); 11. } 12. 13. // close the database connection 14. db.close(); 15. } 16. }
  • 8. Database Helper 1. // update an existing item 2. public void updateItem(SocialItem item) { 3. if(item != null) { 4. // obtain a readable database 5. SQLiteDatabase db = getWritableDatabase(); 6. // prepare values 7. ContentValues values = new ContentValues(); 8. values.put(COLUMN_NUM_CLICKS, item.getNumClicks()); 9. // send query for the row id 10. Cursor cursor = db.query(SOCIAL_ITEMS, new String[] {COLUMN_ID}, 11. COLUMN_TITLE + "=?", new String[] {item.title}, 12. null, null, null, null); 13. 14. if(cursor != null) { 15. if(cursor.moveToFirst()) { 16. // update the row 17. db.update(SOCIAL_ITEMS, values, COLUMN_ID + "=?", 18. new String[] {cursor.getString(0)}); 19. } 20. 21. cursor.close(); 22. } 23. 24. db.close(); // close the database connection 25. } 26. }
  • 9. Database Helper 1. /** 2. * Add a new item 3. */ 4. private void addItem(SQLiteDatabase db, SocialItem item) { 5. // prepare values 6. ContentValues values = new ContentValues(); 7. values.put(COLUMN_TITLE, item.title); 8. values.put(COLUMN_NUM_CLICKS, item.getNumClicks()); 9. 10. // add the row 11. db.insert(SOCIAL_ITEMS, null, values); 12. } 13. }
  • 10. List Adapter The SocialItemsListAdapter class below contains a list List of SocialItems and a HashMap for mapping the title to the icon: 1. public class SocialItemsListAdapter extends ArrayAdapter<ListViewItem> { 2. private List<SocialItem> mSocialItems; 3. private Map<String, Drawable> mIconsMap; 4. 5. public SocialItemsListAdapter(Context context, List<SocialItem> socialItems, Map<String, Drawable> iconsMap) { 6. super(context, R.layout.listview_item); 7. mSocialItems = socialItems; 8. mIconsMap = iconsMap; 9. } 10. 11. @Override
  • 11. List Adapter 1. @Override 2. public View getView(int position, View convertView, ViewGroup parent) { 3. ViewHolder viewHolder; 4. 5. if(convertView == null) { 6. // inflate the GridView item layout 7. LayoutInflater inflater = LayoutInflater.from(getContext()); 8. convertView = inflater.inflate(R.layout.listview_item, parent, false); 9. 10. // initialize the view holder 11. viewHolder = new ViewHolder(); 12. viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon); 13. viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle); 14. viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription); 15. convertView.setTag(viewHolder); 16. } else { 17. viewHolder = (ViewHolder) convertView.getTag(); // recycle the already inflated view 18. } 19. 20. // update the item view 21. ListViewItem item = getItem(position); 22. viewHolder.ivIcon.setImageDrawable(item.icon); 23. viewHolder.tvTitle.setText(item.title); 24. viewHolder.tvDescription.setText(item.description); 25. 26. return convertView;
  • 12. List Adapter 1. /** 2. * The view holder design pattern prevents using findViewById() 3. * repeatedly in the getView() method of the adapter. 4. * 5. * @see http://developer.android.com/training/improving-layouts/smooth- scrolling.html#ViewHolder 6. */ 7. private static class ViewHolder { 8. ImageView ivIcon; 9. TextView tvTitle; 10. TextView tvDescription; 11. }
  • 13. DatabaseDemoFragment The fragment that contains the ListView. This class uses an AsyncTask for loading the items from the database and sorting them according to the user’s preferences: 1. public class DatabaseDemoFragment extends ListFragment { 2. // database helper 3. private SocialItemsDatabaseHelper mDatabaseHelper; 4. 5. // database items list 6. private List<SocialItem> mSocialItems; 7. 8. // list adapter 9. private SocialItemsListAdapter mAdapter; 10.
  • 14. DatabaseDemoFragment 1. @Override 2. public void onCreate(Bundle savedInstanceState) { 3. super.onCreate(savedInstanceState); 4. // initialize the database helper 5. mDatabaseHelper = new SocialItemsDatabaseHelper(getActivity()); 6. 7. // initialize the icons map 8. Map<String, Drawable> iconsMap = new HashMap<String, Drawable>(); 9. Resources resources = getResources(); 10. iconsMap.put(getString(R.string.aim), resources.getDrawable(R.drawable.aim)); 11. : 12. iconsMap.put(getString(R.string.youtube), resources.getDrawable(R.drawable.youtube)); 13. 14. // initialize the items list 15. mSocialItems = mDatabaseHelper.getAllItems(); 16. 17. // initialize and set the list adapter 18. mSocialItems = new ArrayList<SocialItem>(); 19. mAdapter = new SocialItemsListAdapter(getActivity(), mSocialItems, iconsMap); 20. setListAdapter(mAdapter); 21. 22. // start an AsyncTask for loading the items from the database 23. AsyncTask<String, Integer, List<SocialItem>> loader = new AsyncTask<String, Integer, List<SocialItem>>() { 24. 25.
  • 15. DatabaseDemoFragment 1. @Override 2. protected List<SocialItem> doInBackground(String... params) { 3. List<SocialItem> items = mDatabaseHelper.getAllItems(); 4. 5. if(items.size() == 0) { 6. for(String title : params) { 7. items.add(new SocialItem(title)); 8. } 9. 10. mDatabaseHelper.addItems(items); // add the items to the database 11. } 12. 13. Collections.sort(items); // sort the list 14. return items; 15. } 16. 17. @Override 18. protected void onPostExecute(List<SocialItem> items) { 19. for(SocialItem item : items) { 20. mSocialItems.add(item); 21. mAdapter.notifyDataSetChanged(); 22. } 23. } 24. }; 25. 26. Set<String> set = iconsMap.keySet(); 27. loader.execute(set.toArray(new String[set.size()])); 28. }
  • 16. DatabaseDemoFragment 1. @Override 2. public void onViewCreated(View view, Bundle savedInstanceState) { 3. super.onViewCreated(view, savedInstanceState); 4. getListView().setDivider(null); 5. } 6. 7. @Override 8. public void onListItemClick(ListView l, View v, int position, long id) { 9. // retrieve the item 10. SocialItem item = mSocialItems.get(position); 11. 12. // update the clicks counter 13. item.increaseNumClicks(); 14. 15. // notify the adapter 16. mAdapter.notifyDataSetChanged(); 17. 18. // update the database 19. mDatabaseHelper.updateItem(item); 20. } 21. }