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 sqlite
Deepa Rani
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
Krazy Koder
 
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
 

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

project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
briancrawford30935
 
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
 

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.pptx
Unit - IV.pptxUnit - IV.pptx
Unit - IV.pptx
 
Unit - IV (1).pptx
Unit - IV (1).pptxUnit - IV (1).pptx
Unit - IV (1).pptx
 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Save data in to sqlite
Save data in to sqliteSave data in to sqlite
Save data in to sqlite
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
F1
F1F1
F1
 
ACADGILD:: ANDROID LESSON
ACADGILD:: ANDROID LESSON ACADGILD:: ANDROID LESSON
ACADGILD:: ANDROID LESSON
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
 
ADO DOT NET
ADO DOT NETADO DOT NET
ADO DOT NET
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

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