简体   繁体   English

如何永久保存在SQLitedatabase中

[英]How to save in SQLitedatabase permanently

I have created a SQLitedatabase and want to store data. 我创建了一个SQLitedatabase,并希望存储数据。 But the data is deleted on each start of the app again, because the "create table" methods are implemented in in the OnCreate-Method of the database. 但是,由于在数据库的OnCreate-Method中实现了“ create table”方法,因此在应用程序的每次启动时都会再次删除数据。

  1. How can i prevent that the OnCreate Method is called on each start of the app. 如何防止在每次启动应用程序时调用OnCreate方法。
  2. Where does the creation of the database object fits best? 数据库对象的创建最适合哪里?

OnCreate of the database: 数据库的OnCreate:

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

Th initNinjas method contains some Insert SQLs which create the sample data. initNinjas方法包含一些创建示例数据的插入SQL。 I already tried to make an if-decision in the constructor to ask whether there is already a database but this doesnt work. 我已经尝试在构造函数中做出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;
    }
}

The constructor of the MasterActivity creates the database object and starts with beginning of the app. MasterActivity的构造函数创建数据库对象,并从应用程序的开头开始。 As following: 如下:

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


    dbHelper = new DatabaseHelper(this);}

The DatabaseHelper Constructor: DatabaseHelper构造函数:

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

Here is my SQLiteAdapter (DBHelper)Class: 这是我的SQLiteAdapter (DBHelper)类:

Using this this db will be created only once. 使用此数据库将仅创建一次。 You can call this from any method and activity. 您可以从任何方法和活动中调用它。 Make changes according to your requirement. 根据您的要求进行更改。

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

     }

   }
}

If this: 如果这:

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

is your constructor, 是你的构造函数
it creates a database with name the value of TABLE_NAME which is I suppose the name of the table you want to create. 它创建一个名称为TABLE_NAME的数据库,我想是您要创建的表的名称。
So change TABLE_NAME with the database name. 因此,将TABLE_NAME更改为数据库名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM