I'm new to android, please help me
i made a interface in MainActivity and tried to initialize it like => class MainActivity(private val sender: DateSender) but it has to have it's defualt constractor or such.
it was the compile error =>
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.shohadav1/com.example.shohadav1.MainActivity}: java.lang.InstantiationException: class com.example.shohadav1.MainActivity has no zero argument constructor
i want to send my data to a Fragment, if you know any better approach please guide me. thanks
here is my main Activity =>
package com.example.shohadav1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AlertDialog
import com.example.shohadav1.databinding.ActivityMainBinding
import com.example.shohadav1.databinding.AddItemDialogBinding
class MainActivity(private val sender: DateSender) : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
//set AppName text
//set Navi button
val actionBarDrawerToggle = ActionBarDrawerToggle(
this,
binding.drawerLayoutMain,
binding.toolbarMain,
R.string.open,
R.string.close
)
binding.drawerLayoutMain.addDrawerListener(actionBarDrawerToggle)
actionBarDrawerToggle.syncState()
//Fragment setting
var transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container_main, MainItemsViewerFrag())
transaction.commit()
//add Item
binding.toolbarMain.setOnMenuItemClickListener {
when (it.itemId){
R.id.addItem_toolbar -> { additem()}
R.id.search_btn_toolbar -> { }
}
true
}
}
fun additem(){
var addDialog = AlertDialog.Builder(this).create()
var addDialogBinding = AddItemDialogBinding.inflate(layoutInflater)
addDialog.setView(addDialogBinding.root)
addDialog.show()
addDialogBinding.acceptBtnAddDialog.setOnClickListener {
var newName = addDialogBinding.addNameAddDialog.text.toString()
var birthdate = addDialogBinding.addBirthDateAddDialog.text.toString()
var deadDate = addDialogBinding.addDeadDateAddDialog.text.toString()
var vasiatname = addDialogBinding.addVasiatnameAddDialog.text.toString()
var newData = Data(newName, birthdate, deadDate, vasiatname)
sender.sendData(newData)
}
addDialogBinding.cancelBtnAddDialog.setOnClickListener { addDialog.dismiss() }
}
interface DateSender {
fun sendData (newData : Data)
}
}
ViewModel. Or, have the fragment'sViewModeland the activity'sViewModelshare a common repository. FWIW, I cover some of those techniques in this free book.