Android SQLite数据库示例教程

本文是Android SQLite数据库的教程,讲解了如何使用SQLiteOpenHelper创建、升级数据库,以及打开和关闭数据库连接,插入、更新和删除记录的方法。示例项目展示了如何存储国家和货币信息,并通过ListView展示数据。
摘要由CSDN通过智能技术生成

Welcome to Android SQLite Example Tutorial. Android SQLite is the mostly preferred way to store data for android applications. For many applications, SQLite is the apps backbone whether it’s used directly or via some third-party wrapper. Below is the final app we will create today using Android SQLite database.

欢迎使用Android SQLite示例教程。 Android SQLite是为Android应用程序存储数据的首选方法。 对于许多应用程序而言,无论直接使用SQLite还是通过第三方包装器使用,SQLite都是应用程序的骨干。 以下是我们今天将使用Android SQLite数据库创建的最终应用程序。

Android SQLite (Android SQLite)

Android SQLite is a very lightweight database which comes with Android OS. Android SQLite combines a clean SQL interface with a very small memory footprint and decent speed. For Android, SQLite is “baked into” the Android runtime, so every Android application can create its own SQLite databases.

Android SQLite是Android OS附带的非常轻量级的数据库。 Android SQLite结合了干净SQL界面,很小的内存占用和不错的速度。 对于Android,SQLite被“嵌入”到Android运行时中,因此每个Android应用程序都可以创建自己SQLite数据库。

Android SQLite native API is not JDBC, as JDBC might be too much overhead for a memory-limited smartphone. Once a database is created successfully its located in data/data//databases/ accessible from Android Device Monitor.

Android SQLite本机API不是JDBC,因为对于内存受限的智能手机而言,JDBC可能会产生过多开销。 成功创建数据库后,其位于data / data // databases /中,可通过Android Device Monitor访问。

SQLite is a typical relational database, containing tables (which consists of rows and columns), indexes etc. We can create our own tables to hold the data accordingly. This structure is referred to as a schema.

SQLite是一个典型的关系数据库 ,包含表(由行和列组成),索引等。我们可以创建自己的表来相应地保存数据。 此结构称为架构

Android SQLite SQLiteOpenHelper (Android SQLite SQLiteOpenHelper)

Android has features available to handle changing database schemas, which mostly depend on using the SQLiteOpenHelper class.

Android具有可用于处理数据库模式更改的功能,这些功能主要取决于使用SQLiteOpenHelper类。

SQLiteOpenHelper is designed to get rid of two very common problems.

SQLiteOpenHelper旨在摆脱两个非常常见的问题。

  1. When the application runs the first time – At this point, we do not yet have a database. So we will have to create the tables, indexes, starter data, and so on.

    当应用程序首次运行时–此时,我们还没有数据库。 因此,我们将不得不创建表,索引,启动器数据等。
  2. When the application is upgraded to a newer schema – Our database will still be on the old schema from the older edition of the app. We will have option to alter the database schema to match the needs of the rest of the app.

    当应用程序升级到较新的架构时–我们的数据库仍将位于较旧版本的应用程序的旧架构上。 我们将具有更改数据库架构的选项,以匹配应用程序其余部分的需求。

SQLiteOpenHelper wraps up these logic to create and upgrade a database as per our specifications. For that we’ll need to create a custom subclass of SQLiteOpenHelper implementing at least the following three methods.

