SlideShare une entreprise Scribd logo
1  sur  16
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. }

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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 )
 

Similaire à 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
 

Similaire à 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 (1).pptx
Unit - IV (1).pptxUnit - IV (1).pptx
Unit - IV (1).pptx
 
Unit - IV.pptx
Unit - IV.pptxUnit - IV.pptx
Unit - IV.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
 

Dernier

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Dernier (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

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. }