'How to Pass dataclass object from activity to another activity for update/delete
Basically I have a activity which shows all the records input by the user. This uses a recyclerview. When the user clicks on an item row, it takes that info and displays it on the screen in another activity which is "Edit buy screen" . The user can edit the information and update it and then will be taken back to the "all records screen" upon success.
using getIntent, I managed to show the info on the screen. However when I try to update the info it doesnt change. According to debug. The var studentModel(Dataclass obj) is null on the second activity. This tells me that i need a way to bring the studentModel obj data from allrecords activity to the editScreen activity. Any way i can do this using getIntent or another way?
All records class
private lateinit var edName: EditText
private lateinit var edEmail: Button
private lateinit var edBuyAmount: EditText
private lateinit var edUseAmount: EditText
private lateinit var edReason: EditText
private lateinit var btnAdd: Button
private lateinit var btnView: Button
private lateinit var btnUpdate: Button
private lateinit var sqLiteHelper: SQLiteHelper
private lateinit var recyclerView: RecyclerView
private var adapter: StudentAdapter?=null
private var std:StudentModel?=null \<-------------This holds the data when the user clicks a row of data
@RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_all_recordpage)
val textView: TextView =findViewById(R.id.DateText)
val simpleDateFormat= SimpleDateFormat("yyyy/MM/dd\\n HH:mm", Locale.getDefault()).format(
Date()
)
val currentDateAndTime: String = simpleDateFormat.format(Date())
textView.text = currentDateAndTime
val button = findViewById\<Button\>(R.id.goBackToHome)
button.setOnClickListener{
val intent = Intent(this,MainMenu::class.java)
startActivity(intent)
}
initView()
initRecyclerView()
sqLiteHelper= SQLiteHelper(this)
//Show recycler view
val stdList = sqLiteHelper.getAllStudent()
Log.e("おっけ","${stdList.size}")
adapter?.setOnClickItem {
//購入・使用編集画面に遷移
**`if(it.buyamount > 0){`**
**`}else if (it.useamount > 0){`**
}else{
Toast.makeText(this,"エラーが発生しました",Toast.LENGTH_LONG).show()
}
}
adapter?.addItems(stdList)
adapter?.setOnClickDeleteItem{
deleteStudent(it.id)
}
}
private fun deleteStudent(id:Int){
val builder = AlertDialog.Builder(this)
builder.setMessage("データを削除してよろしいですか")
builder.setCancelable(true)
builder.setNegativeButton("いいえ"){dialog, \_ -\>
dialog.dismiss()
}
builder.setPositiveButton("はい"){dialog, \_ -\>
sqLiteHelper.deleteStudentById(id)
getStudents()
dialog.dismiss()
}
val alert = builder.create()
alert.show()
}
private fun updateStudent(){
val name = edName.text.toString()
val email = edEmail.text.toString()
val buyAmount = edBuyAmount.text.toString().toInt()
val useAmount = edUseAmount.text.toString().toInt()
val reason = edReason.text.toString()
//Check record not changed
if(name == std?.name && email == std?.email && buyAmount == std?.buyamount && useAmount == std?.useamount && reason == std?.reason){
Toast.makeText(this,"データが変更されてない", Toast.LENGTH_SHORT).show()
return
}
if(std == null) return
val std = StudentModel(id=std!!.id,name = name,email = email, buyamount = buyAmount, useamount = useAmount, reason = reason)
val status = sqLiteHelper.updateStudent(std)
if(status \> -1){
clearEditText()
getStudents()
}else{
Toast.makeText(this,"更新失敗した", Toast.LENGTH_SHORT).show()
}
}
private fun getStudents(){
val stdList = sqLiteHelper.getAllStudent()
Log.e("おっけ","${stdList.size}")
adapter?.addItems(stdList)
}
private fun addStudent(){
val name = edName.text.toString()
val email = edEmail.text.toString()
val buyAmount = edBuyAmount.text.toString().toInt()
val useAmount = edUseAmount.text.toString().toInt()
val reason = edReason.text.toString()
if(name.isEmpty()||email.isEmpty()|| buyAmount.toString().isEmpty() ||useAmount.toString().isEmpty() || reason.toString().isEmpty()){
Toast.makeText(this,"データを入力してください", Toast.LENGTH_SHORT).show()
}else{
val std = StudentModel(name = name, email=email, buyamount=buyAmount, useamount=useAmount, reason = reason)
val status = sqLiteHelper.insertStudent(std)
//Check Insert success or not success
if(status \> -2){
Toast.makeText(this,"データを追加しました。", Toast.LENGTH_SHORT).show()
clearEditText()
}else{
Toast.makeText(this,"データが保存されてないようです。", Toast.LENGTH_SHORT).show()
}
}
}
private fun clearEditText(){
edName.setText("")
edEmail.text = ""
edBuyAmount.setText("")
edUseAmount.setText("")
edReason.setText("")
edName.requestFocus()
}
private fun initRecyclerView(){
recyclerView.layoutManager=LinearLayoutManager(this)
adapter = StudentAdapter()
recyclerView.adapter=adapter
}
private fun initView(){
recyclerView=findViewById(R.id.recyclerView)
}
Buy details screen
\`class buyDetailsScreen : AppCompatActivity() {\`
private lateinit var edName: EditText
private lateinit var edEmail: Button
private lateinit var edBuyAmount: EditText
private lateinit var btnUpdate: Button
private lateinit var sqLiteHelper: SQLiteHelper
private lateinit var recyclerView: RecyclerView
private var adapter: StudentAdapter?=null
private var std:StudentModel?= null //Has nothing inside it . I need to get the info from first activity and put here
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_buy_details_screen)
val button = findViewById\<Button\>(R.id.goBackToMain)
button.setOnClickListener{
val intent = Intent(this,allRecordpage::class.java)
startActivity(intent)
}
val button2 = findViewById\<Button\>(R.id.goBacktoMain2)
button2.setOnClickListener{
val intent = Intent(this,allRecordpage::class.java)
startActivity(intent)
}
initView()
initRecyclerView()
sqLiteHelper= SQLiteHelper(this)
//Show recycler view
val stdList = sqLiteHelper.getAllStudent()
Log.e("おっけ","${stdList.size}")
adapter?.addItems(stdList)
edEmail = findViewById(R.id.edEmail)
edEmail.setOnClickListener{
clickDatePicker()
}
**edEmail.text = intent.getStringExtra("date")**
btnUpdate.setOnClickListener{
updateStudent()
val intent = Intent(this,allRecordpage::class.java)
startActivity(intent)
}
}
private fun clickDatePicker() {
val calender = Calendar.getInstance()
val year = calender.get(Calendar.YEAR)
val month = calender.get(Calendar.MONTH)
val day = calender.get(Calendar.DAY_OF_MONTH)
val datepicker = DatePickerDialog(this,
{ view,selectedYear,selectedMonth,selectedDay -\>
val selectedDate = "$selectedYear/${selectedMonth+1}/$selectedDay"
edEmail?.text=selectedDate
},
year,
month,
day
)
datepicker.datePicker.maxDate = System.currentTimeMillis()
datepicker.show()
}
private fun updateStudent(){
val name = edName.text.toString()
val email = edEmail.text.toString()
val buyAmount = edBuyAmount.text.toString().toInt()
//Check record not changed
if(name == std?.name && email == std?.email && buyAmount == std?.buyamount){
Toast.makeText(this,"データが変更されてない", Toast.LENGTH_SHORT).show()
return
}
if(std == null) return
val std = StudentModel(id=std!!.id,name = name,email = email, buyamount = buyAmount )
val status = sqLiteHelper.updateStudent(std)
if(status \> -1){
clearEditText()
getStudents()
}else{
Toast.makeText(this,"更新失敗した", Toast.LENGTH_SHORT).show()
}
}
private fun getStudents(){
val stdList = sqLiteHelper.getAllStudent()
Log.e("おっけ","${stdList.size}")
adapter?.addItems(stdList)
}
private fun clearEditText(){
edName.setText("")
edEmail.text = ""
edBuyAmount.setText(0)
edName.requestFocus()
}
private fun initRecyclerView(){
recyclerView.layoutManager= LinearLayoutManager(this)
adapter = StudentAdapter()
recyclerView.adapter=adapter
}
private fun initView(){
edName = findViewById(R.id.edName)
edEmail = findViewById(R.id.edEmail)
edBuyAmount = findViewById(R.id.edBuyAmount)
btnUpdate=findViewById(R.id.btnUpdate)
recyclerView=findViewById(R.id.recyclerView)
}
I expected to be able to update the std object but the Buy details activity private var std:StudentModel?= null contains nothing . how do i pass std:StudentModel from main activity to buy details activity so i can update/delete the record from SQlite
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