SQLiteOpenHelper了这些逻辑,以根据我们的规范创建和升级数据库。 为此,我们需要创建一个SQLiteOpenHelper的自定义子类,至少实现以下三种方法。

  1. Constructor : This takes the Context (e.g., an Activity), the name of the database, an optional cursor factory (we’ll discuss this later), and an integer representing the version of the database schema you are using (typically starting from 1 and increment later).
    public DatabaseHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

    构造函数 :这需要Context(例如Activity),数据库名称,可选的游标工厂(我们将在后面讨论)和代表您所使用的数据库模式版本的整数(通常从1开始)然后再增加)。
  2. onCreate(SQLiteDatabase db) : It’s called when there is no database and the app needs one. It passes us a SQLiteDatabase object, pointing to a newly-created database, that we can populate with tables and initial data.

    onCreate(SQLiteDatabase db) :在没有数据库且应用程序需要一个数据库时调用。 它向我们传递了一个SQLiteDatabase对象,该对象指向一个新创建的数据库,我们可以在其中填充表和初始数据。
  3. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) : It’s called when the schema version we need does not match the schema version of the database, It passes us a SQLiteDatabase object and the old and new version numbers. Hence we can figure out the best way to convert the database from the old schema to the new one.

    onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) :当我们需要的架构版本与数据库的架构版本不匹配时,将调用此方法,它会向我们传递一个SQLiteDatabase对象以及新旧版本号。 因此,我们可以找出将数据库从旧模式转换为新模式的最佳方法。

We define a DBManager class to perform all database CRUD(Create, Read, Update and Delete) operations.

我们定义一个DBManager类来执行所有数据库CRUD(创建,读取,更新和删除)操作。

打开和关闭Android SQLite数据库连接 (Opening and Closing Android SQLite Database Connection)

Before performing any database operations like insert, update, delete records in a table, first open the database connection by calling getWritableDatabase() method as shown below:

在执行任何数据库操作(如插入,更新,删除表中的记录)之前,首先通过调用getWritableDatabase()方法打开数据库连接,如下所示:

public DBManager open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        return this;
    }

The dbHelper is an instance of the subclass of SQLiteOpenHelper.

dbHelperSQLiteOpenHelper子类的SQLiteOpenHelper

To close a database connection the following method is invoked.

要关闭数据库连接,将调用以下方法。

public void close() {
        dbHelper.close();
    }

将新记录插入Android SQLite数据库表 (Inserting new Record into Android SQLite database table)

The following code snippet shows how to insert a new record in the android SQLite database.

以下代码段显示了如何在android SQLite数据库中插入新记录。

public void insert(String name, String desc) {
        ContentValues contentValue = new ContentValues();
        contentValue.put(DatabaseHelper.SUBJECT, name);
        contentValue.put(DatabaseHelper.DESC, desc);
        database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
    }

Content Values creates an empty set of values using the given initial size. We’ll discuss the other instance values when we jump into the coding part.

内容值会使用给定的初始大小创建一组空值。 当我们跳到编码部分时,我们将讨论其他实例值。

更新Android SQLite数据库表中的记录 (Updating Record in Android SQLite database table)

The following snippet shows how to update a single record.

以下代码段显示了如何更新单个记录。

public int update(long _id, String name, String desc) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DatabaseHelper.SUBJECT, name);
        contentValues.put(DatabaseHelper.DESC, desc);
        int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
        return i;
    }

Android SQLite –删除记录 (Android SQLite – Deleting a Record)

We just need to pass the id of the record to be deleted as shown below.

我们只需要传递要删除的记录的ID,如下所示。

public void delete(long _id) {
        database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
    }

Android SQLite游标 (Android SQLite Cursor)

A Cursor represents the entire result set of the query. Once the query is fetched a call to cursor.moveToFirst() is made. Calling moveToFirst() does two things:

游标代表查询的整个结果集。 提取查询后, 将对cursor.moveToFirst()进行调用。 调用moveToFirst()有两件事:

  • It allows us to test whether the query returned an empty set (by testing the return value)

    它允许我们测试查询是否返回空集(通过测试返回值)
  • It moves the cursor to the first result (when the set is not empty)

    它将光标移动到第一个结果(当集合不为空时)

The following code is used to fetch all records:

以下代码用于获取所有记录:

public Cursor fetch() {
        String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC };
        Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

Another way to use a Cursor is to wrap it in a CursorAdapter. Just as ArrayAdapter adapts arrays, CursorAdapter adapts Cursor objects, making their data available to an AdapterView like a ListView.

使用Cursor的另一种方法是将其包装在CursorAdapter 。 就像ArrayAdapter适应数组一样, CursorAdapter适应Cursor对象,使它们的数据像ListView一样可用于AdapterView

