Unable to Start Acticity Component Info - android

In my project, I am trying to save data into a sqllite database and trying to read those data once its saved. I am able to write all the data in the database but while trying to retrieve the data then I am getting unable to start activity: Kotlin.kotlinNullPointerException error. I followed all the recommendation by android suggestion but still getting this error. Any help is appreciated.
Language Used
Kotlin
Error
Unable to start activity ComponentInfo: kotlin.KotlinNullPointerException
Code
noteList = dbHandler!!.readNotes()
Read Code
fun readNotes(): ArrayList<Notes>
{
var db=readableDatabase
val list:ArrayList<Notes> = ArrayList()
var selectAll = "SELECT * FROM " + TABLE_NAME
var cursor: Cursor = db.rawQuery(selectAll, null)
if(cursor.moveToFirst())
{
do {
var note = Notes()
note.id=cursor.getInt(cursor.getColumnIndex(KEY_ID))
note.noteName = cursor.getString(cursor.getColumnIndex(KEY_NOTE_NAME))
list.add(note)
}
while (cursor.moveToNext())
}
return list
}
Steps Checked
1) Activity is presented in Android Manifest File
2) Data's are stored in the database
3) Text Views castings are done properly

The dbHandler might be null. using !! asserts that the object is not null. Check if you have initialised the dbHandler or post the whole code

Related

Retrieving a shared preferences item from another activity. Android Studio, Kotlin, API 29

I am a complete Novice writing my first app.
I created an Activity called SettingsInput.kt and it works fine saving settings as sharedPreferences, displaying them on press of buttons.
Now I want to use one of the settings as part of a calculation in a function to cull old data from a couple of tables in the database The function is in the databaseHandler class.
I get an error "Unresolved reference: getSharedPreferences" None of the methods I have tried have helped so far. Can anyone help, bearing in mind that the target API level is API 29?
var sharedPrefFile = "greenbandbasicpreference"
val sharedPreferences:SharedPreferences = getSharedPreferences(sharedPrefFile,Context.MODE_PRIVATE)//doesnt recognise getSharedPreferences
fun cullData(){
var noow = ZonedDateTime.now(Clock.systemUTC())
var noowSecs:Long = noow.toEpochSecond()
var noowMins:Long = (noowSecs)/60
//var bolusLifeMins:Long = 220// this has to come from a database or store of "preferences"
//var bolusLifeMins:Long = sharedPreferences.getLong("insLife_key",0)
val bolusLifeMins = getSharedPreferences("greenbandbasicpreference",Context.MODE_PRIVATE)
var minTimeMins = noowMins - bolusLifeMins - 2*(24*60)
val db = this.writableDatabase
db.delete(
"BolusTable",
"btime <"+ minTimeMins ,
null
)
db.delete(//this is a part of the function for cull CarbsTable
"CarbsTable",
"carbTime <"+ minTimeMins ,
null
)
db.close()
}
The method getSharedPreferences is a method from Context class, so you will need a context to request it, like:
context.getSharedPreferences(sharedPrefFile,Context.MODE_PRIVATE)
https://developer.android.com/reference/android/content/Context#getSharedPreferences(java.lang.String,%20int)

Android Room database - when all rows are loaded

I am trying to use Android Room described there: https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#13
source codes: https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin/app/src/main/java/com/example/android/roomwordssample
I would like to choose one record when all records will be loaded.
I tried in the end of "onCreate(savedInstanceState: Bundle?)" function add this code:
var rnd : Random = Random(System.currentTimeMillis())
var words : List<Word>? = wordViewModel.allWords.value
// now wordViewModel.allWords.value is NULL
if (words != null) {
var textViewRandomWord: TextView = findViewById<TextView>(R.id.textView)
textViewRandomWord.text = words.get(rnd.nextInt(words.size)).word
}
But in this time is variable wordViewModel.allWords.value is still null.
Can you help me, where to add this code (or any similar code) to get random record from all saved records and show it when activity is created?
Thank you.
wordViewModel.allWords is [LiveData] : https://developer.android.com/topic/libraries/architecture/livedata object, so its good to get value by observer
wordViewModel.allWords.observe(this, Observer { words ->
// Do your implementation
})

Android Kotlin Executing SQLite query in MainActivity

