Android 利用文件,SharedPreferences 數據庫保存數據增刪改查————第一行代碼

展示

1.文件保存

在這裏插入圖片描述  在這裏插入圖片描述

2.SharedPreferences

在這裏插入圖片描述在這裏插入圖片描述

3.數據庫保存

在這裏插入圖片描述  在這裏插入圖片描述在這裏插入圖片描述

例子下載

https://download.csdn.net/download/ljp345775/12489221

代碼實現

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")
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章