SlideShare a Scribd company logo
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. }
Ad

More Related Content

What's hot (20)

Android Database
Android DatabaseAndroid Database
Android Database
Rashad Aliyev
ย 
android sqlite
android sqliteandroid sqlite
android sqlite
Deepa Rani
ย 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
ย 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
Arif 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
ย 
Database
DatabaseDatabase
Database
nationalmobileapps
ย 
Sql lite android
Sql lite androidSql lite android
Sql lite android
Dushyant Nasit
ย 
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
Vincent Clyde
ย 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
Gourav Kumar Saini
ย 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
ย 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
Krazy Koder
ย 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
Make 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 iOS
Make School
ย 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
Anuchit 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 World
jkreibich
ย 
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 Storage
Nikmesoft 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 First
James Johnson
ย 
Android Database
Android DatabaseAndroid Database
Android Database
Rashad Aliyev
ย 
android sqlite
android sqliteandroid sqlite
android sqlite
Deepa Rani
ย 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
ย 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
Arif 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
ย 
Sql lite android
Sql lite androidSql lite android
Sql lite android
Dushyant Nasit
ย 
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
Vincent Clyde
ย 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
Gourav Kumar Saini
ย 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
Krazy Koder
ย 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
Make 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 iOS
Make School
ย 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
Anuchit 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 World
jkreibich
ย 
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 Storage
Nikmesoft 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 First
James Johnson
ย 

Viewers also liked (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)
Nehemiah Tan
ย 
Getting Started With ANDROID
Getting Started With ANDROIDGetting Started With ANDROID
Getting Started With ANDROID
Amit Yadav
ย 
android app development training report
android app development training reportandroid app development training report
android app development training report
Rishita Jaggi
ย 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in Android
Perfect APK
ย 
(็ถš) Effective SQLite for Android
(็ถš) Effective SQLite for Android(็ถš) Effective SQLite for Android
(็ถš) Effective SQLite for Android
Shinobu Okano
ย 
Sqlite Multiple Table
Sqlite Multiple TableSqlite Multiple Table
Sqlite Multiple Table
Danang Kukuh Pribadi
ย 
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
ย 
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 ANDROID
Amit Yadav
ย 
android app development training report
android app development training reportandroid app development training report
android app development training report
Rishita Jaggi
ย 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in Android
Perfect APK
ย 
(็ถš) Effective SQLite for Android
(็ถš) Effective SQLite for Android(็ถš) Effective SQLite for Android
(็ถš) Effective SQLite for Android
Shinobu 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
ย 
Ad

Similar to Android Database Tutorial (20)

Android sq lite database tutorial
Android sq lite database tutorialAndroid sq lite database tutorial
Android sq lite database tutorial
maamir farooq
ย 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
briancrawford30935
ย 
Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
Aravindharamanan S
ย 
Lecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptxLecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptx
Yousef Alamir
ย 
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
vishal 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 ListViews
Ahsanul Karim
ย 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
Dr. Ramkumar Lakshminarayanan
ย 
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
Conint29
ย 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
alifha12
ย 
Unit - IV (1).pptx
Unit - IV (1).pptxUnit - IV (1).pptx
Unit - IV (1).pptx
VaishnaviGaikwad67
ย 
Unit - IV.pptx
Unit - IV.pptxUnit - IV.pptx
Unit - IV.pptx
VaishnaviGaikwad67
ย 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
KV(AFS) Utarlai, Barmer (Rajasthan)
ย 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
Matteo Bonifazi
ย 
Save data in to sqlite
Save data in to sqliteSave data in to sqlite
Save data in to sqlite
Junifar hidayat
ย 
Mobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptxMobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptx
JayasimhaThummala1
ย 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
Vivek Bhusal
ย 
F1
F1F1
F1
Saber LAJILI
ย 
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.JS
Min 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 Retrieval
Dr. Ranbijay Kumar
ย 
Android sq lite database tutorial
Android sq lite database tutorialAndroid sq lite database tutorial
Android sq lite database tutorial
maamir farooq
ย 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
briancrawford30935
ย 
Lecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptxLecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptx
Yousef Alamir
ย 
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
vishal 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 ListViews
Ahsanul 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.pdf
Conint29
ย 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
alifha12
ย 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
Matteo Bonifazi
ย 
Save data in to sqlite
Save data in to sqliteSave data in to sqlite
Save data in to sqlite
Junifar hidayat
ย 
Mobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptxMobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptx
JayasimhaThummala1
ย 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
Vivek Bhusal
ย 
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.JS
Min 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 Retrieval
Dr. Ranbijay Kumar
ย 
Ad

Recently uploaded (20)

AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
ย 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
ย 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
ย 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
ย 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
ย 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
ย 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
ย 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
ย 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
ย 
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything โ€“ Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
ย 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
ย 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
ย 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
ย 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
ย 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
ย 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
ย 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
ย 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
ย 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
ย 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
ย 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
ย 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
ย 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
ย 

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