I've a table of Holidays, I'm trying to check if some specific one took any holidays before
This is my table construction:
db.execSQL("CREATE TABLE IF NOT EXISTS Holidays (HolidayID INTEGER PRIMARY KEY, Department TEXT NOT NULL, Profession TEXT NOT NULL, EmpName TEXT NOT NULL, DaysofHoliday TEXT NOT NULL, StartDay TEXT NOT NULL, StartMonth TEXT NOT NULL, StartYear TEXT NOT NULL, EndDay TEXT, EndMonth TEXT, EndYear TEXT, PresentedDay TEXT NOT NULL, PresentedMonth TEXT NOT NULL, PresentedYear TEXT NOT NULL, Engineer TEXT NOT NULL, ApproveDay TEXT NOT NULL, ApproveMonth TEXT NOT NULL, ApproveYear TEXT NOT NULL)")
My companion object:
companion object {
val DB_Name = "samalout.db"
val TABLE_HOL = "Holidays"
val COL_41 = "HolidayID"
val COL_42 = "Department"
val COL_43 = "Profession"
val COL_44 = "EmpName"
val COL_45 = "DaysofHoliday"
val COL_46 = "StartDay"
val COL_47 = "StartMonth"
val COL_48 = "StartYear"
val COL_49 = "EndDay"
val COL_410 = "EndMonth"
val COL_411 = "EndYear"
val COL_412 = "PresentedDay"
val COL_413 = "PresentedMonth"
val COL_414 = "PresentedYear"
val COL_415 = "Engineer"
val COL_416 = "ApproveDay"
val COL_417 = "ApproveMonth"
val COL_418 = "ApproveYear"
}
This my search function:
fun Game() {
var query1 = ""
var rv = ArrayList<String>()
val db = dbHelper.writableDatabase
query1 = "SELECT * FROM " + DBHelper.TABLE_HOL + " WHERE " + DBHelper.COL_44 + "='" + spin3.selectedItem.toString() + "'"
val c1 = db.rawQuery(query1, null)
while (c1.moveToNext()) {
rv.add(c1.getString(0))
textView13.text = rv.sum().toString()
}
}
Edit:
sum function can't b done to arraylist of strings, so I tried something else:
while (c1.moveToNext()) {
rv.add(c1.getString(0))
for (item in rv)
println(item)
}
but also it didn't get me result
I found the problem, It's the Column that I search .. I performed a select query on adb, it returned different columns .. for clarity: I assigned the following columns (HolidayID, Department, Profession, EmpName), when I made a select * from table Holidays; on adb it returned the following (HolidayID, EmpName, Department, Profession) .. I don't know what happened to reverse my initials but I changed search query in main activity to the second column of table and it worked for me.
Edit: It was the insertion statement, it's all my fault
fun insertDataHol(holid: Int, department: String, profession: String, empname: String, daysofholiday: String, startday: String, startmonth: String, startyear: String, endday: String, endmonth: String, endyear: String, presentedday: String, presentedmonth: String, presentedyear: String, engineer: String, approveday: String, approvemonth: String, approveyear: String) {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(COL_41, holid)
contentValues.put(COL_42, empname)
contentValues.put(COL_43, department)
contentValues.put(COL_44, profession)
contentValues.put(COL_45, daysofholiday)
contentValues.put(COL_46, startday)
contentValues.put(COL_47, startmonth)
contentValues.put(COL_48, startyear)
contentValues.put(COL_49, endday)
contentValues.put(COL_410, endmonth)
contentValues.put(COL_411, endyear)
contentValues.put(COL_412, presentedday)
contentValues.put(COL_413, presentedmonth)
contentValues.put(COL_414, presentedyear)
contentValues.put(COL_415, engineer)
contentValues.put(COL_416, approveday)
contentValues.put(COL_417, approvemonth)
contentValues.put(COL_418, approveyear)
db.insert(TABLE_HOL, null, contentValues)
}
In the insert statement I defined to insert name as the second column, so it's my fault I tried to retrieve name from the forth column while it's inserted in second column.
Related
I'm working with a few different databases that all have the same stored procedure, but some have been updated while others haven't.
Suppose I have this entity:
#NamedStoredProcedureQueries(
NamedStoredProcedureQuery(
name = "getData",
procedureName = "dbo.selClientByStatus",
resultClasses = [MonitorData::class],
parameters = [
StoredProcedureParameter(name = "lowerRange", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "upperRange", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "connectionStatus", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "serverID", type = String::class, mode=ParameterMode.IN),
]
)
)
#Entity
data class MonitorData(
#Id
#Column(name = "serverId")
val serverId: Int? = null,
#Column(name = "displayName")
val displayName: String? = null,
#Column(name = "providerId")
val providerId: Int? = null
)
When I call the stored procedure with:
em?.createNamedStoredProcedureQuery("getData")
?.setParameter("lowerRange", null)
?.setParameter("upperRange", null)
?.setParameter("connectionStatus", null)
?.resultList
Some databases have providerId as a select in the stored procedure, but some don't. It's not really a necessary field, but it can help with sorting, etc. When a stored procedure doesn't select providerId I understandably get a(n) SQLServerException saying The column providerId is not valid.
Is it possible to ignore that field if it doesn't exist in the resultList?
I currently have a TABLE object, as below and existing table in DB. I am creating a webservice using KTOR.
object Arts: Table() {
val id : Column<Int> = integer("id").autoIncrement().primaryKey()
val title = varchar("title" , 256)
val description = varchar("desc", 512)
val price = double("price")
}
I would like to add a column, last_modified how to alter the current table.
First, add the column last_modified to your table.
object Arts: Table() {
val id : Column<Int> = integer("id").autoIncrement().primaryKey()
val title = varchar("title" , 256)
val description = varchar("desc", 512)
val price = double("price")
val lastModified = datetime("last_modified").defaultExpression(CurrentDateTime())
}
Then call the function
SchemaUtils.createMissingTablesAndColumns(Arts)
here is the class I set up for my database. database handler being the inner class.
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.ContentValues
import android.util.Log
import java.sql.Date
class Scores {
var id : Int = 0
var dataBaseName = "ScoreDatabase"
var averageTime = 0.0f
val date = Date(System.currentTimeMillis()).toString()
constructor(averageTime:Float) {
this.averageTime = averageTime
Log.d("Poop", averageTime.toString())
}
constructor()
inner class DataBaseHandler(var context:Context, tableName:String): SQLiteOpenHelper(context, dataBaseName, null,1){
val TABLE_NAME = tableName
val COL_ID = "id"
val COL_AVG = "Average_Time"
val COL_DATE = "Date"
override fun onCreate(db: SQLiteDatabase?) {
val createTable = "CREATE TABLE " + TABLE_NAME +" (" +
COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_AVG + " VARCHAR(256)," +
COL_DATE +" VARCHAR(256)"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun insertData(score: Scores){
val db = this.writableDatabase
var cv = ContentValues()
cv.put(COL_AVG,score.averageTime)
cv.put(COL_DATE,score.date)
var result = db.insert(TABLE_NAME,null,cv)
if(result == -1.toLong())
Log.d("POOP", "fail score table in addition")
else
Log.d("POOP", "Success score table in addition" )
}
fun readData(): MutableList<Scores>{
var list: MutableList<Scores> = ArrayList()
val db = this.readableDatabase
val query = "Select * from $TABLE_NAME"
val result = db.rawQuery(query,null)
if (result.moveToFirst()){
do {
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
}while (result.moveToNext())
}
result.close()
db.close()
return list
}
}
}
I tried this where the scores class and the handler were two separate classes, but it generated the same results.
here is how I write to the database (from 4 separate activities. in each activity the tablename is different. in this one for example it is 'additionDataBase')
val scores = Scores("%.3f".format(timeKeeper.averageNumber).toFloat())
val db = scores.DataBaseHandler(context, "additionDataBase")
db.insertData(scores)
and here is how I read from the database which is in a different activity that shows the averageTime from each table. here is the code for one of them
val context: Context? = activity
val adb = Scores().DataBaseHandler(context!!,"additionDataBase")
val data = adb.readData()
TextViewAdScore.text = data[0].averageTime.toString() + " " + data[1].date
I think I am missing something, but I can't seem to find what it is.
so far, no matter how many times I do this. the output is always 0.0f
Look at what you do in readData:
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
id, AvgTime, and date are retrieved but not used in any way, so your code is equivalent to just writing list.add(Scores()). (Side note: there's no reason for them to be var, and why the case inconsistency between AvgTime and the rest?)
I have use two different classes:
ListTitle.kt
class ListTitle {
var id: Int? = null
var title: String? = null
constructor(id:Int, title: String) {
this.id = id
this.title = title
}
}
ListDes.kt
class ListDes {
var address: Int? = null
var des: String? = null
constructor(address: Int, des: String) {
this.address = address
this.des = des
}
}
listOfTitle and listDes are ArrayLists:
listOfTitle.add(ListTitle(1, "Hello"))
listOfTitle.add(ListTitle(2, "World"))
listDes.add(ListDes(1, "World Des"))
listDes.add(ListDes(2, "Hello Des"))
I want to assign title of ListTitle to des of ListDes by matching them by id/address for each element of the two lists.
How can I approach this?
You can use zip to merge two lists into one which has Pairs as elements.
val listOfTitle = listOf(ListTitle(1, "Hello"), ListTitle(2, "World"))
val listDes = listOf(ListDes(1, "World Des"), ListDes(2, "Hello Des"))
val pairList = listOfTitle.zip(listDes)
// since an element in the new list is a pair, we can use destructuring declaration
pairList.forEach { (title, des) ->
println("${title.title} ${des.des}")
}
Output:
Hello World Des
World Hello Des
A few notes:
You can write your classes in a shorter form in Kotlin. Just put the properties directly in the argument list of the primary constructor like shown below.
class ListTitle(
var id: Int? = null,
var title: String? = null
)
class ListDes(
var address: Int? = null,
var des: String? = null
)
Don't overuse nullability (using Int? instead of Int for instance). Make properties only nullable if necessary. If you always pass in arguments for the specified properties there is not need for them to be nullable.
Maybe you should choose other names for the classes (without "List" in it) since they are actually elements of a List in your example and not lists themselves.
If you just want to print the values you could do this:
listOfTitle.forEach {
val id = it.id
println(it.title + " " + listDes.filter { it.address == id }[0].des)
}
will print the matching des for each id:
Hello World Des
World Hello Des
The above code is supposed to work when both lists have the same length and there is always a matching des for each id
if you want to create a new list with the matching pairs:
val newList = listOfTitle.map { it ->
val id = it.id
Pair(it.title, listDes.filter { it.address == id }[0].des)
}
newList.forEach { println(it.first + " " + it.second) }
I have this simulation:
init : (Model, Cmd Msg)
init = ({ dog = List Dog }, Cmd.none)
type alias Dog =
{ name : String
, age : Int
, price : Float
, extra = List Extra
}
type alias Extra =
{ allergies : List String
, wishes : List String
}
[{ name = "Hot"
, age = 1
, price = 300.5
, extra = [{...}]
},
{ name = "Dog"
, age = 3
, price = 150.0
, extra = [{...}]
}]
And I want to remove only 'extras' of Dog, in determined part of the code:
[{ name = "Hot"
, age = 1
, price = 300.5
},
{ name = "Dog"
, age = 3
, price = 150.0
}]
I can do this by mapping the entire list and generating a new one by removing 'extra' occurrence:
removeExtraOfDogs dogList =
(dogList |> List.map (\dog ->
{ name = dog.name
, age = dog.age
, price = dog.price
}
))
but I want to make it dynamic to just pass the extra to remove, without having to know what variables there are in the type and recreate it
Elm used to have this feature but it was removed a while ago. But, based on your use case described in a comment, I don't think you need this feature. You can instead use extensible record feature of Elm to allow passing different records into a function as long as they contain a fixed set of fields.
For example, let's say you have two types with name and age fields and having an extra incompatible field:
type alias Foo = { name : String, age : Int, extra : List String }
type alias Bar = { name : String, age : Int, extra : Int }
You can define a function that takes a record with a name field of type String and age of type Int and any extra fields:
encode : { r | name : String, age : Int } -> String
encode record = record.name ++ "," ++ toString record.age
You'll can now pass both Foo and Bar to this function because they both satisfy the requirements of the type signature.