- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我找到了一个 dbhelper
类,它将我之前创建的数据库复制到 DB_PATH = "/data/data/"+ context.getPackageName() + "/"+ "databases_name/"
通过这个对象,我可以很容易地从我复制的数据库中读取数据。但是,我不知道如何从该数据库中插入和删除数据。
这是我完整的 dbhelper 对象..
public class DatabaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
String DB_PATH = null;
private static String DB_NAME = "ContactInfo";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
// return cursor
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy) {
return myDataBase.query(table, columns, selection, selectionArgs,
groupBy, having, orderBy);
}
public Cursor rawQuery(String query) {
// TODO Auto-generated method stub
return myDataBase.rawQuery(query, null);
}
}
我在我的 Activity 类中创建了这样的对象:
DatabaseHelper myDbHelper = new DatabaseHelper(MainActivity.this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
myDbHelper.close();
我可以通过在游标上运行查询来读取数据 c=myDbhelper.rawquery(query);
什么是插入和删除?如何使用此对象进行插入和删除?
最佳答案
您可以使用以下示例代码在数据库中插入值:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Contact.java
public class Contact {
//private variables
int _id;
String _name;
String _phone_number;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Contact(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
关于android - 使用我的 DBhelper 类插入和删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375184/
我正在开发一个简单的注册登录系统。在每个类中,每个 DbHelper 事件都有许多相同的错误。错误是 DBHelper 无法解析为变量。我的资源文件没有错误。我在这里发布类代码之一 这是我的代码 pa
我有以下情况,并且对 dbhelper 的实例方法或静态方法感到困惑? 我们有一个 dbhelper 类,顾名思义,它可以帮助其他类使用 MySql 数据库。 db helper 类将由 2 个独立模
public void update(View v){String amount1 = ct2.getText().toString(); //amount String barcode1
我在这段代码上得到了一个空指针...所以迷失了。 我有一个名为 DbAdapter 的数据库辅助类。 public class DbAdapter { private final Context mC
我找到了一个 dbhelper 类,它将我之前创建的数据库复制到 DB_PATH = "/data/data/"+ context.getPackageName() + "/"+ "databases
当我尝试在手机上调试应用程序时,就会发生此错误...... 我不知道问题出在哪里? 错误是:MY LOGCAT WINDOW My DatabaseHelper class package com.e
我想使用 ORMLite,但我不喜欢为每个 Activity 管理 1 个数据库助手。在整个应用程序生命周期中拥有一个不是更好吗?直到现在我一直在使用 greendao,它没有这个问题。 我想实现它,
我的 android 应用程序中有一个 SQLite 数据库,但不幸的是,使用新的虚拟机 ART 它停止工作。 我在 DbHelper 类中遇到错误,特别是当我打开数据库以写入/读取它时。 我需要帮助
我在重新安装后第一次运行我的应用程序时遇到此错误: android.database.sqlite.SQLiteException: 没有这样的表 (当我的应用试图从数据库中读取时会发生此错误) 由于
这个问题在这里已经有了答案: Select random row from a sqlite table (7 个答案) 关闭 8 年前。 我目前正在 Android 上开发一个问答游戏,我正在尝试
我的数据库有问题。应用程序发送用户编写的链接并作为响应获得链接的简短形式(工作正常)。在我的数据库中,我需要放置两个版本的链接 - 完整版本和简短版本,这里我们遇到了问题。我得到这样的错误: java
当我尝试在从 SQLiteOpenHelper 扩展的 DbHelper 类的 onCreate 方法中插入记录时,会出现此错误。 我发现了一些类似的主题,例如: Android getDatabas
我有一个扩展 SQLiteOpenHelper 的 DatabaseHelper 类,使用 DBHelper 执行数据提取的最佳做法是什么? 在我的 DatabaseHelper 类中,我有一个方法可
此FireBase通知创建了Notify(唯一id、标题、消息、Big_Image、link、post_id);数据保存数据库帮助器。适配器数据未显示。如何让DBHelper将适配器数据传递。DBhe
public class Main2Activity extends AppCompatActivity { private EditText editText1, editText2, ed
我是一名优秀的程序员,十分优秀!