Let’s jump to our project that uses SQLite to store some meaningful data.

让我们跳到使用SQLite存储一些有意义的数据的项目。

Android SQLite示例项目结构 (Android SQLite Example Project Structure)

In this application we wish to create records that store Country names and their respective currencies in the form of a ListView. We cover all the features discusses above.

在此应用程序中,我们希望创建以ListView形式存储国家名称及其各自货币的记录。 我们涵盖了上面讨论的所有功能。

Android SQLite项目代码 (Android SQLite Project Code)

The application consists of 5 classes. We begin with defining with DatabaseHelper, which is a subclass of SQLiteOpenHelper as follows:

该应用程序包含5个类。 我们首先使用DatabaseHelper进行定义,它是SQLiteOpenHelper的子类,如下所示:

DatabaseHelper.java

DatabaseHelper.java

package com.journaldev.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

    // Table Name
    public static final String TABLE_NAME = "COUNTRIES";

    // Table columns
    public static final String _ID = "_id";
    public static final String SUBJECT = "subject";
    public static final String DESC = "description";

    // Database Information
    static final String DB_NAME = "JOURNALDEV_COUNTRIES.DB";

    // database version
    static final int DB_VERSION = 1;

    // Creating table query
    private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + _ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT + " TEXT NOT NULL, " + DESC + " TEXT);";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

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

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

As discussed above we have overridden the onCreate() and onUpgrade() methods besides the constructor. We’ve assigned the names to the database and the table as JOURNALDEV_COUNTRIES.DB and COUNTRIES respectively. The index column is auto incremented whenever a new row is inserted. The column names for country and currency are “subject” and “description”.

如上所述,除了构造函数之外,我们还重写了onCreate()onUpgrade()方法。 我们已将名称分别分配给数据库和表,分别为JournalDEV_COUNTRIES.DB和COUNTRIES。 每当插入新行时,索引列都会自动递增。 国家和货币的列名称为“主题”和“描述”。

The DBManager classes is where the DatabaseHelper is initialized and the CRUD Operations are defined. Below is the code for this class:

在DBManager类中,可以初始化DatabaseHelper并定义CRUD操作。 下面是该类的代码:

DBManager.java

DBManager.java

package com.journaldev.sqlite;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBManager {

    private DatabaseHelper dbHelper;

    private Context context;

    private SQLiteDatabase database;

    public DBManager(Context c) {
        context = c;
    }

    public DBManager open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        dbHelper.close();
    }

    public void insert(String name, String desc) {
        ContentValues contentValue = new ContentValues();
        contentValue.put(DatabaseHelper.SUBJECT, name);
        contentValue.put(DatabaseHelper.DESC, desc);
        database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
    }

    public Cursor fetch() {
        String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC };
        Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    public int update(long _id, String name, String desc) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DatabaseHelper.SUBJECT, name);
        contentValues.put(DatabaseHelper.DESC, desc);
        int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
        return i;
    }

    public void delete(long _id) {
        database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
    }

}

The CountryListActivity.java class is the activity which is launched when the application starts. Below is layout defined for it:

CountryListActivity.java类是在应用程序启动时启动的活动。 下面是为其定义的布局:

fragment_emp_list.xml

fragment_emp_list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp"
        android:padding="10dp" >
    </ListView>

    <TextView
        android:id="@+id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/empty_list_text" />

</RelativeLayout>

Here a ListView component is defined to included the records stored in the database. Initially the ListView would be empty hence a TextView is used to display the same.

在此,将ListView组件定义为包括存储在数据库中的记录。 最初,ListView将为空,因此使用TextView来显示它。

CountryListActivity.java

CountryListActivity.java

package com.journaldev.sqlite;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

public class CountryListActivity extends ActionBarActivity {

    private DBManager dbManager;

    private ListView listView;

    private SimpleCursorAdapter adapter;

    final String[] from = new String[] { DatabaseHelper._ID,
            DatabaseHelper.SUBJECT, DatabaseHelper.DESC };

