SQLite与本地数据库,是否可能?

时间:2018-03-09 16:18:14

标签: java android sqlite

我正在尝试创建一个应用。我刚刚开始使用Android进行开发。我读到SQLite是将数据保存在私有数据库中,并且有本地存储来保存文件中的内容。但问题是,我认为将数据保存在文件中,阅读所有内容然后向用户显示将在我的情况下有效(小应用程序)但无聊。有没有办法用SQLite创建数据库?我的意思是,我正在使用它,但它不起作用,每次我关闭应用程序,并在一段时间后再打开它所有的数据都消失了。好像是临时数据库,不稳定。我做错了什么或者没有办法,除了使用本地存储,因为我在互联网上没有任何数据库。

package com.example.daniel.sm;

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

import java.util.ArrayList;
import java.util.List;

/**
 * Created by daniel on 08/03/18.
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "SMdb";
    private static final String TABLE_NAME = "equipamentos";
    private static final String COL_1 = "id";
    private static final String COL_2 = "equipamento";
    private static final String COL_3 = "quantidade";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "+TABLE_NAME+" (" +
                COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT,"+
                COL_2+" TEXT,"+COL_3+" INTEGER NOT NULL DEFAULT 0);";
        sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(sqLiteDatabase);
    }

    public int addEquipment(String nome, int quantidade){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL_2,nome);
        values.put(COL_3,quantidade);
        int newlyId = (int) db.insert(TABLE_NAME,null,values);
        db.close();
        return newlyId;
    }

    public int updateEquipment(Equipamento equipamento){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL_2,equipamento.getNome());
        values.put(COL_3,equipamento.getQuantidade());

        return db.update(TABLE_NAME,values,COL_1+" =?",new String[]{String.valueOf(equipamento.getId())});
    }

    public void deleteEquipment(Equipamento equipamento){
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME,COL_1+" =?",new String[]{String.valueOf(equipamento.getId())});
        db.close();
    }

    public Equipamento getEquipment(int id){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.query(TABLE_NAME,new String[]{COL_1,COL_2,COL_3},COL_1+" =?",new String[]{String.valueOf(id)},null,null,null,null);
        if (cursor != null){
            cursor.moveToFirst();
        }
        return new Equipamento(cursor.getInt(0),cursor.getString(1),cursor.getInt(2));
    }

    public List<Equipamento> getAllEquipment(){
        List<Equipamento> listEquipamento = new ArrayList<>();
        String selectQuery = "SELECT * FROM "+TABLE_NAME;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery,null);
        if(cursor.moveToFirst()){
            do {
                Equipamento equipamento = new Equipamento();
                equipamento.setId(cursor.getInt(0));
                equipamento.setNome(cursor.getString(1));
                equipamento.setQuantidade(cursor.getInt(2));
                listEquipamento.add(equipamento);
            } while (cursor.moveToNext());
        }
        return  listEquipamento;
    }
}

1 个答案:

答案 0 :(得分:0)

SQLite是应用程序的本地数据库,它用于在多个应用程序启动之间保留数据。

所以在你的情况下,只使用SQLite,你不需要写/读文件

但是,不是直接使用SQLiteDatabase并写下您的所有请求,您可以使用 Room ,它是 SQLite 的抽象层,使用起来非常简单。你只需要一个实体,一个dao和一个数据库类。

您可以这样实现:

User.java

@Entity
public class User {
    @PrimaryKey
    private int id;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    // Getters and setters are ignored for brevity,
    // but they're required for Room to work.
}

UserDao.java

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Insert
    void insert(User user);

    @Update
    void update(User user);

    @Delete
    void delete(User user);

}

Database.java

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

最后在您的应用程序中,您可以通过这种方式实例化数据库:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "database-name").build();

有关房间数据库的更多信息,请查看Android指南:https://developer.android.com/training/data-storage/room/index.html