-3

I would like to know how to store a single integer value to an sqlite database locally and then retrieve this value in a method in another class. PS: I don't want to use sharedpreference.

I have a boolean set to true which I have converted to an int using;

 public class MainActivity extends Activity{
      boolean booleanValue = true
      public static int value= (booleanValue == true)? 1:0;

    }

In Class 2

  public int retrieveValue(){
   //SQlite function to retrieve integer value
   int valueInDatabase = value;
   return valueInDatabase;
  }
Kingsley Onwus
  • 263
  • 1
  • 8

1 Answers1

1

The database is not a solution for your case. If you do not want to use shared preference then use the file.

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

How to use it in your code.

In your main activity.

writeToFile(this, YOUR_FILE_NAME, yourInterger.toString())

Then in your second activity

val fileContent = readFromFile(this, YOUR_FILE_NAME)
var yourInterger = if (fileContent.isEmpty()) {
    yourDefaultValue
}else{
    fileContent.toInt()
}

But if you want the only database then, Official sitel will help you

// 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) 
Jasurbek
  • 2,946
  • 3
  • 20
  • 37