Home > Articles > Mobile Application Development & Programming

Saving with SQLite

This chapter is from the book

Working with Databases

The first thing that must be done is to define the database table that should be created for storing the cards 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, and 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. 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:

public class CardsDBHelper extends SQLiteOpenHelper {
    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);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CARDS);
        onCreate(db);
    }
}
Figure 16.1

Figure 16.1 Showing the SampleSQLite application.

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

Now that you are able to create a database, you need a way to access the database. To do so, you will create a class that provides 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 this is provided in the CardsData.java file and a partial implementation can be found here:

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);
    }

    public void open() {
        db = cardDbHelper.getWritableDatabase();    }

    public void close() {
        if (cardDbHelper != null) {
            cardDbHelper.close();        }
    }
}

Notice the CardsData() constructor. This creates a new CardsDBHelper() object that will allow us to access the database. 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 when you have the appropriate access.

Updating the SampleMaterialActivity Class

The onCreate() method of the SampleMaterialActivity now creates a new data access object and opens the database. Here is the updated onCreate() method:

public CardsData cardsData = new CardsData(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample_material);

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

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

Updating the SampleMaterialAdapter Constructor

An update in the SampleMaterialAdapter class is also needed, and the constructor is shown below:

public CardsData cardsData;
public SampleMaterialAdapter(Context context, ArrayList<Card> cardsList,
            CardsData cardsData) {
    this.context = context;
    this.cardsList = cardsList;
    this.cardsData = cardsData;
}

Notice a CardsData object is passed into the constructor to ensure the database is available to the SampleMaterialAdapter object once it is created.

Database Operations Off the Main UI Thread

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 will subsequently update 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:

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);
                Log.d(DEBUG_TAG, "Card created with id " + card.getId() + ",
name " + card.getName() + ", color " + card.getColorResource());
            }
        }
        return cardsList;
    }

    @Override
    protected void onPostExecute(ArrayList<Card> cards) {
        super.onPostExecute(cards);
        adapter = new SampleMaterialAdapter(SampleMaterialActivity.this,
                cardsList, cardsData);
        recyclerView.setAdapter(adapter);
    }
}

When this 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 and each Card is added to the cardsList, and then 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, and then adds that adapter to the recyclerView to update the UI once the entire background operation has completed.

Notice the AsyncTask class has three types defined; the first is of type Void, the second is also Void, and the third is ArrayList<Card>. These map to the Params, Progress, and Result generic types of an AsyncTask. The first Params is used as the parameter of the doInBackground() method, which are Void, and the third Result generic is used as the parameter of the onPostExecute() method. In this case, the second Void generic was not used, but would be used as the parameter for the onProgressUpdate() method of an AsyncTask.

Creating a Card in the Database

The magic happens in the call to cardsData.create(). This is where the Card is inserted into the database. Here is the create() method definition found in the CardsData class:

public Card create(Card card) {
    ContentValues values = new ContentValues();
    values.put(CardsDBHelper.COLUMN_NAME, card.getName());
    values.put(CardsDBHelper.COLUMN_COLOR_RESOURCE, card.getColorResource());
    long id = db.insert(CardsDBHelper.TABLE_CARDS, null, values);
    card.setId(id);
    Log.d(DEBUG_TAG, "Insert id is " + String.valueOf(card.getId()));
    return card;
}

The create() method accepts a Card data object. A ContentValues object is created to temporarily store the data that will be inserted into the database in a structured format. There are two value.put() calls that map the database column to a Card attribute. The insert() method is then called on the cards table and the temporary values are passed in for insertion. An id is returned from the call to insert() and that value is then set as the id for the Card, and finally a Card object is returned. Figure 16.2 shows the logcat output of cards being inserted into the database.

Figure 16.2

Figure 16.2 logcat output showing items inserted into the database.

Getting All Cards

Earlier, we mentioned the getAll() method that queries the database for all the cards in the cards table. Here is the implementation of the getAll() method:

public ArrayList<Card> getAll() {
    ArrayList<Card> cards = new ArrayList<>();
    Cursor cursor = null;
    try {
        cursor = db.query(CardsDBHelper.TABLE_CARDS,
                COLUMNS, null, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Card card = new Card();
                card.setId(cursor.getLong(cursor
                        .getColumnIndex(CardsDBHelper.COLUMN_ID)));
                card.setName(cursor.getString(cursor
                        .getColumnIndex(CardsDBHelper.COLUMN_NAME)));
                card.setColorResource(cursor
                        .getInt(cursor.getColumnIndex(CardsDBHelper
                                .COLUMN_COLOR_RESOURCE)));
                    cards.add(card);
            }
        }
    } catch (Exception e){
        Log.d(DEBUG_TAG, "Exception raised with a value of " + e);
    } finally{
        if (cursor != null) {
            cursor.close();
        }
    }
    return cards;
}

A query is performed on the cards table inside a try statement with a call to query() that returns all columns for the query as a Cursor object. A Cursor allows you to access the results of the database query. First, we ensure that the Cursor count is greater than zero, otherwise no results will be returned from the query. Next, we iterate through all the cursor objects by calling the moveToNext() method on the cursor, and for each database item, we create a Card data object from the data in the Cursor and set the Cursor data to Card data. We also handle any exceptions that we may have encountered, and finally the Cursor object is closed and all cards are returned.

Adding a New Card

You already know how to insert cards into the database because we did that to initialize the database. So adding a new Card is very similar to how we initialized the database. The addCard() method of the SampleMaterialAdapter class needs a slight modification. This method executes AsyncTask to add a new card in the background. Here is the updated implementation of the addCard() method creating a CreateCardTask and executing the task:

