SQLiteOpenHelper类实例-英文生词本

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
    android:orientation="vertical">


    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        
        <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        
        <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="生词"/>
        <EditText android:id="@+id/add_word"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"/>
  
    </LinearLayout>
    
        <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
       
        <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="介绍"/>
        <EditText android:id="@+id/add_detail"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"/>
        
    </LinearLayout>
        
        <Button android:id="@+id/add_but"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="添加生词"/>
        
    </LinearLayout>
    
    <EditText android:id="@+id/sear_word"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <Button  android:id="@+id/serach_but" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="查找生词"/>
    
    <TextView android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


</LinearLayout>

MyDataBaseHelper.java

package com.example.wordbooktest;


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


public class MyDataBaseHelper extends SQLiteOpenHelper{


final String CREATE_TABLE_SQL="create table dict(" +
"word_id integer primary key autoincrement," +
"word varchar(50)," +
"detait varchar(50))";



//name代表数据库的名称
public MyDataBaseHelper(Context context, String name,CursorFactory factory, int version) {
super(context, name, factory, version);
}


@Override
public void onCreate(SQLiteDatabase db) {
//第一次使用数据库时候自动创建表
db.execSQL(CREATE_TABLE_SQL);
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("升级数据库版本,旧版本:"+oldVersion+"新版本:"+newVersion);
}


}

MainActivity.java

package com.example.wordbooktest;


import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {


MyDataBaseHelper dbHelper;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//创建数据库DataBseHelper
dbHelper=new MyDataBaseHelper(MainActivity.this, "hanqing.db3", null, 1);

Button addBut=(Button) super.findViewById(R.id.add_but);
Button searchBut=(Button) super.findViewById(R.id.serach_but);

final EditText inputWord=(EditText) super.findViewById(R.id.add_word);
final EditText inputDetail=(EditText) super.findViewById(R.id.add_detail);

final TextView searchResult=(TextView) super.findViewById(R.id.result);


//获取用户查询的时候输入的关键词EditText
final EditText inputKey=(EditText) super.findViewById(R.id.sear_word);

addBut.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

//获取用户输入的生词和生词介绍
String word=inputWord.getText().toString();
String detail=inputDetail.getText().toString();

//插入生词记录
insertData(dbHelper.getReadableDatabase(),word,detail);
//显示添加成功
Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_LONG).show();
}
});



//当用户点击查询的时候
searchBut.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
//获取用户输入的查询的关键词
String key=inputKey.getText().toString();
//执行查询操作
Cursor cursor=dbHelper.getReadableDatabase().rawQuery("select * from dict where word like ? or detait like ?", new String[]{"%"+key+"%","%"+key+"%"});
//遍历cursor结果集
while(cursor.moveToNext()){
searchResult.setText("查询情况为:"+cursor.getString(1)+cursor.getString(2));
}

}
});

}



//向数据库当中插入数据的方法

public void insertData(SQLiteDatabase db,String word,String detail){

db.execSQL("insert into dict values(null,?,?)",new String[]{word,detail});
}




