android studio 中的数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24844514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:51:13  来源:igfitidea点击:

Database in android studio

androiddatabasesqlitedatabase-designandroid-studio

提问by Amal B

I'm a windows phone developer and newly I started developing android apps using android studio.

我是一名 Windows 手机开发人员,最近我开始使用 android studio 开发 android 应用程序。

I need to create a database and store in it values and retrieve the updated values on screen, so I need help in:

我需要创建一个数据库并在其中存储值并在屏幕上检索更新的值,因此我需要以下帮助:

  1. Creating the database.
  2. How to show values from the database on screen?
  1. 创建数据库。
  2. 如何在屏幕上显示数据库中的值?

回答by Jimmy

to create database , you need to extend SQLiteOpenHelper and need a constructor that takes Context. lets say you name this class DBOperator. The table creation process will look something like this ,

要创建数据库,您需要扩展 SQLiteOpenHelper 并需要一个接受 Context 的构造函数。假设您将此类命名为 DBOperator。表创建过程看起来像这样,

public class DbOperator extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "DB_NAME";
    protected static final String FIRST_TABLE_NAME = "FIRST_TABLE";
    protected static final String SECOND_TABLE_NAME = "SECOND_TABLE";

    public static final String CREATE_FIRST_TABLE = "create table if not exists "
            + FIRST_TABLE_NAME
            + " ( _id integer primary key autoincrement, COL1  TEXT NOT NULL, COL2 TEXT NOT NULL,COL3 TEXT, COL4 int, COL5 TEXT,"
            + "COL6 TEXT,COL7 REAL, COL8 INTEGER,COL9 TEXT not null);";

    public static final String CREATE_SECOND_TABLE = "create table if not exists "
            + SECOND_TABLE_NAME+.........

    public DbOperator(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_SFIRST_TABLE);
        db.execSQL(CREATE_SECOND_TABLE);
        //db.close();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //THIS WILL BE EXECUTED WHEN YOU UPDATED VERSION OF DATABASE_VERSION
        //YOUR DROP AND CREATE QUERIES
    }
}


Now your data manipulation class ( add, delete , update ) will look something like this ,

现在您的数据操作类(添加、删除、更新)将如下所示,

public class FirstTableDML extends DbOperator {

    public FirstTableDML(Context context) {
        super(context);
    }

    private static final String COL_ID = "_id";
    private static final String COL1 = "COL1";
    private static final String COL2 = "COL2";
    ........
    .......

    public void deleteFirstTableDataList(List<FirstTableData> firstTableDataList) {
        for (FirstTableData data : firstTableDataList)
            deleteFirstTableDetailData(data);
    }
    public void deleteFirstTableDetailData(FirstTableData item) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(FIRST_TABLE_NAME, item.getId() + "=" + COL_ID, null);
        db.close();
    }
    /**this method retrieves all the records from table and returns them as list of  
     FirstTableData types. Now you use this list to display detail on your screen as per your 
    requirements.
    */
    public List< FirstTableData > getFirstTableDataList() {
        List< FirstTableData > firstTableDataList = new ArrayList< FirstTableData >();
        String refQuery = "Select * From " + FIRST_TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(refQuery, null);
        try {
            if (cursor.moveToFirst()) {
                do {
                    FirstTableData itemData = new FirstTableData();

                    itemData.setId(cursor.getInt(0));

                    itemData.setCol1(cursor.getString(1));
                    itemData.setCol2(cursor.getInt(2));
                    .....
                    .....

                    firstTableDataList.add(itemData);
                } while (cursor.moveToNext());
            }
        } finally {

            db.close();
        }

        Collections.sort(itemDataList);
        return itemDataList;
    }

    public int  addFirstTableData(FirstTableData data) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(COL1, data.getCol1());
        values.put(COL2, data.getCol2());
        .....
        .....
        long x=db.insert(FIRST_TABLE_NAME, null, values);
        db.close();
        return (int)x;
    }

    public void updateItemDetailData(FirstTableData data) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(COL1, data.getCol1());
        values.put(COL2, data.getCol2());
        values.put(COL3, data.getCol3());
        .....
        .....


        db.update(FIRST_TABLE_NAME, values, COL_ID + "=" + data.getId(),    null);
        db.close();
    }

}

P.S : *Data class are POJO data class representing the corresponding table. Since you said you are not totally new to these, I have not provided any helper comments as most of the method names are self explanatory. Hope it helps you to get started.

PS:*Data类是代表对应表的POJO数据类。由于您说您对这些并不完全陌生,因此我没有提供任何帮助注释,因为大多数方法名称都是不言自明的。希望它可以帮助您入门。

回答by Paresh Mayani

To creating a database for Android application, there are 2 ways:

要为 Android 应用程序创建数据库,有两种方法:

  1. Create database and tables using Code
  2. Use existing database
  1. 使用代码创建数据库和表
  2. 使用现有数据库

1) Create database and tables using Code

1)使用代码创建数据库和表

In this scenario, you have to write a class and code to create database and tables for it. You have to use different classes and interfaces like SQLiteOpenHelper, SQLiteDatabase, etc. Check answer posted by Jimmy above.

在这种情况下,您必须编写一个类和代码来为其创建数据库和表。您必须使用不同的类和接口,如 SQLiteOpenHelper、SQLiteDatabase 等。检查上面 Jimmy 发布的答案。

2) Use existing database

2) 使用现有数据库

In this scenario, you can use your existing sqlite database inside your android application. You have to place database file inside assetsfolder and write a code to copy that existing database on to either internal or external storage.

在这种情况下,您可以在 android 应用程序中使用现有的 sqlite 数据库。您必须将数据库文件放在assets文件夹中并编写代码将该现有数据库复制到内部或外部存储。

Regarding best scenario, I would say it's depend on the application functionality and nature, if your database is small then you should go with 1st scenario and if your database is large with many tables then you should go with 2nd scenario because you would be creating database using any GUI based SQLite browser and which would help you to make less mistakes. (When I say less mistakes using GUI, believe me there are chances of creating tables by code).

关于最佳方案,我会说这取决于应用程序的功能和性质,如果您的数据库很小,那么您应该使用第一种方案,如果您的数据库很大并且有很多表,那么您应该使用第二种方案,因为您将创建数据库使用任何基于 GUI 的 SQLite 浏览器,这将帮助您减少错误。(当我使用 GUI 减少错误时,相信我有机会通过代码创建表)。

How to show values from the database on screen?

如何在屏幕上显示数据库中的值?

For that you have to write a SQL query which gives you Cursorin return which is a set of resultant data, so you have to iterate through the cursor data and prepare a set of data in terms of ArrayList or Array or HashMap.

为此,您必须编写一个 SQL 查询,该查询Cursor返回一组结果数据,因此您必须遍历游标数据并根据 ArrayList 或 Array 或 HashMap 准备一组数据。

You can display this set of data in ListViewor GridView.

您可以在ListView或 中显示这组数据GridView

P.S. I am not posting links to any tutorials or examples as there are plenty of information/examples available on web, so suggesting you to search around the given points.

PS 我不会发布任何教程或示例的链接,因为网络上有大量信息/示例,因此建议您围绕给定的点进行搜索。

回答by Andrei Catinean

A good way to start is to read about Storage Optionson the official Android documentation website: http://developer.android.com/guide/topics/data/data-storage.html

一个好的开始方法是Storage Options在官方 Android 文档网站上阅读:http: //developer.android.com/guide/topics/data/data-storage.html