    final int[] to = new int[] { R.id.id, R.id.title, R.id.desc };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_emp_list);

        dbManager = new DBManager(this);
        dbManager.open();
        Cursor cursor = dbManager.fetch();

        listView = (ListView) findViewById(R.id.list_view);
        listView.setEmptyView(findViewById(R.id.empty));

        adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
        adapter.notifyDataSetChanged();

        listView.setAdapter(adapter);

        // OnCLickListiner For List Items
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
                TextView idTextView = (TextView) view.findViewById(R.id.id);
                TextView titleTextView = (TextView) view.findViewById(R.id.title);
                TextView descTextView = (TextView) view.findViewById(R.id.desc);

                String id = idTextView.getText().toString();
                String title = titleTextView.getText().toString();
                String desc = descTextView.getText().toString();

                Intent modify_intent = new Intent(getApplicationContext(), ModifyCountryActivity.class);
                modify_intent.putExtra("title", title);
                modify_intent.putExtra("desc", desc);
                modify_intent.putExtra("id", id);

                startActivity(modify_intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.add_record) {

            Intent add_mem = new Intent(this, AddCountryActivity.class);
            startActivity(add_mem);

        }
        return super.onOptionsItemSelected(item);
    }

}

In this activity the DBManager object is invoked to perform the CRUD Operations.

在此活动中,将调用DBManager对象以执行CRUD操作。

A SimpleCursorAdapter is defined to add elements to the list from the query results that are returned in an Cursor Object.
On list item click an intent is performed to open the ModifyCountryActivity class.

定义了一个SimpleCursorAdapter,以将游标对象中返回的查询结果中的元素添加到列表中。
在列表项上单击一个意图,以打开ModifyCountryActivity类。

The menu contains an item to add a new record from the ActionBar. Here again an intent is performed to open the AddCountryActivity class. Below is menu.xml code.

该菜单包含一个用于从ActionBar添加新记录的项目。 在这里再次执行一个意图来打开AddCountryActivity类。 以下是menu.xml代码。

menu.xml

menu.xml

<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    tools:context="com.example.sqlitesample.MainActivity" >

    <item
        android:id="@+id/add_record"
        android:icon="@android:drawable/ic_menu_add"
        android:orderInCategory="100"
        android:title="@string/add_record"
        app:showAsAction="always"/>

</menu>

The xml layout and code of AddCountryActivity.java file are defined below:

AddCountryActivity.java文件的xml布局和代码定义如下:

activity_add_record.xml

activity_add_record.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp" >

    <EditText
        android:id="@+id/subject_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/enter_title" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/description_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/enter_desc"
        android:inputType="textMultiLine"
        android:minLines="5" >
    </EditText>

    <Button
        android:id="@+id/add_record"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/add_record" />

</LinearLayout>

Two EditText components that take the inputs for country and currency along with a button to add the values to the database and display it in the ListView are defined.

定义了两个EditText组件,这些组件接受国家和货币的输入以及一个将值添加到数据库并在ListView中显示的按钮。

AddCountryActivity.java

AddCountryActivity.java

package com.journaldev.sqlite;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class AddCountryActivity extends Activity implements OnClickListener {

    private Button addTodoBtn;
    private EditText subjectEditText;
    private EditText descEditText;

    private DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTitle("Add Record");

        setContentView(R.layout.activity_add_record);

        subjectEditText = (EditText) findViewById(R.id.subject_edittext);
        descEditText = (EditText) findViewById(R.id.description_edittext);

        addTodoBtn = (Button) findViewById(R.id.add_record);

        dbManager = new DBManager(this);
        dbManager.open();
        addTodoBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_record:

                final String name = subjectEditText.getText().toString();
                final String desc = descEditText.getText().toString();

                dbManager.insert(name, desc);

                Intent main = new Intent(AddCountryActivity.this, CountryListActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                startActivity(main);
                break;
        }
    }

}

The CRUD operation performed here is adding a new record to the database.

此处执行的CRUD操作是将新记录添加到数据库中。

The xml layout and code of ModifyCountryActivity.java file are defined below:

下面定义ModifyCountryActivity.java文件的xml布局和代码:

activity_modify_record.xml

