Android 利用文件,SharedPreferences 数据库保存数据增删改查————第一行代码

212 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

展示

1.文件保存

在这里插入图片描述  在这里插入图片描述

2.SharedPreferences

在这里插入图片描述在这里插入图片描述

3.数据库保存

在这里插入图片描述  在这里插入图片描述在这里插入图片描述

例子下载

download.csdn.net/download/lj…

代码实现

1.文件存储

  主要代码如下:

//保存到文件
btn_saveData.setOnClickListener {
    var str_data = edt_data.text.toString()
    if (str_data != null) {
        try {
            var output = openFileOutput("KotlinDemo5", Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            //use函数就是自动关闭最外层的流
            writer.use {
                it.write(str_data)
            }
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
//从文件中读取
btn_getdata.setOnClickListener {
    val input = openFileInput("KotlinDemo5")
    val reader = BufferedReader(InputStreamReader(input))
    val content = StringBuilder()
    reader.use {
        reader.forEachLine {
            content.append(it)
            content.append("\n")
        }
    }
    tv_data.setText(content.toString())
}
2.SharedPreferences

  主要代码如下:

//存储
btn_save.setOnClickListener {
    val user = edt_user.text.toString();
    val pwd = edt_pwd.text.toString();
    if (user != null && pwd != null) {
        var editor = getSharedPreferences("KotlinDemo5", Context.MODE_PRIVATE).edit()
        editor.putString("user", user)
        editor.putString("pwd", pwd)
        editor.apply()
    }

    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()

}
btn_getData.setOnClickListener {
    var sp = getSharedPreferences("KotlinDemo5", Context.MODE_PRIVATE)
    var user = sp.getString("user", "")
    var pwd = sp.getString("pwd", "")
    tv_user.setText("用户名:$user")
    tv_pwd.setText("密码:$pwd")
}
3.数据库
(1).创建数据库
 myDataHelper = MyDataHelper(this, DBNAME, 1)
 myDataHelper.writableDatabase
(2).增
/**
 * 向数据库中插入数据
 */
private fun insertBook() {
    db = myDataHelper.writableDatabase
    val name = edt_name.text.toString()
    val author = edt_author.text.toString()
    val pages = edt_pages.text.toString()
    val price = edt_price.text.toString()
    if (!name.isBlank() && !author.isBlank() && !pages.isBlank() && !price.isBlank()) {
        val cv1 = ContentValues().apply {
            put("name", name)
            put("author", author)
            put("pages", pages.toInt())
            put("price", price.toDouble())
        }
        val i = db.insert(BOOK, null, cv1)
        if (i > 0) {
            Toast.makeText(this, "数据保存成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "数据保存失败", Toast.LENGTH_SHORT).show()
        }
    } else {
        Toast.makeText(this, "请完善数据", Toast.LENGTH_SHORT).show()
    }
}
(3).删
db = myDataHelper.writableDatabase
val i = db.delete(BOOK, "id=?", arrayOf("" + book.id))
if (i > 0) {
    Toast.makeText(context, "数据删除成功", Toast.LENGTH_SHORT).show()
    queryBook()
} else {
    Toast.makeText(context, "数据删除失败", Toast.LENGTH_SHORT).show()
}
(4).改
/**
 * 修改数据
 */
private fun updateBook() {
    db = myDataHelper.writableDatabase
    val name = edt_name.text.toString()
    val author = edt_author.text.toString()
    val pages = edt_pages.text.toString()
    val price = edt_price.text.toString()
    if (name.isBlank()) {
        Toast.makeText(this, "请输入书名", Toast.LENGTH_SHORT).show()
    } else {
        val values = ContentValues()
        //作者
        if (!author.isBlank()) {
            values.put("author", author)
        }
        //页数
        if (!pages.isBlank()) {
            values.put("pages", pages.toInt())
        }
        //价格
        if (!price.isBlank()) {
            values.put("price", price.toDouble())
        }
        if (values.size() > 0) {
            val i = db.update(BOOK, values, "name = ?", arrayOf(name))
            Log.e("aaa", "i-->" + i)
            if (i > 0) {
                Toast.makeText(this, "数据修改成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "数据修改失败", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "请输入修改条件", Toast.LENGTH_SHORT).show()
        }

    }
}
(5).查
/**
 * 查询数据
 */
private fun queryBook() {
    db = myDataHelper.writableDatabase
    val cursor = db.query(BOOK, null, null, null, null, null, null, null)
//        val cursor = db.rawQuery("select * from book where name like '%$name%'", null)
    list.clear()
    if (cursor.moveToFirst()) {
        do {
            val name = cursor.getString(cursor.getColumnIndex("name"))
            val author = cursor.getString(cursor.getColumnIndex("author"))
            val pages = cursor.getInt(cursor.getColumnIndex("pages"))
            val price = cursor.getDouble(cursor.getColumnIndex("price"))
            val id = cursor.getInt(cursor.getColumnIndex("id"))
            list.add(Book(id, name, author, pages, price))
        } while (cursor.moveToNext())
    }
    if (bookAdapter != null) {
        bookAdapter!!.setList(list)
        bookAdapter!!.notifyDataSetChanged()
    } else {
        bookAdapter = BookAdapter(list)
        lv_data.adapter = bookAdapter
    }
}
(6).MyDataHelper
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast

class MyDataHelper(val context: Context, name: String, version: Int) :
    SQLiteOpenHelper(context, name, null, version) {

    private val createBook = "create table Book (" +
            "id integer primary key autoincrement," +
            "author text," +
            "price real," +
            "pages integer," +
            "name text)"

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(createBook)
        Toast.makeText(context, "数据库创建成功", Toast.LENGTH_SHORT).show()
    }

    override fun onUpgrade(db: SQLiteDatabase?, p1: Int, p2: Int) {
        TODO("Not yet implemented")
    }

}