@Override
protected void onDestroy() {

super.onDestroy();

//退出程序时候关闭MyDatabaseHelper里的SQLiteDatabase
if(dbHelper!=null){
dbHelper.close();
}

}

}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要定义一个数据模型来表示生词本的单词和解释,如下所示: ```kotlin data class Word(val id: Long = -1, val word: String, val meaning: String) ``` 接下来,我们需要创建一个来管理SQLite数据库和表格的创建,更新和查询。这个应该继承自SQLiteOpenHelper,如下所示: ```kotlin class WordDatabaseHelper( context: Context, name: String? = null, factory: SQLiteDatabase.CursorFactory? = null, version: Int = 1 ) : SQLiteOpenHelper(context, name, factory, version) { companion object { private const val DATABASE_NAME = "word.db" private const val DATABASE_VERSION = 1 const val TABLE_NAME = "words" const val ID = "_id" const val WORD = "word" const val MEANING = "meaning" } override fun onCreate(db: SQLiteDatabase?) { val createTableSql = """ CREATE TABLE $TABLE_NAME ( $ID INTEGER PRIMARY KEY AUTOINCREMENT, $WORD TEXT NOT NULL, $MEANING TEXT NOT NULL ) """.trimIndent() db?.execSQL(createTableSql) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { val dropTableSql = "DROP TABLE IF EXISTS $TABLE_NAME" db?.execSQL(dropTableSql) onCreate(db) } } ``` 在这个中,我们定义了数据库的名称和版本,以及表格的名称和列名。在onCreate()方法中,我们创建了一个名为words的表格,并定义了三个列:_id,word和meaning。在onUpgrade()方法中,我们删除了旧表格并重新创建。 接下来,我们可以创建一个单例来管理数据库的操作,如下所示: ```kotlin object WordDatabaseManager { private lateinit var dbHelper: WordDatabaseHelper private lateinit var db: SQLiteDatabase fun init(context: Context) { dbHelper = WordDatabaseHelper(context, WordDatabaseHelper.DATABASE_NAME, null, WordDatabaseHelper.DATABASE_VERSION) db = dbHelper.writableDatabase } fun insert(word: Word): Boolean { val contentValues = ContentValues().apply { put(WordDatabaseHelper.WORD, word.word) put(WordDatabaseHelper.MEANING, word.meaning) } val result = db.insert(WordDatabaseHelper.TABLE_NAME, null, contentValues) return result != -1L } fun queryAll(): List<Word> { val cursor = db.query( WordDatabaseHelper.TABLE_NAME, arrayOf(WordDatabaseHelper.ID, WordDatabaseHelper.WORD, WordDatabaseHelper.MEANING), null, null, null, null, null ) val wordList = mutableListOf<Word>() while (cursor.moveToNext()) { val id = cursor.getLong(cursor.getColumnIndex(WordDatabaseHelper.ID)) val word = cursor.getString(cursor.getColumnIndex(WordDatabaseHelper.WORD)) val meaning = cursor.getString(cursor.getColumnIndex(WordDatabaseHelper.MEANING)) wordList.add(Word(id, word, meaning)) } cursor.close() return wordList } fun delete(id: Long): Boolean { val result = db.delete(WordDatabaseHelper.TABLE_NAME, "${WordDatabaseHelper.ID} = ?", arrayOf(id.toString())) return result > 0 } } ``` 在这个中,我们使用WordDatabaseHelper创建了一个数据库,并定义了三个常见的操作:插入,查询和删除。在insert()方法中,我们创建了一个ContentValues对象并将单词和解释添加到其中,然后使用insert()方法将其插入到数据库中。在queryAll()方法中,我们使用query()方法查询所有单词并返回它们的列表。在delete()方法中,我们使用delete()方法根据_id删除一个单词。 现在我们可以在Activity中使用这个,如下所示: ```kotlin class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) WordDatabaseManager.init(this) binding.btnAdd.setOnClickListener { val word = binding.etWord.text.toString() val meaning = binding.etMeaning.text.toString() if (word.isNotEmpty() && meaning.isNotEmpty()) { val result = WordDatabaseManager.insert(Word(word = word, meaning = meaning)) if (result) { Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show() binding.etWord.setText("") binding.etMeaning.setText("") } else { Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "请输入单词和解释", Toast.LENGTH_SHORT).show() } } binding.btnQuery.setOnClickListener { val words = WordDatabaseManager.queryAll() val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, words) binding.lvWords.adapter = adapter } binding.lvWords.setOnItemClickListener { _, _, position, _ -> val word = binding.lvWords.adapter.getItem(position) as Word val dialog = AlertDialog.Builder(this) .setTitle("删除单词") .setMessage("确定要删除单词${word.word}吗?") .setPositiveButton("确定") { _, _ -> val result = WordDatabaseManager.delete(word.id) if (result) { Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show() binding.btnQuery.performClick() } else { Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show() } } .setNegativeButton("取消", null) .create() dialog.show() } } } ``` 在这个Activity中,我们使用WordDatabaseManager来执行添加,查询和删除操作,并使用ListView显示所有单词。当用户点击一个单词时,我们会显示一个对话框询问用户是否要删除该单词。 现在,我们已经成功地创建了一个共享生词本应用程序,并使用SQLite数据库和SQLiteOpenHelper实现了数据存储和管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值