I'm trying to figure out how to execute a SQL query from my MainActivity. I'm currently using a large portion of this example. Upon clicking my Acknowledge button, it finds the selected rows, gets the jsonID of said row, then I'm wanting to update a value in my SQLite table of those rows.
So my question is, how do I execute my "jsonQuery" string, to my SQLite database upon clicking my Acknowledge button?
Here's the code I have in my MainActivity:
acknowledge.setOnClickListener {
var jsonData_text: String = ""
for (i in 0 until JSONParser.MrAdapter.public_modelArrayList!!.size) {
if (JSONParser.MrAdapter.public_modelArrayList!!.get(i).getSelecteds()) {
jsonData_text = jsonData_text + JSONParser.MrAdapter.public_modelArrayList!!.get(i).getJSONID() + ","
}
}
val jsonSQLQuery = jsonData_text.dropLast(1)
val jsonQuery = "update Notes set acknowledged = 1 WHERE jsonID in ("+jsonSQLQuery+")"
Log.d("logged_json", jsonQuery)
}
Thanks for any help!

Unable to fetch the list column of AWS DynamoDB in Android Kotlin

I am developing an Android application using Kotlin and AWS DynamoDB. I am new to both technologies. What I am doing now is I am trying to scan data from a table of DynamoDB. I know how to scan it. But the problem is that one of the column has List data type.
I have a table called item with the following columns.
Note in particular the Images field.
In Kotlin Android, I scan the table like this.
val dynamoDBClient = AmazonDynamoDBClient(AWSMobileClient.getInstance().credentialsProvider)
val fetchedItems: ArrayList<Any> = ArrayList();
val scanRequest = ScanRequest().withTableName(MainApplication.DB_TABLE_ITEMS);
scanRequest.exclusiveStartKey = lastEvaluatedKey
val scanResult = dynamoDBClient.scan(scanRequest)
scanResult.items.forEach { item ->
Log.i("ITEM_NAME", item.get("Name")?.s)
val viewItem = ItemDO()
viewItem.id = item.get("Id")?.s
viewItem.description = item.get("Description")?.s
viewItem.name = item.get("Name")?.s
viewItem.userId = item.get("UserId")?.s
viewItem.images = item.get("Images")?.ns
fetchedItems.add(viewItem)
Log.i("IMAGES_COUNT", item.get("Images")?.ns?.size.toString())
}
But this
item.get("Images")?.ns
always return null even if the data exists in the column as in the screenshot below.
Why my code is not fetching the list data type but others?
The code looks good and should be returning data for all the attributes irrespective of their type. I have equivalent piece of code in java that works as expected. Can you try inspecting the value returned by item.get("Images") before making the null-safe call. Type of the value returned by item.get("Images") is AttributeValue and so there is a possibility that the value gets lost in the course of implicit type conversion.

How to check if record exists or not using Anko?

I am learning to fetching data from sqlite using anko. I can print the data successfully (if the record exist) but my application always crash when the data doesn't exist.
the error says:
parseSingle accepts only cursors with a single entry
I know exactly the meaning of error, I just dont know how to solve it.
here is the code for query:
fun getUserByUid(uid: Int): UserModel
{
val data = context.database.use {
val db = context.database.readableDatabase
val columns = UserModel.COLUMN_ID + "," + UserModel.COLUMN_NAME + "," + UserModel.COLUMN_API_KEY
val query = db.select(UserModel.TABLE_NAME, columns)
.whereArgs("(uid = {userId})",
"userId" to uid)
query.exec {
val rowParser = classParser<UserModel>()
parseSingle(rowParser) // this line that trigger error exception
}
}
return data
}
I tried to find count function in query or rowParser variable to check if the record exist or not but could not find it.
From the wiki page.
https://github.com/Kotlin/anko/wiki/Anko-SQLite#parsing-query-results
Parsing query results
So we have some Cursor, and how can we parse it into regular classes? Anko provides functions parseSingle, parseOpt and parseList to do it much more easily.
Method Description
parseSingle(rowParser): T Parse exactly one row
parseOpt(rowParser): T? Parse zero or one row
parseList(rowParser): List Parse zero or more rows
Note that parseSingle() and parseOpt() will throw an exception if the received Cursor contains more than one row.

Categories

Resources