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

More Related Content

What's hot (20)

PPTX
Android Database
Rashad Aliyev
 
PPTX
android sqlite
Deepa Rani
 
PPT
SQLITE Android
Sourabh Sahu
 
PDF
Persitance Data with sqlite
Arif Huda
 
PPTX
Android Training (Storing data using SQLite)
Khaled Anaqwa
 
PPTX
Database
nationalmobileapps
 
ODP
Sql lite android
Dushyant Nasit
 
PPTX
Using sqlite database in android with sqlite manager browser add ons
Vincent Clyde
 
PPTX
SQLite database in android
Gourav Kumar Saini
 
DOCX
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
 
PDF
Android datastorage
Krazy Koder
 
PDF
Advanced Core Data
Make School
 
PDF
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
DicodingEvent
 
PDF
Persistence on iOS
Make School
 
PDF
Android App Development 05 : Saving Data
Anuchit Chalothorn
 
PDF
Introduction to SQLite: The Most Popular Database in the World
jkreibich
 
PDF
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
DicodingEvent
 
PDF
[Android] Data Storage
Nikmesoft Ltd
 
PPT
Data Storage In Android
Aakash Ugale
 
PPTX
Entity Framework Database and Code First
James Johnson
 
Android Database
Rashad Aliyev
 
android sqlite
Deepa Rani
 
SQLITE Android
Sourabh Sahu
 
Persitance Data with sqlite
Arif Huda
 
Android Training (Storing data using SQLite)
Khaled Anaqwa
 
Sql lite android
Dushyant Nasit
 
Using sqlite database in android with sqlite manager browser add ons
Vincent Clyde
 
SQLite database in android
Gourav Kumar Saini
 
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
 
Android datastorage
Krazy Koder
 
Advanced Core Data
Make School
 
Dicoding Developer Coaching #20: Android | Apa itu Content Provider?
DicodingEvent
 
Persistence on iOS
Make School
 
Android App Development 05 : Saving Data
Anuchit Chalothorn
 
Introduction to SQLite: The Most Popular Database in the World
jkreibich
 
Dicoding Developer Coaching #19: Android | Menyimpan Database Secara Local di...
DicodingEvent
 
[Android] Data Storage
Nikmesoft Ltd
 
Data Storage In Android
Aakash Ugale
 
Entity Framework Database and Code First
James Johnson
 

Viewers also liked (7)

PDF
FYPJ - Cerebral Android App Development (Report)
Nehemiah Tan
 
PPT
Getting Started With ANDROID
Amit Yadav
 
PDF
android app development training report
Rishita Jaggi
 
PPTX
BroadcastReceivers in Android
Perfect APK
 
PDF
(続) Effective SQLite for Android
Shinobu Okano
 
PPTX
Sqlite Multiple Table
Danang Kukuh Pribadi
 
PDF
Evrdi : Social Diary ( iOS and Android )
Eakapong Kattiya
 
FYPJ - Cerebral Android App Development (Report)
Nehemiah Tan
 
Getting Started With ANDROID
Amit Yadav
 
android app development training report
Rishita Jaggi
 
BroadcastReceivers in Android
Perfect APK
 
(続) Effective SQLite for Android
Shinobu Okano
 
Sqlite Multiple Table
Danang Kukuh Pribadi
 
Evrdi : Social Diary ( iOS and Android )
Eakapong Kattiya
 
Ad

Similar to Android Database Tutorial (20)

PDF
Android sq lite database tutorial
maamir farooq
 
DOCX
project2.classpathproject2.project project2 .docx
briancrawford30935
 
DOCX
Android sql examples
Aravindharamanan S
 
PPTX
Lecture 10: Android SQLite database.pptx
Yousef Alamir
 
PPTX
Create an android app for database creation using.pptx
vishal choudhary
 
PDF
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
DOCX
Android-data storage in android-chapter21
Dr. Ramkumar Lakshminarayanan
 
PDF
I am looking for some assistance with SQLite database. I have tried se.pdf
Conint29
 
PDF
Mvc4 crud operations.-kemuning senja
alifha12
 
PPTX
Unit - IV.pptx
VaishnaviGaikwad67
 
PPTX
Unit - IV (1).pptx
VaishnaviGaikwad67
 
PDF
Chapter6 database connectivity
KV(AFS) Utarlai, Barmer (Rajasthan)
 
PDF
Android - Saving data
Matteo Bonifazi
 
PPTX
Save data in to sqlite
Junifar hidayat
 
PPTX
Mobile application Development-UNIT-V (1).pptx
JayasimhaThummala1
 
ODP
Session 2- day 3
Vivek Bhusal
 
ODT
ACADGILD:: ANDROID LESSON
Padma shree. T
 
PDF
Javascript Application Architecture with Backbone.JS
Min Ming Lo
 
PDF
JAM819 - Native API Deep Dive: Data Storage and Retrieval
Dr. Ranbijay Kumar
 
Android sq lite database tutorial
maamir farooq
 
project2.classpathproject2.project project2 .docx
briancrawford30935
 
Android sql examples
Aravindharamanan S
 
Lecture 10: Android SQLite database.pptx
Yousef Alamir
 
Create an android app for database creation using.pptx
vishal choudhary
 
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
Android-data storage in android-chapter21
Dr. Ramkumar Lakshminarayanan
 
I am looking for some assistance with SQLite database. I have tried se.pdf
Conint29
 
Mvc4 crud operations.-kemuning senja
alifha12
 
Unit - IV.pptx
VaishnaviGaikwad67
 
Unit - IV (1).pptx
VaishnaviGaikwad67
 
Chapter6 database connectivity
KV(AFS) Utarlai, Barmer (Rajasthan)
 
Android - Saving data
Matteo Bonifazi
 
Save data in to sqlite
Junifar hidayat
 
Mobile application Development-UNIT-V (1).pptx
JayasimhaThummala1
 
Session 2- day 3
Vivek Bhusal
 
ACADGILD:: ANDROID LESSON
Padma shree. T
 
Javascript Application Architecture with Backbone.JS
Min Ming Lo
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
Dr. Ranbijay Kumar
 
Ad

Recently uploaded (20)

PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PDF
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
Kubernetes - Architecture & Components.pdf
geethak285
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 

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