Easy Tutorial
❮ Verilog2 Lower Power Design Search Websites Recommand ❯

6.3.1 Data Storage and Access - An Introduction to SQLite Databases

Category Android Basic Tutorial

Introduction to This Section:

>

In this section, we will continue to learn about the third method of Android data storage and access: the SQLite database. Unlike other SQL databases, we do not need to install a separate database software on the phone. The Android system has already integrated this database. We don't need to install and configure other database software (Oracle, MSSQL, MySQL, etc.), nor do we need to change ports and so on! That's all for the introduction, let's learn about this next.


1. Basic Concepts

1) What is SQLite? Why use SQLite? What are the features of SQLite?

>

Answer: Please listen to the detailed explanation by the little pig:

① SQLite is a lightweight relational database with fast computation speed and low resource consumption, making it very suitable for use on mobile devices. It not only supports standard SQL syntax but also follows the ACID (database transaction) principle. There is no need for an account, and it is very convenient to use!

② Previously, we learned to use files and SharedPreference to save data, but in many cases, files may not be effective, such as concurrent access in multi-threading; the app needs to handle potentially changing complex data structures, etc.! For example, bank deposits and withdrawals! Using the former two would seem very weak or cumbersome, and the emergence of the database can solve this problem, and Android has provided us with such a lightweight SQLite, why not use it?

③ SQLite supports five data types: NULL, INTEGER, REAL (floating point), TEXT (string text), and BLOB (binary object). Although there are only five, other data types such as varchar and char can also be saved; because SQLite has a major feature: you can save data of various data types in any field without worrying about the data type declared in the field, for example, you can store strings in an Integer type field, of course, except for the fields declared as INTEGER PRIMARY KEY, which can only store 64-bit integers! In addition, SQLite will ignore the data type information following the field name in the CREATE TABLE statement, such as the following statement will ignore the type information of the name field: CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))

Summary of features:

SQLite saves the database through files, a file is a database, the database contains multiple tables, the tables have multiple records, each record is composed of multiple fields, each field has a corresponding value, and each value can be specified with a type, or the type can also be unspecified (except for the primary key)

PS: By the way, the SQLite built into Android is version 3 of SQLite~

2) Several related classes:

>

Hehe, when learning something new, the most disliked thing is to encounter new terms, right? Let's first talk about the three classes we use when using the database:


2. Creating the Database and Version Management Using the SQLiteOpenHelper Class

>

For apps involving databases, we can't manually create the database file for them, so we need to create the database table when the app is first used; and when our app is upgraded and the structure of the database table needs to be modified, it is necessary to update the database table at this time; for these two operations, Android provides two methods of SQLiteOpenHelper, onCreate ( ) and onUpgrade ( ) to achieve this.

Method Analysis:

>

private void bindViews() { btn_insert = (Button) findViewById(R.id.btn_insert); btn_query = (Button) findViewById(R.id.btn_query); btn_update = (Button) findViewById(R.id.btn_update); btn_delete = (Button) findViewById(R.id.btn_delete);

btn_query.setOnClickListener(this);
btn_insert.setOnClickListener(this);
btn_update.setOnClickListener(this);
btn_delete.setOnClickListener(this);

}

@Override public void onClick(View v) { db = myDBHelper.getWritableDatabase(); switch (v.getId()) { case R.id.btn_insert: ContentValues values1 = new ContentValues(); values1.put("name", "Hehe~" + i); i++; //Parameters in order are: table name, column name for forcing null values, data for one record db.insert("person", null, values1); Toast.makeText(mContext, "Insertion complete~", Toast.LENGTH_SHORT).show(); break; case R.id.btn_query: sb = new StringBuilder(); //Parameters in order are: table name, column names, where constraint, specific values for placeholders in where, columns for group by, further constraints //Specify the sort order for the query results Cursor cursor = db.query("person", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { int pid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); sb.append("id: " + pid + ": " + name + "\n"); } while (cursor.moveToNext()); } cursor.close(); Toast.makeText(mContext, sb.toString(), Toast.LENGTH_SHORT).show(); break; case R.id.btn_update: ContentValues values2 = new ContentValues(); values2.put("name", "Xixi~"); //Parameters in order are: table name, new values, where condition, and constraints. If the last two parameters are not specified, all rows will be changed db.update("person", values2, "name = ?", new String[]{"Hehe~2"}); break; case R.id.btn_delete: //Parameters in order are: table name, and where condition with constraints db.delete("person", "personid = ?", new String[]{"3"}); break; } }


5. Using SQL statements to operate the database

>

Of course, you may have already learned SQL and can write related SQL statements, and you don't want to use these APIs provided by Android. You can directly use the methods provided by SQLiteDatabase:

Example of using code:

1. Inserting data:

public void save(Person p)
{
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    db.execSQL("INSERT INTO person(name,phone) values(?,?)",
                new String[]{p.getName(),p.getPhone()});
}

2. Deleting data:

public void delete(Integer id)
{
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    db.execSQL("DELETE FROM person WHERE personid = ?",
                new String[]{id});
}

3. Modifying data:

public void update(Person p)
{
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    db.execSQL
6. Query Record Count:

```java
public long getCount()
{
    SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
    Cursor cursor =  db.rawQuery("SELECT COUNT (*) FROM person", null);
    cursor.moveToFirst();
    long result = cursor.getLong(0);
    cursor.close();
    return result;      
}

PS : In addition to the above method of obtaining the number of entries, you can also use the cursor.getCount() method to get the number of data entries, but the SQL statement needs to be changed! For example, SELECT * FROM person;


Summary of This Section:

>

This section introduced the basic usage of Android's built-in SQLite, which is relatively simple. In the next section, we will explore some more advanced topics, such as SQLite transactions, how to handle data updates in the database, and methods for storing large binary files in the database! Alright, that's it for this section.

-1.0 Android Basic Tutorial for Beginners

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background and System Architecture Analysis

-1.2 Setting Up the Development Environment

-1.2.1 Developing Android APPs with Eclipse + ADT + SDK

-1.2.2 Developing Android APPs with Android Studio

-1.3 Solving SDK Update Issues

-1.4 Installing Genymotion Emulator

-1.5.1 Git Tutorial on Basic Operations of Local Repositories

-1.5.2 Git: Setting Up Remote Repositories with GitHub

-1.6 How to Play with 9 (Jiu Mei) Images

-1.7 Interface Prototype Design

-1.8 Project-Related Analysis (Various Files, Resource Access)

-1.9 Android App Signing and Packaging

-1.11 Decompiling APK to Retrieve Code & Resources

-2.1 The Concept of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 TextView (Text Box) Detailed Explanation

-2.3.2 EditText (Input Box) Detailed Explanation

-2.3.3 Button (Button) and ImageButton (Image Button)

-2.3.4 ImageView (Image View)

-2.3.5 RadioButton (Radio Button) & Checkbox (Checkbox)

-2.3.6 ToggleButton (Toggle Button) and Switch (Switch)

-2.3.7 ProgressBar (Progress Bar)

-2.3.8 SeekBar (Slider)

-2.3.9 RatingBar (Rating Bar)

-2.4.1 ScrollView (Scroll View)

-2.4.2 Date & Time Components (Part 1)

-2.4.3 Date & Time Components (Part 2)

-2.4.4 Adapter Basics

-2.4.5 Simple and Practical ListView

-2.4.6 Optimizing with BaseAdapter

-[2.4.7 ListView

Follow on WeChat

❮ Verilog2 Lower Power Design Search Websites Recommand ❯