Can you help solve the problem with the missing column? It seems to me that I did everything right, but I get the error that something is wrong with one column.
ERROR
E/SQLiteLog: (1) no such column: Stezenie D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.apkadlapacjenta, PID: 11261
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apkadlapacjenta/com.example.apkadlapacjenta.HistoriaPomiarow}:
android.database.sqlite.SQLiteException: no such column: Stezenie
(code 1 SQLITE_ERROR): , while compiling: SELECT Id, Stezenie, Zegar,
Data, Posilek, Stres, Samopoczucie, Hiperglikemia FROM Pomiary
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: android.database.sqlite.SQLiteException: no such column: Stezenie (code 1 SQLITE_ERROR): , while compiling: SELECT Id,
Stezenie, Zegar, Data, Posilek, Stres, Samopoczucie, Hiperglikemia
FROM Pomiary
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:61)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1443)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:515)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:392)
at com.example.apkadlapacjenta.DbMenager.Query(DbMenager.kt:65)
at com.example.apkadlapacjenta.HistoriaPomiarow.LoadQuery(HistoriaPomiarow.kt:55)
at com.example.apkadlapacjenta.HistoriaPomiarow.onCreate(HistoriaPomiarow.kt:33)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I/Process: Sending signal. PID: 11261 SIG: 9 Disconnected from the
target VM, address: 'localhost:8630', transport: 'socket'
MAIN ACTIVITY
package com.example.apkadlapacjenta
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.SearchView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_historia_pomiarow.*
import kotlinx.android.synthetic.main.content_historia_pomiarow.*
import kotlinx.android.synthetic.main.row.view.deleteBtn
import kotlinx.android.synthetic.main.row1.view.*
#Suppress("DEPRECATION")
class HistoriaPomiarow : AppCompatActivity() {
var listaWynikow = ArrayList<FIrebaseVal>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_historia_pomiarow)
setSupportActionBar(toolbar)
//Wczytujemy baze danych
LoadQuery("%")
}
override fun onResume() {
super.onResume()
LoadQuery("%")
}
private fun LoadQuery(pomiary: String) {
val dbManager = DbMenager(this)
val projections = arrayOf(
"Id",
"Stezenie",
"Zegar",
"Data",
"Posilek",
"Stres",
"Samopoczucie",
"Hiperglikemia"
)
val selectionArgs = arrayOf(pomiary)
val cursor =
dbManager.Query(projections,null,null,null)
listaWynikow.clear()
if (cursor.moveToFirst()) {
do {
val ID = cursor.getInt(cursor.getColumnIndex("Id"))
val Stezenie = cursor.getString(cursor.getColumnIndex("Stezenie"))
val Zegar = cursor.getString(cursor.getColumnIndex("Zegar"))
val Data = cursor.getString(cursor.getColumnIndex("Data"))
val Posilek = cursor.getString(cursor.getColumnIndex("Posilek"))
val Stres = cursor.getString(cursor.getColumnIndex("Stres"))
val Samopoczucie = cursor.getString(cursor.getColumnIndex("Samopoczucie"))
val Hiperglikemia = cursor.getString(cursor.getColumnIndex("Hiperglikemia"))
listaWynikow.add(
FIrebaseVal(
ID,
Stezenie,
Zegar,
Data,
Posilek,
Stres,
Samopoczucie,
Hiperglikemia ))
} while (cursor.moveToNext())
}
//Adapter
val ListaWynikowAdapter = MylistApdater(this, listaWynikow)
//ustawienia adaptera
listapomiarow.adapter = ListaWynikowAdapter
// Wszystkie zadania
val total = listapomiarow.count
//actionbar
val mActionBar = supportActionBar
if(mActionBar !=null){
//ustawienia Action Bara
mActionBar.subtitle = "Masz $total wyników"
}
}
override fun onCreateOptionsMenu(menu: Menu?):Boolean {
menuInflater.inflate(R.menu.notemenu, menu)
//searchView
val sv: SearchView = menu!!.findItem(R.id.app_bar_search).actionView as SearchView
val sm = getSystemService(Context.SEARCH_SERVICE) as SearchManager
sv.setSearchableInfo(sm.getSearchableInfo(componentName))
sv.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
//implementujemy dwie metody
override fun onQueryTextSubmit(query: String?): Boolean {
LoadQuery("%$query%")
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
LoadQuery("%$newText%")
return false
}
})
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.dodaj_notatke->{
startActivity(Intent(this,AddNote::class.java))
}
R.id.sortuj->{
showSortDialog()
}
}
return super.onOptionsItemSelected(item)
}
private fun showSortDialog() {
//lista opcji
val sortOption = arrayListOf("Najnowsze","starsze","Tytul rosnaco","Tytul malejaco")
val mBuilder = AlertDialog.Builder(this)
mBuilder.setTitle("Sort by")
mBuilder.setIcon(R.drawable.ic_sort)
}
inner class MylistApdater(
context: Context,
private var ListaWynikowAdapter: ArrayList<FIrebaseVal>
) : BaseAdapter() {
var listWynikiArray = ArrayList<FIrebaseVal>()
var context: Context? = context
#SuppressLint("ViewHolder","InflateParams")
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val myView = layoutInflater.inflate(R.layout.row1, null)
val Wynik = ListaWynikowAdapter[position]
myView.stezenienumberpicker.text = Wynik.nodeNumberPicker.toString()
myView.godzina.text = Wynik.nodezegar
myView.data.text = Wynik.nodedata
myView.posilekRG.text = Wynik.nodeposilek
myView.SP1.text = Wynik.nodehiperglikemia
myView.SP2.text = Wynik.nodestres
myView.SP3.text = Wynik.nodesamopoczucie
//Przycisk kasowania
myView.deleteBtn.setOnClickListener {
val dbMenager = DbMenager(this.context!!)
val selectionArgs = arrayOf(Wynik.nodeID.toString())
dbMenager.delete("ID=?", selectionArgs)
LoadQuery("%")
}
return myView
}
override fun getItem(position: Int): Any {
return ListaWynikowAdapter[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return ListaWynikowAdapter.size
}
}
private fun GoToUpdateFun(Wyniki: FIrebaseVal) {
val intent = Intent(this,AddPomiary::class.java)
intent.putExtra("Id",Wyniki.nodeID)//wpisz Id
intent.putExtra("Stezenie",Wyniki.nodeNumberPicker)
intent.putExtra("Zegar",Wyniki.nodezegar)
intent.putExtra("Data",Wyniki.nodedata)
intent.putExtra("Posilek",Wyniki.nodeposilek)
intent.putExtra("Hiperglikemia",Wyniki.nodehiperglikemia)
intent.putExtra("Stres",Wyniki.nodestres)
intent.putExtra("Samopoczucie",Wyniki.nodesamopoczucie)
startActivity(intent)
}
}
DBMENAGER
package com.example.apkadlapacjenta
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQueryBuilder
import android.widget.RadioGroup
import android.widget.Toast
class DatebaseMenagerPomiary(context: Context) {
//Database name
var dbName = "Historia Pomiarów"
//table name
var dbTable = "Wyniki"
//kolumny
var colID = "Id"
var colStezenie = "Stezenie"
var colZegar = "Zegar"
var colData = "Data"
var colPosilek = "Posilek"
var colStres = "Stres"
var colSamopoczucie = "Samopoczucie"
var colHiperglikemia = "Hiperglikemia"
//wersja
var dbVersion = 1
//Tworzymy tabele
val sqlCreateTable =
"CREATE TABLE$dbTable($colID INTEGER PRIMARY KEY, $colStezenie TEXT, $colZegar TEXT, $colData TEXT, $colPosilek TEXT, $colStres TEXT,$colSamopoczucie TEXT, $colHiperglikemia TEXT)"
var sqlDB: SQLiteDatabase? = null
init {
val db = DatabaseHelperWyniki(context)
sqlDB = db.writableDatabase
}
inner class DatabaseHelperWyniki : SQLiteOpenHelper {
var context: Context? = null
constructor(context: Context) : super(context, dbName, null, dbVersion) {
this.context = context
}
override fun onCreate(db: SQLiteDatabase?) {
db!!.execSQL(sqlCreateTable)
Toast.makeText(this.context,"baza danych utworzona...",Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db!!.execSQL("zamknij tabele jeśli nie istnieje" + dbTable)
}
}
fun insert(values:ContentValues):Long{
val ID = sqlDB!!.insert(dbTable,"",values)
return ID
}
fun Query(projection:Array<String>,selection:String,selectionArgs:Array<String>,sorOrder:String): Cursor {
val qb = SQLiteQueryBuilder()
qb.tables=dbTable
val cursor = qb.query(sqlDB,projection,selection,selectionArgs,null,null,sorOrder)
return cursor
}
fun delete(selection: String,selectionArgs: Array<String>):Int{
val count = sqlDB!!.delete(dbTable,selection,selectionArgs)
return count
}
fun update(values:ContentValues,selection: String,selectionArgs: Array<String>): Int {
val count = sqlDB!!.update(dbTable,values,selection,selectionArgs)
return count
}
}
NODE CLASS dont see on name :D
package com.example.apkadlapacjenta
class FIrebaseVal(
nodeID: Int, nodeNumberPicker:String,
nodezegar:String,
nodedata:String,
nodeposilek: String,
nodehiperglikemia: String,
nodestres: String,
nodesamopoczucie: String
) {
var nodeID: Int?= nodeID
var nodeNumberPicker: String? = nodeNumberPicker
var nodezegar:String?=nodezegar
var nodedata:String?=nodedata
var nodeposilek: String? =nodeposilek
var nodehiperglikemia:String?=nodehiperglikemia
var nodestres:String?=nodestres
var nodesamopoczucie:String?=nodesamopoczucie
}
Mates can you explain me what is wrong ? Thx
Probably you add this column but forget to add migration from old database version. You can check it by clear all application data (or delete and install it). If reinstall fix the problem you should create migration from old database verstion to new
Also you can refactor all your database to use Room instead of ugly ORMLite.
It's friendly and powerfull persistance library from google
I believe that your issue may be due to the line :-
val sqlCreateTable =
"CREATE TABLE$dbTable($colID INTEGER PRIMARY KEY, $colStezenie TEXT, $colZegar TEXT, $colData TEXT, $colPosilek TEXT, $colStres TEXT,$colSamopoczucie TEXT, $colHiperglikemia TEXT)"
There is no space between the TABLE keyword and the table name.
Try changing to :-
val sqlCreateTable =
"CREATE TABLE $dbTable($colID INTEGER PRIMARY KEY, $colStezenie TEXT, $colZegar TEXT, $colData TEXT, $colPosilek TEXT, $colStres TEXT,$colSamopoczucie TEXT, $colHiperglikemia TEXT)"
And then after uninstalling the App or deleting the App's data try rerunning.
Related
I have a MainFragment.kt
package com.funkytwig.tasktimer
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.funkytwig.tasktimer.databinding.FragmentMainBinding
private const val TAG = "MainFragmentXX"
/**
* A simple [Fragment] subclass as the default destination in the navigation.
*/
class MainFragment : Fragment() {
private var _binding: FragmentMainBinding? = null
private val viewModel by lazy { ViewModelProvider(this)[TaskTimerViewModel::class.java] } // New
private val mAdapter = CursorRecyclerViewAdapter(null) // null=view with instructions NEW
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
val funct = "onCreate"
Log.d(TAG, funct)
super.onCreate(savedInstanceState)
Log.d(TAG, "$funct about to register viewModel")
viewModel.cursor.observe( // New
this, Observer { cursor -> mAdapter.swapCursor(cursor)?.close() }
)
Log.d(TAG, "$funct done")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
Log.d(TAG, "onCreateView")
_binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Log.d(TAG, "onViewCreated")
super.onViewCreated(view, savedInstanceState)
binding.taskList.layoutManager =
LinearLayoutManager(context) // Set layout manager to Linear NEW
binding.taskList.adapter = mAdapter // Attach Adapter to Recyclerview New
}
override fun onDestroyView() {
Log.d(TAG, "onDestroyView")
super.onDestroyView()
_binding = null
}
// ** From here ist just logging functions **
override fun onAttach(context: Context) {
Log.d(TAG, "onAttach")
super.onAttach(context)
}
// override fun onActivityCreated(savedInstanceState: Bundle?) { // depreciated
// Log.d(TAG, "onActivityCreated(depreciated)")
// super.onActivityCreated(savedInstanceState)
// }
override fun onViewStateRestored(savedInstanceState: Bundle?) {
Log.d(TAG, "onViewStateRestored")
super.onViewStateRestored(savedInstanceState)
}
override fun onStart() {
Log.d(TAG, "onStart")
super.onStart()
}
override fun onResume() {
Log.d(TAG, "onResume")
super.onResume()
}
override fun onPause() {
Log.d(TAG, "onPause")
super.onPause()
}
override fun onSaveInstanceState(outState: Bundle) {
Log.d(TAG, "onSaveInstanceState")
super.onSaveInstanceState(outState)
}
override fun onStop() {
Log.d(TAG, "onStop")
super.onStop()
}
override fun onDestroy() {
Log.d(TAG, "onDestroy")
super.onDestroy()
}
override fun onDetach() {
Log.d(TAG, "onDetach")
super.onDetach()
}
}
And am getting the following errors in Logcat when
viewModel.cursor.observe( // New
this, Observer { cursor -> mAdapter.swapCursor(cursor)?.close() }
)
runs in onCreate (i.e. if I comment out this it works)
FATAL EXCEPTION: main
Process: com.funkytwig.takstimer, PID: 7099
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.funkytwig.takstimer/com.funkytwig.tasktimer.MainActivity}: android.view.InflateException: Binary XML file line #25 in com.funkytwig.takstimer:layout/activity_main: Binary XML file line #15 in com.funkytwig.takstimer:layout/content_main: Error inflating class androidx.fragment.app.FragmentContainerView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: android.view.InflateException: Binary XML file line #25 in com.funkytwig.takstimer:layout/activity_main: Binary XML file line #15 in com.funkytwig.takstimer:layout/content_main: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: android.view.InflateException: Binary XML file line #15 in com.funkytwig.takstimer:layout/content_main: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.funkytwig.tasktimer.TaskTimerViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:320)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at com.funkytwig.tasktimer.MainFragment$viewModel$2.invoke(MainFragment.kt:23)
at com.funkytwig.tasktimer.MainFragment$viewModel$2.invoke(MainFragment.kt:23)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at com.funkytwig.tasktimer.MainFragment.getViewModel(MainFragment.kt:23)
at com.funkytwig.tasktimer.MainFragment.onCreate(MainFragment.kt:35)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:3090)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1720)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:323)
at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.kt:158)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:53)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:136)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:248)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:227)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1069)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:997)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1263)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1119)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
at com.funkytwig.tasktimer.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:55)
at com.funkytwig.tasktimer.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:49)
at com.funkytwig.tasktimer.MainActivity.onCreate(MainActivity.kt:27)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:312)
... 50 more
Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range. The statement has 0 parameters.
at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:215)
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:169)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:203)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:49)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1443)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:515)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:392)
at com.funkytwig.tasktimer.AppProvider.query(AppProvider.kt:125)
at android.content.ContentProvider.query(ContentProvider.java:1214)
at android.content.ContentProvider.query(ContentProvider.java:1307)
at android.content.ContentProvider$Transport.query(ContentProvider.java:267)
at android.content.ContentResolver.query(ContentResolver.java:944)
at android.content.ContentResolver.query(ContentResolver.java:880)
at android.content.ContentResolver.query(ContentResolver.java:836)
at com.funkytwig.tasktimer.TaskTimerViewModel.loadTasks(TaskTimerViewModel.kt:32)
at com.funkytwig.tasktimer.TaskTimerViewModel.<init>(TaskTimerViewModel.kt:19)
... 53 more
TaskTimerViewModel.kt is
package com.funkytwig.tasktimer
import android.app.Application
import android.database.Cursor
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
private const val TAG = "TaskTimerViewModelXX"
class TaskTimerViewModel(application: Application) : AndroidViewModel(application) {
private val dbCursor = MutableLiveData<Cursor>()
val cursor: LiveData<Cursor>
get() = dbCursor
init {
Log.d(TAG, "init")
loadTasks()
}
private fun loadTasks() {
val funct = "loadTasks"
Log.d(TAG, funct)
val projection = arrayOf(
TasksContract.Columns.TASK_NAME,
TasksContract.Columns.TASK_DESCRIPTION,
TasksContract.Columns.TASK_SORT_ORDER
)
val sortOrder =
"${TasksContract.Columns.TASK_SORT_ORDER}, ${TasksContract.Columns.TASK_NAME}"
val cursor = getApplication<Application>().contentResolver.query(
TasksContract.CONTENT_URI, null, null, projection, sortOrder
)
dbCursor.postValue(cursor!!) // Update on different thread
Log.d(TAG, "$funct done")
}
}
CursorViewRecyclerAdapter.kt is
package com.funkytwig.tasktimer
import android.database.Cursor
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.funkytwig.tasktimer.databinding.TaskListItemsBinding
private const val TAG = "CurRecViewAdapterXX"
class TaskViewHolder(private val binding: TaskListItemsBinding) :
RecyclerView.ViewHolder(binding.root) {
val taskListName: TextView = binding.taskListName
val taskListDescription: TextView = binding.taskListDescription
val taskListEdit: ImageButton = binding.taskListEdit
val taskListDelete: ImageButton = binding.taskListDelete
}
class CursorRecyclerViewAdapter(private var cursor: Cursor?) :
RecyclerView.Adapter<TaskViewHolder>() {
// Called by Recyclerview when it needs new view to display
// viewType allows different types to be shows on different lines of view,
// to find out more google 'Recyclerview getItemViewType
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
Log.d(TAG, "onCreateViewHolder (new view requested)")
val viewHolder = TaskListItemsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return TaskViewHolder(viewHolder)
}
// When Recycler view wants new data to be displayed and is providing existing view to be reused
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val func = "onBindViewHolder"
Log.d(TAG, "$func (bind data to view)")
val cursor = cursor // Smart Cast Hack
if (cursor == null || cursor.count == 0) { // No items in cursor
Log.d(TAG, "$func: providing instructions ")
holder.taskListName.setText(R.string.instructions_heading)
holder.taskListDescription.setText(R.string.instructions)
holder.taskListEdit.visibility = View.GONE
holder.taskListDelete.visibility = View.GONE
} else { // Cursor not empty
if (!cursor.moveToPosition(position)) throw IllegalStateException("Could not move cursor to position $position")
// Create Task object from data in cursor
val task = Task(
cursor.getString(cursor.getColumnIndex(TasksContract.Columns.TASK_NAME)),
cursor.getString(cursor.getColumnIndex(TasksContract.Columns.TASK_DESCRIPTION)),
cursor.getInt(cursor.getColumnIndex(TasksContract.Columns.TASK_SORT_ORDER))
)
// Remember ID is not set in constructor
task.id = cursor.getLong(cursor.getColumnIndex(TasksContract.Columns.ID))
holder.taskListName.text = task.name
holder.taskListDescription.text = task.description
holder.taskListEdit.visibility = View.VISIBLE // TODO: add onclick
holder.taskListDelete.visibility = View.VISIBLE // TODO: add onclick
}
}
override fun getItemCount(): Int {
val func = "getItemCount"
Log.d(TAG, func)
val count = cursor?.count
if (count == 0 || cursor == null) {
Log.d(TAG, "$func: no items so return 1")
return 1 // So Instructions are displayed if cursor empty
} else {
Log.d(TAG, "$func: $count items")
return count!!.toInt()
}
}
/**
* Swap is a new cursor, returning the old cursor.
* The returned cursor is *not* closed
*
* This allows underlying cursor to be swapped if data changes and we need to re query
* Should be called when the cursor that the adapter is using is changed.
* Reruns previous cursor so it can be closed.
*
* #param newCursor The new cursor to be used if there was not one.
* If the given new cursor is the same as the previous set cursor, null is also returned.
*/
fun swapCursor(newCursor: Cursor?): Cursor? {
if (newCursor === cursor) return null
val numItems = itemCount
val oldCursor = cursor
if (newCursor != null) {
// notify observer about cursor
notifyDataSetChanged()
} else { // cursor has changed
// Notify observer about lack of dataset, all of it from 0 to newItems,
// i.e. whole range of records has gone
notifyItemRangeChanged(0, numItems)
}
return oldCursor
}
}
All the code is at https://github.com/funkytwig/tasktimer/tree/master/app/src/main
Ive been googling and trying to work this out for a few houres but no joy.
I have a layout that has two EDITETEXT and they should be filled and saved in the database by pressing the save button
Everything is correct, but when I write the button code, the program runs
and quickly exits the program
(And that there is no mistake)
If I want to say complete, it means: everything is correct until I want to use the database :|
code main activity:
enter codeclass MainActivity : AppCompatActivity() {
private lateinit var adapter: Adapter
private lateinit var layoutManger:LinearLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
buttonsave.setOnClickListener {
var dbmanger= DBmanager(this)
var values = ContentValues()
values.put("Title",editTextTitle.text.toString())
values.put("Desc",editTextdesc.text.toString())
val ID= dbmanger .Insert (values)
if (ID > 0 ){
Toast.makeText(this, "یــادادشــت جـــدیِـد ذخـیره شـــد!", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(this, " خطــا در ذخـیره یــادادشــت !", Toast.LENGTH_SHORT).show()
}
}
setContentView(R.layout.activity_main)
layoutManger = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
adapter = Adapter()
val list = ArrayList<Model>()
list.apply {
add(Model("fatemeh", "chamani fard"))
add(Model("reyhaneh", "chamani fard"))
add(Model("bahareh", "chamani fard"))
add(Model("abolfazl", "chamani fard"))
}
adapter.setList(list)
list_main.layoutManager=layoutManger
list_main.adapter=adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu,menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId)
{
R.id.menuItemNew->{
var intent=Intent(this,addnoteactivity::class.java)
startActivity(intent)
}
}
return super.onOptionsItemSelected(item)
}
}
code button:
enter cod buttonsave.setOnClickListener {
var dbmanger= DBmanager(this)
var values = ContentValues()
values.put("Title",editTextTitle.text.toString())
values.put("Desc",editTextdesc.text.toString())
val ID= dbmanger .Insert (values)
if (ID > 0 ){
Toast.makeText(this, "یــادادشــت جـــدیِـد ذخـیره شـــد!", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(this, " خطــا در ذخـیره یــادادشــت !", Toast.LENGTH_SHORT).show()
}
}
code database:
enter code hclass DBmanager {
val dbName="notesDB"
val dbTable="tblNotes"
val colID="ID"
val colTitle="Title"
val colDesc="Desc"
val dbVersion=1
val sqlCreateTable="CREATE TABLE IF NOT EXISTS " + dbTable + " ("+ colID +" INTEGER PRIMARY KEY , "+ colTitle +" TEXT,"+ colDesc +" TEXT);"
var sqlDB:SQLiteDatabase ?= null
constructor (context: Context){
val db =DatabaseHelper(context)
sqlDB=db.writableDatabase
}
inner class DatabaseHelper :SQLiteOpenHelper {
var context:Context ?= null
constructor(context: Context):super(context,dbName,null,dbVersion){
this.context=context
}
override fun onCreate(p0: SQLiteDatabase?) {
p0 !!.execSQL(sqlCreateTable)
Toast.makeText(context, "دیتا بیس ایجاد شد", Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
p0 !!.execSQL(" DROP TABLE IF EXISTS " + dbTable)
}
}
fun Insert(values:ContentValues):Long{
val ID=sqlDB!!.insert(dbTable,"",values)
return ID
}
}
Help me please
Kotlin language
These are displayed in logcat:
--------- beginning of crash
2022-07-17 09:20:46.820 7916-7916/com.example.data420tir E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.data420tir, PID: 7916
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.data420tir/com.example.data420tir.MainActivity}: java.lang.NullPointerException: findViewById(R.id.buttonsave) must not be null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3897)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4076)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8349)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
Caused by: java.lang.NullPointerException: findViewById(R.id.buttonsave) must not be null
at com.example.data420tir.MainActivity.onCreate(MainActivity.kt:23)
at android.app.Activity.performCreate(Activity.java:8085)
at android.app.Activity.performCreate(Activity.java:8073)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3870)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4076)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8349)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
2022-07-17 09:20:46.834 7916-7916/com.example.data420tir I/Process: Sending signal. PID: 7916 SIG: 9
And one question: what does Android aip 31 mean?
Add layout file before any action or initialization of widget.
It should be like
MainActivity : AppCompatActivity() {
//Your code
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val buttonsave:Button = findViewById(R.id.buttonsave)
buttonsave.setOnClickListener {
//Your code
}
//Your code
}
I am trying to implement the onCreate() method in my Content provider and can't wrap my head around what I should do to resolve this error:
"Type mismatch: inferred type is Context? but Context was expected
Here is my DatabaseHandler.kt
package com.example.rewardreacher
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast
const val DATABASE_NAME = "GoalDB"
const val TABLE_NAME = "Goals"
const val COL_NAME = "name"
const val COL_FREQUENCY = "frequency"
const val COL_PERFORMED = "performed"
const val COL_ID = "id"
class DatabaseHandler(var context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 1) {
override fun onCreate(db: SQLiteDatabase?) {
// No DB - Then create
val createTable = "CREATE TABLE $TABLE_NAME (" +
"$COL_ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"$COL_NAME VARCHAR(256), " +
"$COL_FREQUENCY INTEGER(1), " +
"$COL_PERFORMED INTEGER(256))"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db?.execSQL("DROP TABLE IF EXISTS $DATABASE_NAME");
onCreate(db);
}
fun insertData(goal : Goal) {
val db = this.writableDatabase
val cv = ContentValues()
cv.put(COL_NAME, goal.name)
cv.put(COL_FREQUENCY, goal.frequency)
cv.put(COL_PERFORMED, goal.performed)
val result = db.insert(TABLE_NAME, null, cv)
if (result == (0).toLong())
Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show()
else
Toast.makeText(context, "Success", Toast.LENGTH_LONG).show()
}
#SuppressLint("Range")
fun readData() : MutableList<Goal> {
val list: MutableList<Goal> = ArrayList()
val db = this.readableDatabase
val query = "Select * from $TABLE_NAME"
val result = db.rawQuery(query, null)
if (result.moveToFirst()) {
do {
val goal = Goal()
goal.id = result.getString(result.getColumnIndex(COL_ID)).toInt()
goal.name = result.getString(result.getColumnIndex(COL_NAME))
goal.frequency = result.getString(result.getColumnIndex(COL_FREQUENCY)).toInt()
goal.performed = result.getString(result.getColumnIndex(COL_PERFORMED)).toInt()
list.add(goal)
} while (result.moveToNext())
}
result.close()
db.close()
return list
}
}
And MyContentProvider.kt
package com.example.rewardreacher.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import com.example.rewardreacher.DatabaseHandler
const val DATABASE_NAME = "GoalDB"
const val GOALS_TABLE = "Goals"
const val COL_NAME = "name"
const val COL_FREQUENCY = "frequency"
const val COL_PERFORMED = "performed"
const val COL_ID = "id"
class MyContentProvider : ContentProvider() {
private var dbHandler: DatabaseHandler? = null
override fun onCreate(): Boolean {
dbHandler = DatabaseHandler(context)
return false
}
private val GOALS = 1
private val GOALS_ID = 2
private val sURIMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
sURIMatcher.addURI(AUTHORITY, GOALS_TABLE, GOALS)
sURIMatcher.addURI(AUTHORITY, GOALS_TABLE + "/#",
GOALS_ID)
}
companion object {
val AUTHORITY = "com.example.rewardreacher.provider.MyContentProvider"
val CONTENT_URI : Uri = Uri.parse("content://" + AUTHORITY + "/" +
GOALS_TABLE)
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
TODO("Implement this to handle requests to delete one or more rows")
}
override fun getType(uri: Uri): String? {
TODO(
"Implement this to handle requests for the MIME type of the data" +
"at the given URI"
)
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
TODO("Implement this to handle requests to insert a new row.")
}
override fun query(
uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, sortOrder: String?
): Cursor? {
TODO("Implement this to handle query requests from clients.")
}
override fun update(
uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?
): Int {
TODO("Implement this to handle requests to update one or more rows.")
}
}
I never work in android studio / kotlin and I guess it is probably a simple solution but I can't seem to fix it...
The context that you use to create databaseHandler has a nullable annotation.
public final #Nullable Context getContext() {
return mContext;
}
So you can fix it by making the databaseHandler context nullable
class DatabaseHandler(var context: Context?)
Or you can add a null check before instantiating the databaseHandler :
override fun onCreate(): Boolean {
dbHandler = context?.let { DatabaseHandler(it) }
return false
}
context returns a nullable Context (a Context?) because it's null in the lifecycle before onCreate(). According to the documentation, inside onCreate(), it is no longer null, so it is safe to assert non-null with !!.
Also, you should be returning true from onCreate if there wasn't a problem.
override fun onCreate(): Boolean {
dbHandler = DatabaseHandler(context!!)
return true
}
I'm a bit lost, make a database, where the user will have to save the results of the study, in which he will choose data from various widgets, such as spinners or RGs. How to encode variables of type Int or String is not a problem for me but in the case of Spinner number picker and RG already. Can somebody straighten me out?
MAIN ACTIVITY
Package com.example.apkadlapacjenta
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_historia_pomiarow.*
class HistoriaPomiarow : AppCompatActivity() {
var listaWynikow = ArrayList<FIrebaseVal>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_historia_pomiarow)
setSupportActionBar(toolbar)
//Wczytujemy baze danych
LoadQuery("%")
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onResume() {
super.onResume()
LoadQuery("%")
}
private fun LoadQuery(title:String){
val dbManager = DbMenager(this)
val projections = arrayOf("Id", "Stezenie", "Zegar","Data","Posilek","Stres","Samopoczucie","Hiperglikemia","Insulina")
val cursor =
dbManager.Query(projections, "Title like?", selectionArgs , "Title")
listaWynikow.clear()
if (cursor.moveToFirst()) {
do {
***val ID = cursor.getInt(cursor.getColumnIndex("Id")) ---> HERE i have problem
val Stezenie = cursor.getInt(cursor.getColumnIndex("Stezenie")) ---> NumberPicker
val Zegar = cursor.getString(cursor.getColumnIndex("Zegar"))
val Data =cursor.getString(cursor.getColumnIndex("Data"))
val Posilek = cursor.getString(cursor.getColumnIndex("Posilek")) -----> RB
val Stres = cursor.getString(cursor.getColumnIndex("Stres"))
val Samopoczucie = cursor.getString(cursor.getColumnIndex("Samopoczucie")) --->SPINNER
val Hiperglikemia = cursor.getString(cursor.getColumnIndex("Hiperglikemia"))--->SPINNER
val Insulina = cursor.getInt(cursor.getColumnIndex("Insulina")) --->SPINNER
**listaWynikow.add(Note(ID, Stezenie, Zegar,Data,Posilek,Stres,Samopoczucie,Hiperglikemia,Insulina))
} while (cursor.moveToNext())*****
}
}
}
"---> Spinner,Numberpicker,RG" etc etc isnt CODE
DateBase Menager
package com.example.apkadlapacjenta
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQueryBuilder
import android.widget.RadioGroup
import android.widget.Toast
class DatebaseMenagerPomiary {
//Database name
var dbName = "Historia Pomiarów"
//table name
var dbTable = "Wyniki"
//kolumny
var colID = "Id"
var colStezenie = "Stezenie"
var colZegar = "Zegar"
var colData = "Data"
var colPosilek = "Posilek"
var colStres = "Stres"
var colSamopoczucie = "Samopoczucie"
var colHiperglikemia = "Hiperglikemia"
var colInsulina = "Insulina"
//wersja
var dbVersion = 1
//Tworzymy tabele
val sqlCreateTable =
"CREATE TABLE$dbTable($colID INTEGER PRIMARY KEY, $colStezenie NumberPicker, $colZegar TEXT, $colData TEXT, $colPosilek RADIO GROUP, $colStres SPINNER,$colSamopoczucie SPINNER, $colHiperglikemia SPINNER, $colInsulina TEXT)"
var sqlDB: SQLiteDatabase? = null
constructor(context: Context){
var db = DatabaseHelperWyniki(context)
sqlDB = db.writableDatabase
}
inner class DatabaseHelperWyniki : SQLiteOpenHelper {
var context: Context? = null
constructor(context: Context) : super(context, dbName, null, dbVersion) {
this.context = context
}
override fun onCreate(db: SQLiteDatabase?) {
db!!.execSQL(sqlCreateTable)
Toast.makeText(this.context,"baza danych utworzona...",Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db!!.execSQL("zamknij tabele jeśli nie istnieje" + dbTable)
}
}
fun insert(values:ContentValues):Long{
val ID = sqlDB!!.insert(dbTable,"",values)
return ID
}
fun Query(projection:Array<String>,selection:String,selectionArgs:Array<String>,sorOrder:String): Cursor {
val qb = SQLiteQueryBuilder();
qb.tables=dbTable
val cursor = qb.query(sqlDB,projection,selection,selectionArgs,null,null,sorOrder)
return cursor
}
fun delete(selection: String,selectionArgs: Array<String>):Int{
val count = sqlDB!!.delete(dbTable,selection,selectionArgs)
return count
}
fun update(values:ContentValues,selection: String,selectionArgs: Array<String>): Int {
val count = sqlDB!!.update(dbTable,values,selection,selectionArgs)
return count
}
}
NODE CLASS
NODE CLASS
package com.example.apkadlapacjenta
import android.provider.MediaStore
import android.widget.NumberPicker
import android.widget.RadioGroup
import android.widget.Spinner
class FIrebaseVal(nodeID: Int, nodeNumberPicker:NumberPicker,nodezegar:String,nodedata:String,nodeposilek:RadioGroup,nodehiperglikemia:Spinner,nodestres:Spinner,nodesamopoczucie:Spinner,nodeinsulina:Int) {
var nodeID: Int?= nodeID
var nodeNumberPicker:NumberPicker?= nodeNumberPicker
var nodezegar:String?=nodezegar
var nodedata:String?=nodedata
var nodeposilek:RadioGroup?=nodeposilek
var nodehiperglikemia:Spinner?=nodehiperglikemia
var nodestres:Spinner?=nodestres
var nodesamopoczucie:Spinner?=nodesamopoczucie
var nodeinsulina:Int?=nodeinsulina
}
The rest of the code I know how to do, i.e. the adapter and various functions such as SearchView etc, need help with Numberpicker, Spinner and RG encoding because in the line:
listaWynikow.add(Note(ID, Stezenie, Zegar,Data,Posilek,Stres,Samopoczucie,Hiperglikemia,Insulina))
} while (cursor.moveToNext())
I get an error
"too many arguments for public constructor string() defined ".
The problem with node class here you have declared total 9 parameter :
class FIrebaseVal(nodeID: Int, nodeNumberPicker:NumberPicker,nodezegar:String,nodedata:String,nodeposilek:RadioGroup,nodehiperglikemia:Spinner,nodestres:Spinner,nodesamopoczucie:Spinner,nodeinsulina:Int)
but here your passing 10 parameter please confirm the parameter values. I can't understand variable name.
listaWynikow.add(Note(ID, Stezenie, Zegar,Data,Posilek,Stres,Samopoczucie,Hiperglikemia,Insulina))
Whenever i try to run my app it closes with error no such table todos..
MainActivity.kt
package com.vineet.tododatabase
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import com.vineet.tododatabase.db.MyDbHelper
import com.vineet.tododatabase.db.TodoTable
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val todos = ArrayList<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val todosAdapter = ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
todos
)
val db = MyDbHelper(this).writableDatabase
lvItems.adapter = todosAdapter
fun refreshTodoList(){
val todoList = TodoTable.getAllTodos(db)
Log.d("TODOS", todoList.toString())
}
btnAdd.setOnClickListener {
val newTodo= Todo(
etTask.text.toString(),
false
)
TodoTable.insertTodos(db, newTodo)
refreshTodoList()
}
}
}
MyDbHelper.kt
package com.vineet.tododatabase.db
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class MyDbHelper(context: Context): SQLiteOpenHelper(
context,
"todos.db",
null,
1
){
override fun onCreate(p0: SQLiteDatabase?) {
}
override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
}
}
TodoTable.kt
package com.vineet.tododatabase.db
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import com.vineet.tododatabase.Todo
object TodoTable{
val TABLE_NAME = "todos"
object Columns{
val ID = "id"
val TASK = "task"
val DONE = "done"
}
val CMD_CREATE_TABLE = """
CREATE TABLE IF NOT EXIST $TABLE_NAME
(
${Columns.ID} INTEGER PRIMARY KEY AUTOINCREMENT,
${Columns.TASK} TEXT,
${Columns.DONE} BOOLEAN
);
""".trimIndent()
fun insertTodos(db: SQLiteDatabase, todo: Todo){
val row = ContentValues()
row.put(Columns.TASK, todo.task)
row.put(Columns.DONE, todo.done)
db.insert(TABLE_NAME,null, row)
}
fun getAllTodos(db: SQLiteDatabase): ArrayList<Todo>{
val todos = ArrayList<Todo>()
var c = db.query(
TABLE_NAME,
arrayOf(Columns.ID, Columns.TASK, Columns.DONE),
null, null,
null, null,
null
)
while (c.moveToNext()){
var todo = Todo(c.getString(1), c.getInt(2) == 1)
todos.add(todo)
}
return todos
}
}
models.kt
package com.vineet.tododatabase
data class Todo(var task: String, var done: Boolean)
i dont know why i am getting this error
E/SQLiteLog: (1) no such table: todos E/SQLiteDatabase: Error
inserting task=gg done=false
android.database.sqlite.SQLiteException: no such table: todos (code 1): , while compiling: INSERT INTO todos(task,done)
VALUES (?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1417)
at com.vineet.tododatabase.db.TodoTable.insertTodos(TodoTable.kt:30)
at com.vineet.tododatabase.MainActivity$onCreate$2.onClick(MainActivity.kt:40)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
E/SQLiteLog: (1) no such table: todos
execute create table query in your dbHelper's onCreate method to create table...and then it will try to fetch data from table
p0.execSQL("Create table todos (blah,blah,blah)")