public void addCard(String name, int color) {
    Card card = new Card();
    card.setName(name);
    card.setColorResource(color);
    new CreateCardTask().execute(card);
}

private class CreateCardTask extends AsyncTask<Card, Void, Card> {
    @Override
    protected Card doInBackground(Card... cards) {
        cardsData.create(cards[0]);
        cardsList.add(cards[0]);
        return cards[0];
    }

    @Override
    protected void onPostExecute(Card card) {
        super.onPostExecute(card);
        ((SampleMaterialActivity) context).doSmoothScroll(getItemCount() - 1);
        notifyItemInserted(getItemCount());
        Log.d(DEBUG_TAG, "Card created with id " + card.getId() + ", name " +
                card.getName() + ", color " + card.getColorResource());
    }
}

The doInBackground() method makes a call to the create() method of the cardsData object, and in the onPostExecute() method, a call to the doSmoothScroll() method of the calling Activity is made, then the adapter is notified that a new Card has been inserted.

Updating a Card

To update a Card, we first need a way to keep track of the position of a Card within the list. This is not the same as the database id because the id of the item in the database is not the same as the position of the item in the list. The database increments the id of a Card, so each new Card has an id one higher than the previous Card. The RecyclerView list, on the other hand, shifts positions as items are added and removed from the list.

First, let’s update the Card data object found in the Card.java file and add a new listPosition attribute with the appropriate getter and setter methods as shown here:

private int listPosition = 0;

public int getListPosition() {
    return listPosition;
}

public void setListPosition(int listPosition) {
    this.listPosition = listPosition;
}

Next, update the updateCard() method of the SampleMaterialAdapter class and implement an UpdateCardTask class that extends AsyncTask as follows:

public void updateCard(String name, int list_position) {
    Card card = new Card();
    card.setName(name);
    card.setId(getItemId(list_position));
    card.setListPosition(list_position);
    new UpdateCardTask().execute(card);
}

private class UpdateCardTask extends AsyncTask<Card, Void, Card> {
    @Override
    protected Card doInBackground(Card... cards) {
        cardsData.update(cards[0].getId(), cards[0].getName());
        cardsList.get(cards[0].getListPosition()).setName(cards[0].getName());
        return cards[0];
    }

    @Override
    protected void onPostExecute(Card card) {
        super.onPostExecute(card);
        Log.d(DEBUG_TAG, "list_position is " + card.getListPosition());
        notifyItemChanged(card.getListPosition());
    }
}

The UpdateCardTask calls the update() method of the cardsData object in the doInBackground() method and then updates the name of the corresponding Card in the cardsList object and returns the Card. The onPostExecute() method then notifies the adapter that the item has changed with the notifyItemChanged() method call.

Finally, the CardsData class needs to implement the update() method to update the particular Card in the database. Here is the update() method:

public void update(long id, String name) {
    String whereClause = CardsDBHelper.COLUMN_ID + "=" + id;
    Log.d(DEBUG_TAG, "Update id is " + String.valueOf(id));
    ContentValues values = new ContentValues();
    values.put(CardsDBHelper.COLUMN_NAME, name);
    db.update(CardsDBHelper.TABLE_CARDS, values, whereClause, null);
}

The update() method accepts id and name parameters. A whereClause is then constructed for matching the id of the Card with the appropriate id column in the database, and a new ContentValues object is created for adding the updated name for the particular Card to the appropriate name column. Finally, the update() method is executed on the database.

Deleting a Card

Now let’s take a look at how to modify the deletion of cards. Remember the animateCircularDelete() method—this is where a Card was animated off the screen and deleted from the cardsList object. In the onAnimationEnd() method, construct a Card data object and pass that to the execute method of a DeleteCardTask object, which is an AsyncTask. Here are those implementations:

public void animateCircularDelete(final View view, final int list_position) {
    int centerX = view.getWidth();
    int centerY = view.getHeight();
    int startRadius = view.getWidth();
    int endRadius = 0;
    Animator animation = ViewAnimationUtils.createCircularReveal(view,
            centerX, centerY, startRadius, endRadius);

    animation.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            view.setVisibility(View.INVISIBLE);
            Card card = new Card();
            card.setId(getItemId(list_position));
            card.setListPosition(list_position);
            new DeleteCardTask().execute(card);
        }
    });
    animation.start();
}

private class DeleteCardTask extends AsyncTask<Card, Void, Card> {
    @Override
    protected Card doInBackground(Card... cards) {
        cardsData.delete(cards[0].getId());
        cardsList.remove(cards[0].getListPosition());
        return cards[0];
    }

    @Override
    protected void onPostExecute(Card card) {
        super.onPostExecute(card);
        notifyItemRemoved(card.getListPosition());
    }
}

The doInBackground() method of the DeleteCardTask calls the delete() method of the cardsData object and passes in the id of Card. Then the Card is removed from the cardsList object, and in the onPostExecute() method, the adapter is notified that an item has been removed by calling the notifyItemRemoved() method and passing in the list position of the Card that has been removed.

There is one last method to implement—the delete() method of the CardsData class. Here is that method:

public void delete(long cardId) {
    String whereClause = CardsDBHelper.COLUMN_ID + "=" + cardId;
    Log.d(DEBUG_TAG, "Delete position is " + String.valueOf(cardId));
    db.delete(CardsDBHelper.TABLE_CARDS, whereClause, null);
}

The delete() method of the CardsData class accepts an id of a Card, constructs a whereClause using that id, and then calls the delete() method on the cards table of the database, passing in the appropriate whereClause with the id of the Card to delete.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020