"too many arguments for public constructor string() defined " Kotlin problem - android

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

Related

Content provider: onCreate() type mismatch - Context? vs Context (Kotlin)

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
}

Process: com.example.whatsappclone java.lang.IllegalArgumentException

i am getting this error
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter it
i don't know which variable is null i have used everything
need help , i am a beginner in android development , pls don't judge me
i know it's a simple mistake but unable to find it
Following is the entire code.
enter image description here
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.whatsappclone.Adapters.ChatAdapter
import com.example.whatsappclone.Models.MessageModel
import com.example.whatsappclone.databinding.ActivityChatDetailBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.squareup.picasso.Picasso
import java.util.*
import kotlin.collections.ArrayList
class ChatDetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityChatDetailBinding//view binding
private lateinit var mDbRef: DatabaseReference
private lateinit var auth: FirebaseAuth
private lateinit var messageList: ArrayList<MessageModel>
private lateinit var chatAdapter: ChatAdapter
private var senderRoom: String? = null
private var receiverRoom: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
//view binding
super.onCreate(savedInstanceState)
binding = ActivityChatDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
//removing action bar
supportActionBar?.hide()
//getting instance of auth
auth = FirebaseAuth.getInstance()
//getting database reference
mDbRef = FirebaseDatabase.getInstance().reference
messageList = ArrayList()
val senderId = auth.currentUser?.uid//sender Id
val receiverId = intent.getStringExtra("userId")//receiver Id
senderRoom = senderId + receiverId
receiverRoom = receiverId + senderId
//getting intent extra
val userName = intent.getStringExtra("userName")
val profilePic = intent.getStringExtra("profilePic")
//putting intent extra values in views
binding.username.text = userName
if (!profilePic.equals("")) {
Picasso.get().load(profilePic).placeholder(R.drawable.defaultprofile)
.into(binding.IVProfileImage)
}
//on click listener on back button
binding.btnBack.setOnClickListener {
val intent = Intent(this#ChatDetailActivity, MainActivity::class.java)
startActivity(intent)
this.finish()
}
//chat recycler view adapter
chatAdapter = ChatAdapter(messageList, this)
binding.chatRecyclerView.adapter = chatAdapter
binding.chatRecyclerView.layoutManager = LinearLayoutManager(this)
mDbRef.child("chats")
.child(senderRoom!!).addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
messageList.clear()
for (postSnapshot in snapshot.children) {
val model = postSnapshot.getValue(MessageModel::class.java)
messageList.add(model!!)
}
chatAdapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
}
})
//on click on send button
binding.send.setOnClickListener {
// Toast.makeText(this, "sid:- " + senderId.toString(), Toast.LENGTH_SHORT).show()
// Toast.makeText(this, "rid:- " + receiverId.toString(), Toast.LENGTH_SHORT).show()
val message = binding.etMessage.text.toString()
val model = MessageModel(senderId!!, message)
// Toast.makeText(this, "mess- ${messageList.size}", Toast.LENGTH_SHORT).show()
// Toast.makeText(this, "id- ${senderId}", Toast.LENGTH_SHORT).show()
model.timeStamp = Date().time
binding.etMessage.setText("")
mDbRef.child("chats").child(senderRoom!!).push()
.setValue(model).addOnSuccessListener {
mDbRef.child("chats").child(receiverRoom!!).push()
.setValue(model)
}
}
}
}

Recycler View with duplicate rows after refreshing activity

