fun save(inputText: String) {try {val output = openFileOutput("data", Context.MODE_PRIVATE)val writer = BufferWriter(OutputStreamWriter(output))writer.use {it.write(inputText)}} catch (e: IOException) {e.printStackTrace()}
}
class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)}override fun onDestroy() {super.onDestroy()val inputText = editText.text.toString()save(inputText)}private fun save(inputText: String) {try {val output = openFileOutput("data", Context.MODE_PRIVATE)val writer = BufferedWriter(OutputStreamWriter(output))writer.use {it.write(inputText)}} catch (e: IOException) {e.stackTrace}}
}
private fun load(): String {val content = StringBuilder()try {val input = openFileInput("data")val reader = BufferedReader(InputStreamReader(input))reader.use {reader.forEachLine {content.append(it)}}} catch (e: IOException) {e.stackTrace}return content.toString()}
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val inputText = load()if (inputText.isNotEmpty()) {//设置editText的内容为我们从文件中读取出来的内容editText.setText(inputText)//将光标移动到editText的末尾位置editText.setSelection(inputText.length)//弹出一个提示Toast.makeText(this, "succeeded", Toast.LENGTH_SHORT).show()}
}
class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)saveButton.setOnClickListener {val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()editor.putString("name", "Tom")editor.putInt("age", 18)editor.putBoolean("married", false)editor.apply()}}
}
//如果remember_password对应的是true说明用户之前记住了密码,就可以使用存储的密码来填充输入框
if (isRemember) {//将账号和密码都取出之后填充到输入框当中val account = prefs.getString("account", "")val password = prefs.getString("password", "")accountEdit.setText(account)passwordEdit.setText(password)//将复选框设置为选中rememberPass.isChecked = true
}
login.setOnClickListener {//先从Edit当中获取账户名和密码val account = accountEdit.text.toString()val password = passwordEdit.text.toString()//验证账户名和密码的逻辑if (account == "admin" && password == "123456") {//如果账号和密码都没有问题,那么就跳转到MainActivity
// val intent = Intent(this, MainActivity::class.java)
// startActivity(intent)
// finish()//先获取一个editor对象val edit = prefs.edit()//说明账号和密码都没有问题,现在我们要根据用户是否选择复选框来决定将用户的账号和密码添加到SharedPreferences进行保存if (rememberPass.isChecked) {//如果复选框被选中,那么我们就将用户的信息进行保存//保存账号edit.putString("account", account)//保存密码edit.putString("password", password)//保存是否基础密码这个状态edit.putBoolean("remember_password", true)//提交保存信息edit.apply()} else {//说明用户这一次没有选择记住密码,那么我们调用clear()方法清空SharedPreferences文件当中的信息edit.clear()}val intent = Intent(this, MainActivity::class.java)startActivity(intent)finish()} else {//使用Toast提示一段账号或者密码错误的文本Toast.makeText(this, "account or password is invalid", Toast.LENGTH_SHORT).show()}}
class MyDatabaseHelper(val context: Context, val name: String, val version: Int) :SQLiteOpenHelper(context, name, null, version) {//创建Book表的SQL语句private val createBookSQL = "create table Book (" +"id integer primary key autoincrement," +"author text," +"price integer," +"pages integer," +"name text)"override fun onCreate(db: SQLiteDatabase) {//调用execSQL创建表db.execSQL(createBookSQL)Toast.makeText(context, "Create succeeded", Toast.LENGTH_SHORT).show()}override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {TODO("Not yet implemented")}
}
class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//创建一个MyDatabaseHelper的实例val myDatabaseHelper = MyDatabaseHelper(this, "BookStore.db", 1)createDatabase.setOnClickListener {myDatabaseHelper.writableDatabase}}
}
addData.setOnClickListener {val db = myDatabaseHelper.writableDatabaseval values1 = ContentValues().apply {//开始组装第一条数据put("name", "The Da Vinci Code")put("author", "Dan Brown")put("pages", 454)put("price", 19.67)}//插入第一条数据db.insert("Book", null, values1)val values2 = ContentValues().apply {//开始组装第二条数据put("name", "The Lost Symbol")put("author", "Dan Brown")put("pages", 404)put("price", 10.67)}//插入第二条数据db.insert("Book", null, values2)val values3 = ContentValues().apply {//开始组装第三条数据put("category_name", "文学")put("category_code", 10)}db.insert("Category", null, values3)
}
upDate.setOnClickListener {val db = myDatabaseHelper.writableDatabaseval values = ContentValues()values.put("price", 10.01)db.update("Book", values, "name = ?", arrayOf("The Da Vinci Code"))
}
deleteData.setOnClickListener {val db = myDatabaseHelper.writableDatabasedb.delete("Book", "pages > ?", arrayOf("450"))
}
queryData.setOnClickListener {val db = myDatabaseHelper.writableDatabase//查询所有的数据val cursor = db.query("Book", null, null, null, null, null, null)//将数据的指针移动到第一行的位置if (cursor.moveToFirst()) {do {//遍历Cursor对象,取出数据并打印//利用getColumnIndex()方法传入字段名获得该字段的下标,然后将这个下标传入对应的取值方法取出相应的值val name = cursor.getString(cursor.getColumnIndex("name"))val author = cursor.getString(cursor.getColumnIndex("author"))val pager = cursor.getInt(cursor.getColumnIndex("pages"))val price = cursor.getDouble(cursor.getColumnIndex("price"))Log.d("MainActivity", "book name is $name")Log.d("MainActivity", "book author is $author")Log.d("MainActivity", "book name is $pager")Log.d("MainActivity", "book name is $price")} while (cursor.moveToNext())}cursor.close()
}
//添加数据
db.execSQL("insert into Book (name, author, pages, price) values (?, ?, ?, ?)", arrayOf("The Da Vinci Code", "Dan Brown", "444", "19.78"))
//更新数据
db.execSQL("update Book set price = ? where name = ?", arrayOf("10.99", "The Da Vinci Code"))
//删除数据
db.execSQL("delete from Book where pages > ?", arrayOf("500"))
//查询数据
val cursor = db.rawQuery("selete * from Book", null)
replaceDate.setOnClickListener {//先获得一个SQLiteDatabase对象val db = myDatabaseHelper.writableDatabase//下面我们就要利用这个SQLiteDatabase对象来进行两个数据操作了,所以在进行数据操作之前我们就应该开启事务了db.beginTransaction() //开启事务try {db.delete("Book", null, null)//在这个地方为了演示事务的作用我们在这里手动抛出一个空指针异常if (true) {//手动抛出一个异常让事务执行失败throw NullPointerException()}val values = ContentValues().apply {put("name", " Game")put("author", "drl")put("pages", "10")put("price", 5)}db.insert("Book", null, values)db.setTransactionSuccessful()//事务执行成功} catch (e: Exception) {e.printStackTrace()} finally {db.endTransaction() //结束事务}
}
class MyDatabaseHelper(val context: Context, val name: String, val version: Int) :SQLiteOpenHelper(context, name, null, version) {//创建Book表的SQL语句private val createBookSQL = "create table Book (" +"id integer primary key autoincrement," +"author text," +"price real," +"pages integer," +"name text)"override fun onCreate(db: SQLiteDatabase) {//执行创建Book表的SQLdb.execSQL(createBookSQL)}override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {}
}
class MyDatabaseHelper(val context: Context, val name: String, val version: Int) :SQLiteOpenHelper(context, name, null, version) {//创建Book表的SQL语句private val createBookSQL = "create table Book (" +"id integer primary key autoincrement," +"author text," +"price real," +"pages integer," +"name text)"//创建Category表的SQL语句private val createCategorySQL = "create table Category (" +"id integer primary key autoincrement," +"category_name text," +"category_code integer)"override fun onCreate(db: SQLiteDatabase) {//执行创建Book表的SQLdb.execSQL(createBookSQL)//创建Category表的SQLdb.execSQL(createCategorySQL)}override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {//当我们旧数据库的版本是<=1的时候,我们再做数据覆盖的时候只执行createCategorySQLif(oldVersion <= 1) {db.execSQL(createCategorySQL)}}
}
class MyDatabaseHelper(val context: Context, val name: String, val version: Int) :SQLiteOpenHelper(context, name, null, version) {//创建Book表的SQL语句private val createBookSQL = "create table Book (" +"id integer primary key autoincrement," +"author text," +"price real," +"pages integer," +"name text," + "category_id integer)"//创建Category表的SQL语句private val createCategorySQL = "create table Category (" +"id integer primary key autoincrement," +"category_name text," +"category_code integer)"override fun onCreate(db: SQLiteDatabase) {//执行创建Book表的SQLdb.execSQL(createBookSQL)//创建Category表的SQLdb.execSQL(createCategorySQL)}override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {//当我们旧数据库的版本是<=1的时候,我们再做数据覆盖的时候只执行createCategorySQLif(oldVersion <= 1) {db.execSQL(createCategorySQL)}if(oldVersion <= 2) {db.execSQL("alter table Book add column category_id integer")}}
}
上一篇: 我来教教大家“广西老友玩到底有挂吗”!(确实真的有挂)-知乎
下一篇:刚刚,东方甄选道歉!