Я создал базу данных в SQLlite. Было добавлено, все сохранено. Я могу сохранить только значение TextView. Как я могу сохранить значение Numberpicker в базе данных, или выбор из счетчика или радиогруппы?
Это мой код только с textview. Как я могу завершить сборщик чисел и спиннеров?
ADD NOTE
package com.example.apkadlapacjenta
import android.content.ContentValues import android.os.Bundle import android.view.View import android.widget.Toast import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_add_note.* import kotlinx.android.synthetic.main.content_add_note.* import java.lang.Exception
class AddNote : AppCompatActivity() {
val dbTable = "Pomiary"
var id = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_note)
try{
val bundle:Bundle = intent.extras!!
id = bundle.getInt("ID",0)
if(id!=0){
//update notatki
//zmiana tytułu actionbar
supportActionBar!!.title="Update Note"
//zmiana przycisku tekstu
addBtn.text = "Update"
titleEt.setText(bundle.getString("name"))
descEt.setText(bundle.getString("des"))
}
}catch(ex:Exception){}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
fun addFunc(view: View) {
var dbMenager = DbMenager(this)
var values = ContentValues()
values.put("Title", titleEt.text.toString())
values.put("Description", descEt.text.toString())
if (id == 0) {
val ID = dbMenager.insert(values)
if (ID > 0) {
Toast.makeText(this, "Pomiar dodany", Toast.LENGTH_SHORT).show()
finish()
} else{
Toast.makeText(this, "błąd - spróbuj ponownie....", Toast.LENGTH_SHORT).show()
}
}
else{
var selectionArgs = arrayOf(id.toString())
val ID = dbMenager.update(values,"ID=?",selectionArgs)
if(ID>0){
Toast.makeText(this, "Pomiar zmieniony", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(this, "błąd - spróbuj ponownie....", Toast.LENGTH_SHORT).show()
}
}
}
}
Менеджер базы данных
package com.example.apkadlapacjenta
import android.app.DownloadManager
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.AutoCompleteTextView
import android.widget.Toast
class DbMenager {
//database name
var dbName = "Wyniki Pomiarów"
//table name
var dbTable = "Pomiary"
//kolumny
var colID = "ID"
var colTitle = "Title"
var colDes ="Description"
//database version
var dbVersion = 1
//Tworzymy tabele
val sqlCreateTable = "CREATE TABLE $dbTable($colID INTEGER PRIMARY KEY, $colTitle TEXT, $colDes TEXT)"
var sqlDB:SQLiteDatabase?=null
constructor(context: Context){
var db = DatabseHelperPomiary(context)
sqlDB = db.writableDatabase
}
inner class DatabseHelperPomiary: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
}
}
ОСНОВНАЯ ДЕЯТЕЛЬНОСТЬ
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.text.ClipboardManager
import android.view.*
import android.widget.Toast
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import android.widget.SearchView
import android.widget.SearchView.OnQueryTextListener;
import kotlinx.android.synthetic.main.activity_baza_wynikow.toolbar
import kotlinx.android.synthetic.main.content_baza_wynikow.*
import kotlinx.android.synthetic.main.row.view.*
@Suppress("DEPRECATION")
class BazaWynikow : AppCompatActivity() {
var listaPomiarow = ArrayList<Note>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_baza_wynikow)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
//Wczytujemy baze danych
LoadQuery("%")
}
override fun onResume() {
super.onResume()
LoadQuery("%")
}
private fun LoadQuery(title: String) {
val dbManager = DbMenager(this)
val projections = arrayOf("ID", "Title", "Description")
val selectionArgs = arrayOf(title)
val cursor =
dbManager.Query(projections, "Title like?", selectionArgs , "Title")
listaPomiarow.clear()
if (cursor.moveToFirst()) {
do {
val ID = cursor.getInt(cursor.getColumnIndex("ID"))
val Title = cursor.getString(cursor.getColumnIndex("Title"))
val Description = cursor.getString(cursor.getColumnIndex("Description"))
listaPomiarow.add(Note(ID, Title, Description))
} while (cursor.moveToNext())
}
//Adapter
val mojepomiary = MojePomiaryAdapter(this, listaPomiarow)
//ustawienia adaptera
notes_pomiarow.adapter = mojepomiary
// Wszystkie zadania
val total = notes_pomiarow.count
//actionbar
val mActionBar = supportActionBar
if(mActionBar !=null){
//ustawienia Action Bara
mActionBar.subtitle = "Masz $total pomiaró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)
}
//Implementation MojePomiaryAdapater
inner class MojePomiaryAdapter(context: Context, private var listaPomiarowAdapter: ArrayList<Note>) :
BaseAdapter() {
var context: Context?= context
//Generujemy secondary konstruktor
@SuppressLint("ViewHolder", "InflateParams")
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
//inflate layout row.xml
val myView = layoutInflater.inflate(R.layout.row,null)
val MojPomiar = listaPomiarowAdapter[position]
myView.titleTv.text= MojPomiar.nodeName
myView.descTv.text=MojPomiar.nodeDes
//Przycisk kasowania
myView.deleteBtn.setOnClickListener{
val dbMenager = DbMenager(this.context!!)
val selectionArgs = arrayOf(MojPomiar.nodeID.toString())
dbMenager.delete("ID=?",selectionArgs)
LoadQuery("%")
}
//Przycisk edytowania
myView.editBtn.setOnClickListener{
GoToUpdateFun(MojPomiar)
}
//Przycisk kopiowania
myView.copyBtn.setOnClickListener{
//wez tytul
val title = myView.titleTv.text.toString()
//wez opis pomiaru badania
val desc = myView.descTv.text.toString()
//powiązanie
val s = title+"\n"+desc
val cb = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cb.text = s // dodawanie do clickboardu 54
}
//share
myView.shareBtn.setOnClickListener{
val title = myView.titleTv.text.toString()
//wez opis pomiaru badania
val desc = myView.descTv.text.toString()
//powiązanie
val s = title+"\n"+desc
//intencja share
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "text"
shareIntent.putExtra(Intent.EXTRA_TEXT,s)
startActivity(Intent.createChooser(shareIntent,s))
}
return myView
}
override fun getItem(position: Int): Any {
return listaPomiarowAdapter[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return listaPomiarowAdapter.size
}
}
private fun GoToUpdateFun(mojPomiar: Note) {
val intent = Intent(this,AddNote::class.java)
intent.putExtra("ID",mojPomiar.nodeID)//wpisz Id
intent.putExtra("name",mojPomiar.nodeName)//wpisz nazwe
intent.putExtra("des",mojPomiar.nodeDes)// wpisz opis
startActivity(intent)
}
}
если бы вы могли сказать мне, что делать шаг за шагом, чтобы сохранить значения виджетов, перечисленных выше. В основном здесь
private fun LoadQuery(title: String) {
val dbManager = DbMenager(this)
val projections = arrayOf("ID", "Title", "Description")
val selectionArgs = arrayOf(title)
val cursor =
dbManager.Query(projections, "Title like?", selectionArgs , "Title")
listaPomiarow.clear()
if (cursor.moveToFirst()) {
do {
val ID = cursor.getInt(cursor.getColumnIndex("ID"))
val Title = cursor.getString(cursor.getColumnIndex("Title"))
val Description = cursor.getString(cursor.getColumnIndex("Description"))
listaPomiarow.add(Note(ID, Title, Description))
} while (cursor.moveToNext())
}
Здесь:
fun addFunc(view: View) {
var dbMenager = DbMenager(this)
var values = ContentValues()
values.put("Title", titleEt.text.toString())
values.put("Description", descEt.text.toString())
И здесь
package com.example.apkadlapacjenta
class Note(nodeID: Int, nodeName:String,nodeDes:String) {
var nodeID: Int?= nodeID
var nodeName:String?= nodeName
var nodeDes:String?=nodeDes
}