Java 如何通过sqlite存储和检索单个整数值
我想知道如何在本地将单个整数值存储到sqlite数据库,然后在另一个类的方法中检索该值。 附言:我不想使用SharedReference 我有一个布尔值设置为true,我用它转换成intJava 如何通过sqlite存储和检索单个整数值,java,android,android-sqlite,local-database,Java,Android,Android Sqlite,Local Database,我想知道如何在本地将单个整数值存储到sqlite数据库,然后在另一个类的方法中检索该值。 附言:我不想使用SharedReference 我有一个布尔值设置为true,我用它转换成int public class MainActivity extends Activity{ boolean booleanValue = true public static int value= (booleanValue == true)? 1:0; } 在2班 pub
public class MainActivity extends Activity{
boolean booleanValue = true
public static int value= (booleanValue == true)? 1:0;
}
在2班
public int retrieveValue(){
//SQlite function to retrieve integer value
int valueInDatabase = value;
return valueInDatabase;
}
数据库不是您案例的解决方案。如果不想使用共享首选项,请使用该文件
fun readFromFile(context: Context, fileName: String): String {
return try {
FileInputStream(File(context.applicationContext.filesDir, fileName)).bufferedReader()
.use { it.readText() }
} catch (e: Exception) {
println("it is checking point of Error read file " + e.message)
""
}
}
fun writeToFile(context: Context, fileName: String, data: String = "") {
try {
FileOutputStream(File(context.applicationContext.filesDir, fileName)).use {
it.write(data.toByteArray())
}
} catch (e: FileNotFoundException) {
println("it is checking point of Error write file " + e.message)
}
}
如何在代码中使用它
在你的主要活动中
writeToFile(this, YOUR_FILE_NAME, yourInterger.toString())
然后在你的第二个活动中
val fileContent = readFromFile(this, YOUR_FILE_NAME)
var yourInterger = if (fileContent.isEmpty()) {
yourDefaultValue
}else{
fileContent.toInt()
}
但是如果你想要唯一的数据库,那么,它将帮助你
// Gets the data repository in write mode
val db = dbHelper.writableDatabase
// Create a new map of values, where column names are the keys
val values = ContentValues().apply {
put(FeedEntry.COLUMN_NAME_TITLE, title)
put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle)
}
// Insert the new row, returning the primary key value of the new row
val newRowId = db?.insert(FeedEntry.TABLE_NAME, null, values)