如何永久保存在SQLitedatabase中

时间:2018-10-30 14:59:50

标签: java android sql database sqlite

我已经创建了一个SQLitedatabase,并且想要存储数据。但是,由于在数据库的OnCreate-Method中实现了“ create table”方法,因此在应用程序的每次启动时都会再次删除数据。

  1. 如何防止在每次启动应用程序时调用OnCreate方法。
  2. 在哪里最适合创建数据库对象?

数据库的OnCreate:

@Override
public void onCreate(SQLiteDatabase db) {
    //if (!dbNinjaExists(db)) {
        createTables(db);
        initNinjas(db);
    //}
}

initNinjas方法包含一些创建示例数据的插入SQL。我已经尝试在构造函数中做出if决策,以询问是否已经有一个数据库,但这不起作用。

private boolean dbNinjaExists(SQLiteDatabase db) {

    String query = "SELECT * FROM "+ TABLE_NAME;
    Cursor data = db.rawQuery(query,null);

    if(data.equals(null)){
        return false;
    }else{
        return true;
    }
}

MasterActivity的构造函数创建数据库对象,并从应用程序的开头开始。如下:

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    dbHelper = new DatabaseHelper(this);}

DatabaseHelper构造函数:

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

2 个答案:

答案 0 :(得分:0)

这是我的 SQLiteAdapter (DBHelper)类:

使用此数据库将仅创建一次。您可以从任何方法和活动中调用它。根据您的要求进行更改。

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

import java.util.ArrayList;

class SQLiteAdapter {

private static final String DB_NAME = "DATABASE";
private static final String KEY_TABLE = "KEY_TABLE";

private static final int DB_VERSION = 1;

private static final String KEY_ID = "_id";
private static final String KEYWORD = "Keyword";
private static final String COUNT = "COUNT";
private static final String CONTACT_NAMES = "CONTACT_NAMES";
private static final String CONTACT_NUMBERS = "CONTACT_NUMBERS";


//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
        "create table " + KEY_TABLE + " ("
                + KEY_ID + " integer primary key autoincrement, "
                + KEYWORD + " text, "
                + CONTACT_NAMES + " text, "
                + CONTACT_NUMBERS + " text, "
                + COUNT + " integer);";

private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;

private Context context;

SQLiteAdapter(Context c) {
    context = c;
}

private void openToRead() throws android.database.SQLException {
    sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
    sqLiteDatabase = sqLiteHelper.getReadableDatabase();

}

private void openToWrite() throws android.database.SQLException {
    sqLiteHelper = new SQLiteHelper(context, DB_NAME, null, DB_VERSION);
    sqLiteDatabase = sqLiteHelper.getWritableDatabase();

}

private void close() {
    sqLiteHelper.close();
}

boolean insert(SQLiteAdapter sqLiteAdapter, String keyword, String contact_names, String contact_numbers, int count) {

    sqLiteAdapter.openToWrite();
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEYWORD, keyword);
    contentValues.put(CONTACT_NAMES, contact_names);
    contentValues.put(CONTACT_NUMBERS, contact_numbers);
    contentValues.put(COUNT, count);
    sqLiteDatabase.insert(KEY_TABLE, null, contentValues);
    sqLiteAdapter.close();
    return true;
}

void deleteRow(SQLiteAdapter sqLiteAdapter, String id) {

    sqLiteAdapter.openToWrite();
    sqLiteDatabase.execSQL("delete from " + KEY_TABLE + " where _id='" + id + "'");
    sqLiteAdapter.close();


}

ArrayList<RecordModel> getAllRecords(SQLiteAdapter sqLiteAdapter) {

    sqLiteAdapter.openToRead();
    ArrayList<RecordModel> listItems = new ArrayList<>();

    String[] columns = new String[]{KEY_ID, KEYWORD, CONTACT_NAMES, CONTACT_NUMBERS, COUNT};
    Cursor cursor = sqLiteDatabase.query(KEY_TABLE, columns,
            null, null, null, null, null);

    if (cursor.moveToFirst()) {
        do {
            RecordModel recordModel = new RecordModel();
            recordModel.setCount(cursor.getInt(cursor.getColumnIndex(COUNT)));
            recordModel.setId(cursor.getString(cursor.getColumnIndex(KEY_ID)));
            recordModel.setKeyword(cursor.getString(cursor.getColumnIndex(KEYWORD)));
            recordModel.setContactNames(cursor.getString(cursor.getColumnIndex(CONTACT_NAMES)));
            recordModel.setContactNumbers(cursor.getString(cursor.getColumnIndex(CONTACT_NUMBERS)));
            listItems.add(recordModel);
        } while (cursor.moveToNext());
    }

    cursor.close();

    sqLiteAdapter.close();

    return listItems;
}


public class SQLiteHelper extends SQLiteOpenHelper {

    SQLiteHelper(Context context, String name,
                 CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(SCRIPT_CREATE_DATABASE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

     }

   }
}

答案 1 :(得分:0)

如果这样:

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

是您的构造函数,
它将创建一个名称为TABLE_NAME的数据库,我想这是您要创建的表的名称。
因此,将TABLE_NAME更改为数据库名称。