Mobile Computing With Android ACST 4550 Android Database Storage

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
SQLite is a software library. It is: self-contained + Serverless + zero-configuration transactional = SQL database engine. Most widely deployed. The source.
Cosc 5/4730 Android and Blackberry SQLite. For the sql language syntax, please see SQlite documentation –
SQLLite and Java CS-328 Dick Steflik. SQLLite Embedded RDBMS ACID Compliant Size – about 257 Kbytes Not a client/server architecture –Accessed via function.
CS378 - Mobile Computing Persistence - SQLite. Databases RDBMS – relational data base management system Relational databases introduced by E. F. Codd.
Data Persistence in Android
Data Storage: Part 1 (Preferences)
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
Data Storage: Part 3 (SQLite)
CSE 486/586, Spring 2013 CSE 486/586 Distributed Systems Content Providers & Services.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Cosc 5/4730 Android Content Providers and Intents.
Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.
COMP 365 Android Development.  Manages access from a central database  Allows multiple applications to access the same data.
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
SQLite Supported by BlackBerry OS 5.0 Using SQLite.
Android Storage. There are several options for storage of data with Android We can put data into a preferences file. We can put data into a ‘normal’ file.
Address Book App 1. Define styles   Specify a background for a TextView – res/drawable/textview_border.xml.
9 Persistence - SQLite CSNB544 Mobile Application Development Thanks to Utexas Austin.
Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
SQLite (part deux) 1 CS440. Traditional Model View Controller (MVC) CS440 2.
Mobile Software Development ISCG 7424 Department of Computing UNITEC John Casey and Richard Rabeder SQLite and Permissions.
Android Threads. Threads Android will show an “ANR” error if a View does not return from handling an event within 5 seconds Or, if some code running in.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Android - SQLite Database 12/10/2015. Introduction SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with.
SQlite. SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
Address Book App 1 Fall 2014 CS7020: Game Design and Development.
CHAPTER 9 File Storage Shared Preferences SQLite.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Data Storage in Android Димитър Н. Димитров. Why talk about data? Why not 3D graphics or network connectivity? Data as fundamental term in computer science.
CS371m - Mobile Computing Persistence - SQLite. 2 In case you have not taken 347: Data Management or worked with databases as part of a job, internship,
CS499 – Mobile Application Development
Making content providers
Data Storage: Part 3 (SQLite)
Android aplikacija i baze podataka
Mobile Applications (Android Programming)
SQLite in Android Landon Cox March 2, 2017.
Mobile Software Development for Android - I397
Android – Event Handling
ListView: Part 2.
Mobile Applications (Android Programming)
Android Application SQLite 1.
Reactive Android Development
Android Database using SQLite
Mobile Application Development Chapter 5 [Persistent Data in Android]
Mobile Applications (Android Programming)
Android Storage.
Mobile Computing With Android ACST Android Database Storage Part 2
File Handling Programming Guides.
CMPE419 Mobile Application Development
CMPE419 Mobile Application Development
Android Topics Asynchronous Callsbacks
Android Developer Fundamentals V2
Android Developer Fundamentals V2
Threads, Handlers, and AsyncTasks
ListView A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view. ListAdapter is used to.
Department of School of Computing and Engineering
SQLLite and Android.
plus content providers, loaders, recyclerview
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

Mobile Computing With Android ACST 4550 Android Database Storage

Working with a Database There are many different ways for storing the data of your Android applications. We saw previously, we can store data in the Android file system using the FileOutputStream and the FileInputStream. But what if you need to store structured data for your application, such as data more suited for storing in a database? That’s where SQLite comes in.

Working with a Database The first thing that must be done is to define the database table that should be created for storing the data in the database. Luckily, Android provides a helper class for defining a SQLite database table through Java code. That class is called SQLiteOpenHelper. You need to create a Java class that extends from the SQLiteOpenHelper. This is where you can define a database name and version, and where you define the tables and columns. This is also where you create and upgrade your database.

Sample SQLiteOpenHelper Code public class CardsDBHelper extends SQLiteOpenHelper { private static final String DEBUG_TAG = "CardsDBHelper"; private static final String DB_NAME = "cards.db"; private static final int DB_VERSION = 1; public static final String TABLE_CARDS = "CARDS"; public static final String COLUMN_ID = "_ID"; public static final String COLUMN_NAME = "NAME"; public static final String COLUMN_COLOR_RESOURCE = "COLOR_RESOURCE"; private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_CARDS + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_COLOR_RESOURCE + " INTEGER" + ")"; public CardsDBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } … For the SampleSQLite application, we created a CardsDBHelper class that extends from SQLiteOpenHelper, and here’s the implementation that can be found in the CardsDBHelper.java file.

