При переходе в другую активность приложение вылетает и выдаёт в логе ошибку
Создаю своё простенькое приложение в Android studio. Всё было нормально, но в какой-то момент приложение стало вылетать при переходе в другую активность.
Ниже представлены ошибки, которые выдаёт лог:
Mainactivity.kt
:
package com.example.myapplication1
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val but1:Button = findViewById(R.id.buttwork)
val but2:Button = findViewById(R.id.buttobed)
println("theme")
val th = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
//if (th == Configuration.UI_MODE_NIGHT_YES){
//}
but1.setOnClickListener {
val intent = Intent(this@MainActivity, WorkingActivity::class.java)
startActivity(intent)
}
but2.setOnClickListener {
val intent = Intent(this@MainActivity, Obedsacivity::class.java)
startActivity(intent)
}
}
}
Workingactivit.kt
:
package com.example.myapplication1
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.time.LocalDateTime
import kotlin.time.Duration
class WorkingActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_working)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.work)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
//обьявление основных переменных
val b_in:Button = findViewById(R.id.inwork)
val b_out:Button = findViewById(R.id.outwork)
val list_in:ListView = findViewById(R.id.list_inwork)
val list_out:ListView = findViewById(R.id.list_outwork)
val textime:TextView = findViewById(R.id.textClock)
val arr_in:MutableList<String> = mutableListOf()
val arr_out:MutableList<String> = mutableListOf()
val adapter_in = ArrayAdapter(this,android.R.layout.simple_list_item_1,arr_in)
val adapter_out = ArrayAdapter(this,android.R.layout.simple_list_item_1,arr_out)
val text_tw:TextView = findViewById(R.id.text_tw)
val texttitle:TextView = findViewById(R.id.text_time)
list_in.adapter = adapter_in
list_out.adapter = adapter_out
b_out.isEnabled = false
val mdb = Mydatebase.getDb(this)
var ptim:String = ""
val th = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
if (th == Configuration.UI_MODE_NIGHT_YES){
text_tw.setTextColor(ContextCompat.getColor(this,R.color.white))
texttitle.setTextColor(ContextCompat.getColor(this,R.color.white))
}
val nmon = LocalDateTime.now().toString().split("T")[0].split("-")[1]
//nmon = "10"
text_tw.text = "Отработано за месяц "
//сопрограмма
val scope: Deferred<String> = CoroutineScope(Dispatchers.IO).async {
val pp1 = mdb.getDao().getAll()
var ptim1 = Duration.ZERO
for (i in pp1) {
adapter_in.insert(i.inw, 0)
adapter_out.insert(i.outw, 0)
if (i.mon == nmon) {
var pp = i.tw.split(":")
ptim1 = ptim1 + Duration.parse(pp[0]+"h"+pp[1]+"m")
}
}
ptim = ptim1.toString()
if ("h" in ptim){
var ptimm = ptim.split("h")
text_tw.text = "Отработано за месяц " +ptimm[0]+ ptimm[1].replace("m","") + " минут"
}
else {
if ("s" in ptim){ptim = ptim.replace("s","")}
text_tw.text = "Отработано за месяц 0 часов " + ptim.replace("m","") + " минут"
}
return@async ptim
}
runBlocking {
val ptim = scope.await()
}
//
//определение активации кнопок
if (" " in arr_out) {
b_out.isEnabled = true
b_in.isEnabled = false
}
var pp= LocalDateTime.now().toString().split("T")
var pmon = pp[0].split("-")
//кнопка начало работы
b_in.setOnClickListener {
b_out.isEnabled = true
b_in.isEnabled = false
val time_in = textime.text.toString()
adapter_in.insert(time_in,0)
adapter_out.insert(" ",0)
val item = item(null, arr_in[0], " ", " ",pmon[2],pmon[1],pmon[0])
Thread(){
mdb.getDao().insertitem(item)
}.start()
}
//кнопка конца работы
b_out.setOnClickListener {
b_in.isEnabled = true
b_out.isEnabled = false
arr_out[0] = textime.text.toString()
adapter_out.notifyDataSetChanged()
//arr_out[0] = arr_out[0].replace(" ", time_out)
//println(arr_out[0])
var ptime: String = "null"
var pin = arr_in[0].replace(":","h").plus("m")
var pout = arr_out[0].replace(":","h").plus("m")
var tobed = listOf(Duration.parse("12h30m"), Duration.parse("13h30m"))
if (Duration.parse(pin) < tobed[0]) {
if (Duration.parse(pout) > tobed[1]){
ptime = (Duration.parse(pout) - Duration.parse(pin) - (tobed[1]-tobed[0])).toString()
}
else{
ptime = (Duration.parse(pout) - Duration.parse(pin) ).toString()
}
}
else{
ptime = (Duration.parse(pout) - Duration.parse(pin) ).toString()
}
if (ptime.contains("h") == false) {
ptime = "0h" + ptime
}
var ptime1 = ptime.split("h").toMutableList()
//println(ptime1)
ptime1[1] = ptime1[1].replace("m","")
val w = ptime1[0] + ":" + ptime1[1]
val texttoast = "Отработано " + ptime1[0] + " часов " + ptime1[1] + " минут"
Toast.makeText(this, texttoast, Toast.LENGTH_SHORT).show()
// поток для обновления базы данных и счетчик общего времени
var sc = CoroutineScope(Dispatchers.IO).launch {
mdb.getDao().updateitem(arr_in.size,arr_out[0],w)
val pp1 = mdb.getDao().getAll()
var ptim1 = Duration.ZERO
for (i in pp1) {
//adapter_in.insert(i.inw, 0)
if (i.mon == nmon) {
var pp = i.tw.split(":")
ptim1 = ptim1 + Duration.parse(pp[0] + "h" + pp[1] + "m")
}
}
ptim = ptim1.toString()
if ("h" in ptim){
var ptimm = ptim.split("h")
text_tw.text = "Отработано за месяц " +ptimm[0]+" часов"+ ptimm[1].replace("m","") + " минут"
}
else {
text_tw.text = "Отработано за месяц 0 часов " + ptim.replace("m","") + " минут"
}
}
// runBlocking { sc.join() }
}
}
}
Лог:
Failed to execute the transaction: tId:363569632 ClientTransaction{
tId:363569632 transactionItems=[
tId:363569632 LaunchActivityItem{activityToken=android.os.BinderProxy@aa0a3fd,intent=Intent { cmp=com.example.myapplication1/.WorkingActivity },ident=143980030,info=ActivityInfo{51915bd com.example.myapplication1.WorkingActivity},curConfig={1.0 310mcc260mnc [ru_RU,en_US] ldltr sw411dp w411dp h890dp 420dpi nrml long port night finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2337) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.57 fontWeightAdjustment=0},overrideConfig={1.0 310mcc260mnc [ru_RU,en_US] ldltr sw411dp w411dp h890dp 420dpi nrml long port night finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2337) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.2 fontWeightAdjustment=0},deviceId=0,referrer=com.example.myapplication1,procState=2,state=null,persistentState=null,pendingResults=null,pendingNewIntents=null,sceneTransitionInfo=null,profilerInfo=null,assistToken=android.os.BinderProxy@6ed1f26,shareableActivityToken=android.os.BinderProxy@fd80767,activityWindowInfo=ActivityWindowInfo{isEmbedded=false, taskBounds=Rect(0, 0 - 1080, 2400), taskFragmentBounds=Rect(0, 0 - 1080, 2400)}}
tId:363569632 ResumeActivityItem{mActivityToken=android.os.BinderProxy@aa0a3fd,procState=-1,updateProcState=false,isForward=true,shouldSendCompatFakeFocus=false}
tId:363569632 Target activity: com.example.myapplication1.WorkingActivity
tId:363569632 ]
tId:363569632 }
2024-09-27 11:01:32.235 7307-7307 AndroidRuntime com.example.myapplication1 D Shutting down VM
2024-09-27 11:01:32.247 7307-7307 AndroidRuntime com.example.myapplication1 E FATAL EXCEPTION: main
Process: com.example.myapplication1, PID: 7307
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication1/com.example.myapplication1.WorkingActivity}: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4048)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4235)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:112)
at android.app.servertransaction.TransactionExecutor.executeNonLifecycleItem(TransactionExecutor.java:174)
at android.app.servertransaction.TransactionExecutor.executeTransactionItems(TransactionExecutor.java:109)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:81)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2636)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loopOnce(Looper.java:232)
at android.os.Looper.loop(Looper.java:317)
at android.app.ActivityThread.main(ActivityThread.java:8705)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:580)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:886)
Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.Collections$SingletonList.get(Collections.java:5260)
at com.example.myapplication1.WorkingActivity$onCreate$scope$1.invokeSuspend(WorkingActivity.kt:73)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:104)
at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:111)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:99)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:811)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:715)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:702)
2024-09-27 11:01:32.277 7307-7307 Process com.example.myapplication1 I Sending signal. PID: 7307 SIG: 9
Можете подсказать, в чём проблема?