After doing some research i found out that i need to clear the list that i am using each time i refresh the activity, after trying it to refresh the list at different places, the result remains the same and i have decided to give my brain a break and ask for help. The refreshing takes place on the PostDialogFragment class
i have circled the recycler view causing the issue
PostAdapter
package com.example.osrscritic.view
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.osrscritic.databinding.PostRowItemBinding
import com.example.osrscritic.model.Skillvalue
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.QueryDocumentSnapshot
import com.google.firebase.firestore.QuerySnapshot
class PostsAdapter: RecyclerView.Adapter<PostsViewHolder>() {
val postsMutableList : MutableList<DocumentSnapshot> = mutableListOf()
fun setPostsList(statsList: List<DocumentSnapshot>) {
postsMutableList.addAll(statsList)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostsViewHolder {
val binding = PostRowItemBinding.inflate(LayoutInflater.from(parent.context)
,parent,false)
return PostsViewHolder(binding)
}
override fun onBindViewHolder(holder: PostsViewHolder, position: Int) {
val post = postsMutableList[position]
holder.binding.tvCritic.text = post["critic"].toString()
val posts = post["posts"] as List<String>
var count = 0;
holder.binding.tvActualPost.movementMethod = ScrollingMovementMethod()
for(p in posts) {
holder.binding.tvActualPost.append("${count}: " + p + "\n")
count++
}
}
override fun getItemCount() = postsMutableList.size
}
class PostsViewHolder(val binding: PostRowItemBinding) : RecyclerView.ViewHolder(binding.root)
DisplayUserActivty
package com.example.osrscritic
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.osrscritic.databinding.ActivityDisplayUserBinding
import com.example.osrscritic.view.PostDialogFragment
import com.example.osrscritic.view.PostsAdapter
import com.example.osrscritic.view.StatsAdapter
import com.example.osrscritic.viewmodel.DisplayUserViewModel
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentSnapshot
import org.koin.androidx.viewmodel.ext.android.viewModel
class DisplayUserActivity : AppCompatActivity() {
private val displayUserViewModel : DisplayUserViewModel by viewModel()
lateinit var binding: ActivityDisplayUserBinding
val statsAdapter = StatsAdapter()
val postsAdapter = PostsAdapter()
lateinit var critiquing: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val extras = intent.extras
critiquing = extras?.getString("c")!!
binding = ActivityDisplayUserBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.rsStatsRv.adapter = statsAdapter
binding.rsStatsRv.layoutManager = LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false)
binding.rvPosts.adapter = postsAdapter
binding.rvPosts.layoutManager = LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false)
configureObservers()
displayUserViewModel.getFirebaseRef()
displayUserViewModel.getOSRSPlayer()
binding.ivWritePost.setOnClickListener {
PostDialogFragment.newInstance(critiquing).show(supportFragmentManager
, PostDialogFragment.KEY)
}
}
private fun configureObservers() {
displayUserViewModel.displayUserLiveData.observe(this, {
statsAdapter.setStatsList(it.skillvalues)
binding.tvRunescapeName.text = String.format("Account Name: %s", it.name)
binding.tvCombat.text = String.format("Combat Level: %s", it.combatlevel.toString())
})
displayUserViewModel.loadingState.observe(this, {
when(it){
true -> binding.pgBar.visibility = View.VISIBLE
false -> binding.pgBar.visibility = View.GONE
}
})
displayUserViewModel.errorData.observe(this, {
Toast.makeText(this, it, Toast.LENGTH_LONG).show()
})
displayUserViewModel.displayUserPostsLiveData.observe(this, {
postsAdapter.postsMutableList.clear()
it.document(critiquing).collection("posts").get()
.addOnSuccessListener {
postsAdapter.setPostsList(it.documents)
}
})
}
}
PostDialogFragment
package com.example.osrscritic.view
import android.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.fragment.app.DialogFragment
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.EditText
import android.view.Gravity
import androidx.core.app.ActivityCompat.recreate
import com.example.osrscritic.DisplayUserActivity
import com.example.osrscritic.viewmodel.DisplayUserViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FieldPath
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.SetOptions
import org.koin.androidx.viewmodel.ext.android.viewModel
class PostDialogFragment: DialogFragment() {
private val displayUserViewModel : DisplayUserViewModel by viewModel()
val currentUser = FirebaseAuth.getInstance().currentUser
lateinit var critiquing: String
val postsAdapter = PostsAdapter()
companion object {
const val KEY: String = "KEY2"
//lateinit var param: String
fun newInstance(text: String): PostDialogFragment {
val args = Bundle()
val postDialogFragment = PostDialogFragment()
args.putString(KEY, text)
postDialogFragment.arguments = args
return postDialogFragment
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
critiquing = arguments?.getString(KEY)!!
Log.d("*******8", critiquing)
val builder = AlertDialog.Builder(activity)
val layout = LinearLayout(activity)
val parms = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
layout.orientation = LinearLayout.VERTICAL
layout.layoutParams = parms
layout.gravity = Gravity.CLIP_VERTICAL
layout.setPadding(2, 2, 2, 2)
val tv = TextView(activity)
tv.text = "Text View title"
tv.setPadding(40, 40, 40, 40)
tv.gravity = Gravity.CENTER
tv.textSize = 20f
val et = EditText(activity)
var etString = ""
et.addTextChangedListener(object: TextWatcher{
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(p0: Editable?) {
Log.d("etText", et.text.toString())
etString = et.text.toString()
}
})
val tv1 = TextView(activity)
tv1.text = "Input Student ID"
val tv1Params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
tv1Params.bottomMargin = 5
//layout.addView(tv1, tv1Params)
layout.addView(
et,
LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
)
//param = arguments?.getString(KEY)!!
builder.setTitle("New Post")
builder.setView(layout).setPositiveButton("Done", object: DialogInterface.OnClickListener{
override fun onClick(p0: DialogInterface?, p1: Int) {
activity?.let {
displayUserViewModel.displayUserPostsLiveData.observe(it, {
val post : MutableMap<String, Any> = mutableMapOf()
val posts : MutableList<String> = mutableListOf()
posts.add(etString)
post["critic"] = currentUser?.email!!
post["posts"] = posts
if(it.document(critiquing).collection("posts").document().equals(null)) {
it.document(critiquing).collection("posts")
.document(currentUser?.email!!).set(post)
}
it.document(critiquing).collection("posts")
.document(currentUser?.email!!).update("posts", FieldValue.arrayUnion(etString))
})
}
activity!!.finish()
activity!!.overridePendingTransition( 0, 0);
startActivity(activity!!.intent)
//trying to clear the list here once being refreshed
postsAdapter.postsMutableList.clear()
activity!!.overridePendingTransition( 0, 0);
}
})
builder.setNegativeButton("Cancel", object:DialogInterface.OnClickListener{
override fun onClick(p0: DialogInterface?, p1: Int) {
dismiss()
}
})
return builder.create()
}
}
Overriding those usually solves this kind of issues:
getItemId: return long that uniquely identifies every item. For example, you could use an autoincrementing variable id for each new item object, or some hashcode. This should be paired with setHasStableIds(true). (By default it returns RecyclerView.NO_ID which value is -1).
This helps to make sure RecyclerView e.g. identifies items properly, knows when OnBindViewHolder must be called or to return precise values on getAdapterPosition().
getItemCount: return an int with current number of items. Usually the Array.size() where the data is. (By default it returns 0).
getItemType: If there's multiple view types, return a unique number for each type of ViewHolder (usually starting with 0). (By default it returns 0).

RecyclerView add dynamically item. NotifyDataChanged doesn't work

In this app, i am adding addresses to account and saving them in Realtime database (firebase).I want also to display them in recyclerview but they aren't visible.
Here visualization of my problem : https://youtu.be/OdlZNUQnA-k
The Code should work like this
Addressfragment Contains AddressesRecyclerview
AddAddressfragment for adding new Address
And it goes back to AddressFragment when new Address has been added.
Also when i tried to display all items from one array like for example postcode .It display only last added item. Even on for each loop. Like last item is deleted after adding
I understand that it need something like notifyDataSetChanged() but it doesnt work here
Here is The code:
AddressFragment:
package com.querto.fragments.address
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.querto.R
import com.querto.adapters.AddressAdapter
import com.querto.viewmodel.MainActivityViewModel
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_address.view.*
class AddressFragment : Fragment() {
private lateinit var mMainActivityViewModel: MainActivityViewModel
private lateinit var database: DatabaseReference
private lateinit var mAuth: FirebaseAuth
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
var view = inflater.inflate(R.layout.fragment_address, container, false)
database = FirebaseDatabase.getInstance().reference
mAuth = FirebaseAuth.getInstance()
mMainActivityViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application).create(
MainActivityViewModel::class.java)
if(mAuth.currentUser==null){
Toast.makeText(requireContext(), "To add address please login",Toast.LENGTH_SHORT).show()
activity?.nav_view?.setCheckedItem(R.id.login)
activity?.supportFragmentManager?.beginTransaction()?.setCustomAnimations(R.anim.fragment_slide_in_anim, R.anim.fragment_fade_out_anim, R.anim.fragment_slide_out_anim, R.anim.fragment_fade_in_anim)?.replace(R.id.fragment_container, mMainActivityViewModel.loginFragment)?.commit()
}
view.recyclerViewAddress.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
view.recyclerViewAddress.adapter = AddressAdapter(requireContext(), mMainActivityViewModel.list_of_addresses)
view.add_address_btn.setOnClickListener {
activity?.supportFragmentManager?.beginTransaction()?.setCustomAnimations(R.anim.fragment_slide_in_anim, R.anim.fragment_fade_out_anim, R.anim.fragment_slide_out_anim, R.anim.fragment_fade_in_anim)?.replace(R.id.fragment_container, mMainActivityViewModel.addAddressFragment)?.commit()
}
return view
}
}
Adapter:
package com.querto.adapters
import android.app.Application
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.querto.R
import com.querto.model.Address
import com.querto.viewmodel.MainActivityViewModel
import kotlinx.android.synthetic.main.my_address_row.view.*
class AddressAdapter(contextAdapter: Context, addresses: ArrayList<Address>):
RecyclerView.Adapter<AddressAdapter.MyViewHolder>() {
private var mMainActivityViewModel: MainActivityViewModel
private val context: Context = contextAdapter
private val local_addreses : ArrayList<Address> = addresses
private var database: DatabaseReference
private var mAuth: FirebaseAuth
init {
mMainActivityViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(context.applicationContext as Application).create(
MainActivityViewModel::class.java)
database = FirebaseDatabase.getInstance().reference
mAuth = FirebaseAuth.getInstance()
}
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val currentTitle = itemView.address_title
val currentId = itemView.address_id
val currentStreet = itemView.address_street
val currentPostcode = itemView.address_postcode
val currentHouseNumber = itemView.address_number
val currentAddressCityName = itemView.address_city
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.my_address_row, parent, false))
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.currentTitle.text = local_addreses[position].name
holder.currentId.text = (position + 1).toString()
holder.currentStreet.text =local_addreses[position].street
holder.currentPostcode.text =local_addreses[position].postcode
holder.currentHouseNumber.text = local_addreses[position].house_number
holder.currentAddressCityName.text = local_addreses[position].city_name
}
override fun getItemCount(): Int {
return local_addreses.size
}
fun addAddress(address: Address){
mMainActivityViewModel.list_of_addresses.add(address)
notifyDataSetChanged()
}
}
AddAddress:
package com.querto.fragments.address
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.querto.R
import com.querto.adapters.AddressAdapter
import com.querto.model.Address
import com.querto.viewmodel.MainActivityViewModel
import kotlinx.android.synthetic.main.fragment_add_address.view.*
class AddAddressFragment : Fragment() {
private lateinit var database: DatabaseReference
private lateinit var mAuth: FirebaseAuth
private lateinit var mMainActivityViewModel: MainActivityViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
var view = inflater.inflate(R.layout.fragment_add_address, container, false)
mMainActivityViewModel =
ViewModelProvider.AndroidViewModelFactory.getInstance(activity?.application!!)
.create(MainActivityViewModel::class.java)
view.addAddressButton.setOnClickListener {
val addressName = view.addAddressName.text.toString()
val addressStreet = view.addAddressStreet.text.toString()
val addressNumber = view.addAddressHouseNumber.text.toString()
val addressZipCode = view.addAddressCityZipCode.text.toString()
val addressCityName = view.addAddressCityName.text.toString()
if(inputCheck(addressName,addressStreet,addressNumber,addressZipCode, addressCityName)){
mAuth = FirebaseAuth.getInstance()
database = FirebaseDatabase.getInstance().reference
addAddress(addressName, addressStreet, addressNumber, addressZipCode, addressCityName)
}else{
Toast.makeText(requireContext(), "Please enter all fields", Toast.LENGTH_SHORT).show()
}
}
return view
}
private fun addAddress(addressName: String, addressStreet: String, addressNumber: String,addressZipCode: String, addressCityName: String) {
val address = Address(mAuth.currentUser?.uid, addressName, addressStreet,addressZipCode, addressNumber, addressCityName)
database.child("addresses").child(database.push().key.toString()).setValue(address).addOnCompleteListener {
if(it.isSuccessful){
val addressAdapter= AddressAdapter(requireContext(), mMainActivityViewModel.list_of_addresses)
addressAdapter.addAddress(address)
activity?.supportFragmentManager?.beginTransaction()?.setCustomAnimations(R.anim.fragment_slide_in_anim, R.anim.fragment_fade_out_anim, R.anim.fragment_slide_out_anim, R.anim.fragment_fade_in_anim)?.replace(R.id.fragment_container, mMainActivityViewModel.addressFragment)?.commit()
Toast.makeText(requireContext(), "Added address", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(requireContext(), "Fail at creating address", Toast.LENGTH_SHORT).show()
}
}
}
private fun inputCheck(addressName: String, addressStreet: String, addressNumber: String,addressZipCode: String, adressCityName: String)=
addressName.isNotEmpty() && addressStreet.isNotEmpty() && addressNumber.isNotEmpty() && addressZipCode.isNotEmpty() && adressCityName.isNotEmpty() && addressZipCode.length==5
}
MainActivityViewModel:
class MainActivityViewModel(application: Application) : AndroidViewModel(application) {
private lateinit var database: DatabaseReference
private lateinit var mAuth: FirebaseAuth
val homeFragment = HomeFragment()
val loginFragment = LoginFragment()
val registerFragment = RegisterFragment()
val detailsFragment = DetailsFragment()
val addressFragment = AddressFragment()
val addAddressFragment = AddAddressFragment()
var pizza_names: Array<String> = application.resources.getStringArray(R.array.pizza_titles)
var pizza_desc: Array<String> = application.resources.getStringArray(R.array.pizza_desc)
val pizza_small_price: IntArray = application.resources.getIntArray(R.array.pizza_small_price)
val pizza_medium_price: IntArray = application.resources.getIntArray(R.array.pizza_medium_price)
val pizza_big_price: IntArray = application.resources.getIntArray(R.array.pizza_big_price)
var pizza_img: Array<Int> = arrayOf(R.drawable.napoletana, R.drawable.margherita, R.drawable.estate, R.drawable.pepperone, R.drawable.pancetta, R.drawable.ortolana, R.drawable.marinara, R.drawable.diavola, R.drawable.messicana, R.drawable.quattro_formaggi, R.drawable.sugoza, R.drawable.semola, R.drawable.capriciossa, R.drawable.vulcano, R.drawable.romana, R.drawable.capodanno, R.drawable.primavera, R.drawable.regina, R.drawable.quattro_stagioni, R.drawable.cilento, R.drawable.tirolese, R.drawable.michele, R.drawable.pollo, R.drawable.havana, R.drawable.siciliana, R.drawable.sandra, R.drawable.bari, R.drawable.gringo, R.drawable.angelo, R.drawable.spinaci)
var focaccia_names: Array<String> = application.resources.getStringArray(R.array.foaccia_titles)
var focaccia_desc: Array<String> = application.resources.getStringArray(R.array.foaccia_desc)
val focaccia_price: IntArray = application.resources.getIntArray(R.array.foaccia_price)
var focaccia_img: Array<Int> = arrayOf(R.drawable.base, R.drawable.nutella)
var calzone_names: Array<String> = application.resources.getStringArray(R.array.calzone_titles)
var calzone_desc: Array<String> = application.resources.getStringArray(R.array.calzone_desc)
val calzone_price_normal: IntArray = application.resources.getIntArray(R.array.calzone_normal_price)
val calzone_price_big: IntArray = application.resources.getIntArray(R.array.calzone_big_price)
var calzone_img: Array<Int> = arrayOf(R.drawable.calzone)
var panuozzo_names: Array<String> = application.resources.getStringArray(R.array.panuozzo_titles)
var panuozzo_desc: Array<String> = application.resources.getStringArray(R.array.panuozzo_desc)
val panuozzo_price_normal: IntArray = application.resources.getIntArray(R.array.panuozzo_normal_price)
val panuozzo_price_big: IntArray = application.resources.getIntArray(R.array.panuozzo_big_price)
var panuozzo_img: Array<Int> = arrayOf(R.drawable.panuozzo)
val sosy_names: Array<String> = application.resources.getStringArray(R.array.sosy_titles)
val sosy_price: IntArray = application.resources.getIntArray(R.array.sosy_price)
val napoje_names: Array<String> = application.resources.getStringArray(R.array.napoje_titles)
val napoje_price: IntArray = application.resources.getIntArray(R.array.napoje_price)
val napoje_first_kind: Array<String> = application.resources.getStringArray(R.array.napoje_kinds_one)
val napoje_second_kind: Array<String> = application.resources.getStringArray(R.array.napoje_kinds_two)
val dodatki_names: Array<String> = application.resources.getStringArray(R.array.dodatki_titles)
val dodatki_small_price: IntArray = application.resources.getIntArray(R.array.dodatki_small_price)
val dodatki_medium_price: IntArray = application.resources.getIntArray(R.array.dodatki_medium_price)
val dodatki_big_price: IntArray = application.resources.getIntArray(R.array.dodatki_big_price)
var list_of_addresses = ArrayList<Address>()
private val mutableLoginStatus = MutableLiveData<Boolean>()
val loginStatus: LiveData<Boolean>
get() = mutableLoginStatus
fun checkLogin(username: String, password: String) {
viewModelScope.launch(Dispatchers.IO) {
database = FirebaseDatabase.getInstance().reference
mAuth = FirebaseAuth.getInstance()
mAuth.signInWithEmailAndPassword(username,password).addOnCompleteListener{
if(it.isSuccessful){
mutableLoginStatus.postValue(true)
}else{
mutableLoginStatus.postValue(false)
}
}
}
}
fun shareApp(context: Context) {
val openURL = Intent(android.content.Intent.ACTION_VIEW)
openURL.data = Uri.parse("https://www.facebook.com/1488596184507308/")
context.startActivity(openURL)
}
fun sendMail(context: Context) {
val sendEmail = Intent(Intent.ACTION_SEND)
val email: Array<String> = arrayOf("kontakt#cilento.pl")
sendEmail.setData(Uri.parse("mailto: kontakt#cilento.pl "))
sendEmail.putExtra(Intent.EXTRA_SUBJECT, "Problem z Usługą")
sendEmail.putExtra(Intent.EXTRA_TEXT, "Pizza którą zamówiłem nie przyszła na czas.\n\n\nMoje Dane Kontaktowe: \n\nImie: \nNazwisko: \nAdres: ")
sendEmail.setType("message/rfc822")
sendEmail.putExtra(Intent.EXTRA_EMAIL, email)
val chooser = Intent.createChooser(sendEmail, "Send mail using")
context.startActivity(chooser)
}
}
Address Class:
package com.querto.model
data class Address(
val userId: String?,
val name: String?,
val street: String?,
val postcode: String?,
val house_number: String?,
val city_name: String?
)
After Checking The MainActivityViewModel ,I See that you are not fetching data from the firebase database.
You should add this to AddressFragment class
also Add Variable called addressAdapter in the top of the class
fun getAddresses(){
val ref = FirebaseDatabase.getInstance().reference.child("addresses")
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
val address = dataSnapshot.getValue<Address>()
mMainActivityViewModel.addresses_list.add(address)
addressAdapter.notifyDataChanged()
}
}
override fun onCancelled(databaseError: DatabaseError) {
}
})
}
Also Implementing Address adapter here does not do a thing . just remove it.
private fun addAddress(addressName: String, addressStreet: String, addressNumber: String,addressZipCode: String, addressCityName: String) {
val address = Address(mAuth.currentUser?.uid, addressName, addressStreet,addressZipCode, addressNumber, addressCityName)
database.child("addresses").child(database.push().key.toString()).setValue(address).addOnCompleteListener {
if(it.isSuccessful){
val addressAdapter= AddressAdapter(requireContext(), mMainActivityViewModel.address_title, mMainActivityViewModel.address_street,mMainActivityViewModel.address_post_code, mMainActivityViewModel.address_house_number, mMainActivityViewModel.address_city_name)
addressAdapter.addAddress(addressName, addressStreet,addressZipCode, addressNumber, addressCityName)
activity?.supportFragmentManager?.beginTransaction()?.setCustomAnimations(R.anim.fragment_slide_in_anim, R.anim.fragment_fade_out_anim, R.anim.fragment_slide_out_anim, R.anim.fragment_fade_in_anim)?.replace(R.id.fragment_container, mMainActivityViewModel.addressFragment)?.commit()
Toast.makeText(requireContext(), "Added address", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(requireContext(), "Fail at creating address", Toast.LENGTH_SHORT).show()
}
}
I will try to explain it here.
When you create a custom RecyclerView adapter usually you suppose to pass data you want to be displayed in the list. For me it is better to pass array Of Class You Made To Pass Data For Single Recylcer View itemArrayList<ClassOfSingleItem>, but it is not nessesary of course.
So when you call notifyDataSetCahnged you notify your adapter that data in this ArrayList was changed. But this call will not work if you create new Adapter every time you add or remove something from the RecyclerView list.
EDIT:
Let me explain what i see: you have button with click listener, when you click it you replace current fragmen with the one where you add data.
view.add_address_btn.setOnClickListener {
activity?.supportFragmentManager?.beginTransaction()?.setCustomAnimations(R.anim.fragment_slide_in_anim, R.anim.fragment_fade_out_anim, R.anim.fragment_slide_out_anim, R.anim.fragment_fade_in_anim)?.replace(R.id.fragment_container, mMainActivityViewModel.addAddressFragment)?.commit()
}
then, when you complete editing all fields what you do? replace your addAdressFragment with addressFragment:
val addressAdapter= AddressAdapter(requireContext(), mMainActivityViewModel.list_of_addresses)
addressAdapter.addAddress(address)
activity?.supportFragmentManager?.beginTransaction()?.setCustomAnimations(R.anim.fragment_slide_in_anim, R.anim.fragment_fade_out_anim, R.anim.fragment_slide_out_anim, R.anim.fragment_fade_in_anim)?.replace(R.id.fragment_container, mMainActivityViewModel.addressFragment)?.commit()
inside this method you CREATE new AdressAdapter to call method addAdrees which has notifyDataSetChanged call inside. But recyclerView in your addressFragment has no idea about this new AddressAdapter. This is the main problem. As i mentioned in comment below my answer there are only two ways to update RecyclerView so implement one of them.
Below I show some java code (you mentioned you know java) which can give you an idea:
public class PointActivity extends BaseActivity
implements SearchView.OnQueryTextListener{
private RecyclerView mRecyclerView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_point);
mRecyclerView = findViewById(R.id.point_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
List<PointItem> pointItems = getFilteredAndSortedList();
mRecyclerView.setAdapter(new PointAdapter(this, pointItems));
}
//here we need to update recyclerView
#Override
public boolean onQueryTextSubmit(String query) {
searchResult(query);
return false;
}
public void searchResult(String query) {
if (query.isEmpty()) {
//just full list if query is empty
mRecyclerView.setAdapter(new PointAdapter(this, getFilteredAndSortedList()));
} else {
PointSearchManager pointSearchManager = new PointSearchManager();
List<PointItem> list;
list = Arrays.asList(pointSearchManager.toFilters(getFilteredAndSortedList().toArray(new PointItem[0]), query));
//list filtered with query result
mRecyclerView.setAdapter(new PointAdapter(this, list));
}
}

SQLite - Datebase colums

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.

Categories

Resources