Sample SQLiteOpenHelper Code … @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TABLE_CREATE); Log.i(DEBUG_TAG, "Table has been created"); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_CARDS); onCreate(db); This class starts off by defining a few static final variables for providing a name and version number, and an appropriate table name with table column names. Further, the TABLE_CREATE variable provides the SQL statement for creating the table in the database. The CardsDBHelper constructor accepts a context and this is where the database name and version are set. The onCreate() and onUpgrade() methods either create the new table or delete an existing table, and then create a new table. You should also notice that the table provides one column for the _ID as an INTEGER, one column for the NAME as TEXT, and one column for the COLOR_RESOURCE as an INTEGER.

Providing Data Access public class CardsData { public static final String DEBUG_TAG = "CardsData"; private SQLiteDatabase db; private SQLiteOpenHelper cardDbHelper; private static final String[] ALL_COLUMNS = { CardsDBHelper.COLUMN_ID, CardsDBHelper.COLUMN_NAME, CardsDBHelper.COLUMN_COLOR_RESOURCE }; public CardsData(Context context) { this.cardDbHelper = new CardsDBHelper(context); } … Now that you are able to create a database, you now need a way to access the database. To do so, we will create a class that provides us access to the database from the SQLiteDatabase class using the SQLiteOpenHelper class. This class is where we will be defining the methods for adding, updating, deleting, and querying the database. The class for doing so is provided in the CardsData.java file and a partial implementation can be found here. Notice the CardsData() constructor. This creates a new CardsDBHelper() object which will allow us to access the database.

Providing Data Access … public void open() { db = cardDbHelper.getWritableDatabase(); Log.d(DEBUG_TAG, "cardDbHelper opened"); } public void close() { if (cardDbHelper != null) { cardDbHelper.close(); Log.d(DEBUG_TAG, "cardDbHelper closed"); The open() method is where the database is created with the getWritableDatabase() method. The close() method is for closing the database. It is important to close the database to release any resources obtained by the object so that unexpected errors do not occur in your application during use. You also want to open and close the database during your application’s particular lifecycle events so that you are only executing database operations at the times where you have the appropriate access.

Updating Data in the Activity Class public CardsData cardsData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample_material); cardsData = new CardsData(this); names = getResources().getStringArray(R.array.names_array); colors = getResources().getIntArray(R.array.initial_colors); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); new GetOrCreateCardsListTask().execute(); … The onCreate() method of the SampleMaterialActivity now needs to create a new data access object and open the database. Here is the updated onCreate() method.

Updating Data in the Activity Class … FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Pair<View, String> pair = Pair.create(v.findViewById(R.id.fab), TRANSITION_FAB); ActivityOptionsCompat options; Activity act = SampleMaterialActivity.this; options = ActivityOptionsCompat.makeSceneTransitionAnimation(act, pair); Intent transitionIntent = new Intent(act, TransitionAddActivity.class); act.startActivityForResult(transitionIntent, adapter.getItemCount(), options.toBundle()); } }); Notice the new GetOrCreateCardsListTask().execute() method call on the previous slide. We cover this implementation later in this chapter. This method queries the database for all cards or fills the database with cards if it is empty.

Database Operations Off UI Thread public class GetOrCreateCardsListTask extends AsyncTask<Void, Void, ArrayList<Card>> { @Override protected ArrayList<Card> doInBackground(Void... params) { cardsData.open(); cardsList = cardsData.getAll(); if (cardsList.size() == 0) { for (int i = 0; i < 50; i++) { Card card = new Card(); card.setName(names[i]); card.setColorResource(colors[i]); cardsList.add(card); cardsData.create(card); } return cardsList; protected void onPostExecute(ArrayList<Card> cards) { super.onPostExecute(cards); adapter = new SampleMaterialAdapter(SampleMaterialActivity.this, cardsList, cardsData); recyclerView.setAdapter(adapter); To make sure that the main UI thread of your Android application does not block during a potentially long-running database operation, you should run your database operations in a background thread. Here we have implemented an AsyncTask for creating new cards in the database, and subsequently updating the UI only after the database operation is complete. Here is the GetOrCreateCardsListTask class that extends the AsyncTask class, which either retrieves all the cards from the database or creates them.

Database Operations Off UI Thread When the GetOrCreateCardsListTask class is created and executed in the onCreate() method of the Activity, it overrides the doInBackground() method and creates a background task for retrieving all the cards from the database with the call to getAll(). If no items are returned, that means the database is empty and needs to be populated with entries. The for loop creates 50 Cards. Each Card is added to the cardsList and created in the database with the call to create(). Once the background operation is complete, the onPostExecute() method, which was also overridden from the AsyncTask class, receives the cardsList result from the doInBackground() operation. It then uses the cardsList and cardsData to create a new SampleMaterialAdapter. It then adds that adapter to the recyclerView to update the UI once the entire background operation has completed.