activity_modify_record.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <EditText
        android:id="@+id/subject_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:ems="10"
        android:hint="@string/enter_title" />

    <EditText
        android:id="@+id/description_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/enter_desc"
        android:inputType="textMultiLine"
        android:minLines="5" >
    </EditText>


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/btn_update" />

        <Button
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/btn_delete" />
    </LinearLayout>

</LinearLayout>

It’s similar to the previous layout except that modify and delete buttons are added.

除了添加了“修改”和“删除”按钮之外,它与以前的布局相似。

ModifyCountryActivity.java

ModifyCountryActivity.java

package com.journaldev.sqlite;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ModifyCountryActivity extends Activity implements OnClickListener {

    private EditText titleText;
    private Button updateBtn, deleteBtn;
    private EditText descText;

    private long _id;

    private DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTitle("Modify Record");

        setContentView(R.layout.activity_modify_record);

        dbManager = new DBManager(this);
        dbManager.open();

        titleText = (EditText) findViewById(R.id.subject_edittext);
        descText = (EditText) findViewById(R.id.description_edittext);

        updateBtn = (Button) findViewById(R.id.btn_update);
        deleteBtn = (Button) findViewById(R.id.btn_delete);

        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        String name = intent.getStringExtra("title");
        String desc = intent.getStringExtra("desc");

        _id = Long.parseLong(id);

        titleText.setText(name);
        descText.setText(desc);

        updateBtn.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_update:
                String title = titleText.getText().toString();
                String desc = descText.getText().toString();

                dbManager.update(_id, title, desc);
                this.returnHome();
                break;

            case R.id.btn_delete:
                dbManager.delete(_id);
                this.returnHome();
                break;
        }
    }

    public void returnHome() {
        Intent home_intent = new Intent(getApplicationContext(), CountryListActivity.class)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(home_intent);
    }
}

The CRUD operations performed here are updating and deleting a record.

此处执行的CRUD操作是更新和删除记录。

The below images are the screenshots of the final output of our project.

下图是我们项目最终输出的屏幕截图。

The first image is the output seen when the application is launched for the first time.

android sqlite

第一个图像是首次启动应用程序时看到的输出。

The second image is the result of clicking the menu option from the ActionBar to add a new record as shown below.

android sqlite example create

第二张图片是单击ActionBar中的菜单选项以添加新记录的结果,如下所示。

The third image shows an output when 3 records are added :

android sqlite example crud

第三张图片显示了添加3条记录时的输出:

The fourth image shows the output when any list item is clicked to modify or delete a record :

android sqlite example update

第四个图像显示了单击任何列表项以修改或删除记录时的输出:

The final image is the output when a record is deleted. In this example we delete the first record :

android sqlite example delete

最终图像是删除记录时的输出。 在此示例中,我们删除第一条记录:

打开Android SQLite数据库文件 (Opening the Android SQLite Database file)

As we’ve discussed earlier in this tutorial, the database file is stored in the internal storage that is accessible from the Android Device Monitor as visible in the pic below.

正如我们在本教程前面所讨论的那样,数据库文件存储在内部存储中,可从Android设备监视器访问该内部存储,如下图所示。

To view this database we need to pull this file from the device to our desktop. This is done by clicking the menu option in the top right as seen in the image below :

android sqlite pull file from device

要查看此数据库,我们需要将该文件从设备中拉到桌面。 通过单击右上角的菜单选项来完成此操作,如下图所示:

To open this file download the SQLiteBrowser from this link.

要打开这个文件下载从SQLiteBrowser 这个链接。

The snippets below show the schema and tables in the browser.

下面的片段显示了浏览器中的架构和表。

To view the table go to the Browse Data tab on top. The following image is seen:

要查看该表,请转到顶部的“浏览数据”选项卡。 可以看到以下图像:

This brings an end to Android SQLite tutorial. The final Android SQLite Project is downloadable from the below link.

这结束了Android SQLite教程。 最终的Android SQLite项目可从下面的链接下载。

翻译自: https://www.journaldev.com/9438/android-sqlite-database-example-tutorial

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值