I am currently writing code in Android Studio to build a system that processes payments when a QR code is scanned. I have encountered an error saying "LifecycleOwners must call register before they are STARTED" while the current state is STARTED. It seems to be related to the lifecycle, and I would like to request assistance on how to modify the code to resolve the issue.
I have tried modifying various code related to the lifecycle, but I continue to encounter errors related to the lifecycle component.
package com.project.tosspayment
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private lateinit var paymentWidget: PaymentWidget
lateinit var customDialogBinding: CustomDialogBinding
private val REQUEST_CAMERA_PERMISSION = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
onResume()
}
override fun onResume() {
super.onResume()
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA),REQUEST_CAMERA_PERMISSION)
} else {
openScanner()
}
}
private fun openScanner(){
val QrScan = IntentIntegrator(this)
QrScan.setCameraId(0) //후방카메라 사용
QrScan.setBeepEnabled(false) //스캔할때 소리 끄기
QrScan.addExtra("PROMPT_MESSAGE","QR코드를 스캔해주세요")
QrScan.setOrientationLocked(false)
QrScan.initiateScan()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when(requestCode){
REQUEST_CAMERA_PERMISSION -> {
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openScanner()
}else{
Toast.makeText(this,"카메라를 허용해 주세요",Toast.LENGTH_LONG).show()
}
return
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.w("zio","TossScanner")
val result:IntentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode,data)
val scannerData = result.contents
Log.w("zio","scannerData: $scannerData")
if(scannerData == null){
Toast.makeText(this,"QR코드를 다시 스캔해주세요!!!!!!!!!",Toast.LENGTH_LONG).show()
return
}
if(requestCode == IntentIntegrator.REQUEST_CODE && resultCode == Activity.RESULT_OK){
val pattern =
Pattern.compile("\\{\"orderId\":\"([A-Za-z0-9]+)\",\"price\":(\\d+),\"orderItem\":\"([^,]+)\",\"customerKey\":\"([A-Za-z0-9]+)\"\\}")
val matcher = pattern.matcher(scannerData ?: "")
Log.w("zio","pattern : $pattern")
Log.w("zio","matcher: $matcher")
if (matcher.find()) {
val orderId = matcher.group(1)
val price = matcher.group(2).toDouble()
val orderItem = matcher.group(3)
val customerKey = matcher.group(4)
//위젯 생성하기 위해 생성
val methodWidget = binding.paymentWidget
val agreement = binding.agreementWidget
//위젯에 값전달
paymentWidget = PaymentWidget(
this@MainActivity,
getString(R.string.payment_ClientKey),
customerKey //PaymentWidget.ANONYMOUS
)
Log.w("zio","에러: $paymentWidget")
//가격과 주문번호
paymentWidget.renderPaymentMethods(
method = methodWidget,
amount = price
)
//이용약관 위젯
paymentWidget.renderAgreement(agreement)
//결제위젯 view
PaymentMethod(this, null)
//이용약관 view
Agreement(this, null)
binding.payAccess.setOnClickListener {
customDialogBinding = CustomDialogBinding.inflate(layoutInflater)
paymentWidget.requestPayment(
paymentInfo = PaymentMethod.PaymentInfo(
orderId = orderId,
orderName = orderItem
),
paymentCallback = object : PaymentCallback,
com.tosspayments.paymentsdk.model.PaymentCallback {
override fun onPaymentSuccess(success: TossPaymentResult.Success) {
val client = OkHttpClient()
val mediaType = MediaType.parse("application/json")
val qrBody = RequestBody.create(
mediaType,
"{\"paymentKey\":\"${success.paymentKey}\",\"amount\":$price,\"orderId\":\"$orderId\",\"customerName\":\"$customerKey\",\"orderName\":\"$orderItem\"}"
)
Log.w("zio", "paymentKey: ${success.paymentKey}")
val request = Request.Builder()
.url("https://api.tosspayments.com/v1/payments/confirm")
.header(
"Authorization",
"Basic dGVzdF9za19aT1J6ZE1hcU4zd015a1p5bDdOcjVBa1lYUUd3Og=="
)
.header("Content-Type", "application/json")
.post(qrBody)
.build()
client.newCall(request).enqueue(object : okhttp3.Callback {
override fun onResponse(call: Call, response: Response) {
runOnUiThread {
if (response.isSuccessful) {
Log.w("zio", "결제인증 성공")
dialog(
"결제가 되었습니다.",
"결제요청 결과",
customDialogBinding.dialogButton.setOnClickListener {
val successIntent =
Intent(this@MainActivity,ReceiptActivity::class.java)
startActivity(successIntent)
})
} else {
Log.w(
"zio",
"결제인증 재 시작: $response, orderid: $orderId"
)
}
}
}
override fun onFailure(call: okhttp3.Call, e: IOException) {
runOnUiThread {
Log.w("zio", "결제인증 실패")
dialog(
"결제가 실패돼었습니다..",
"결제요청 결과",
customDialogBinding.dialogButton.setOnClickListener {
val failIntent =
Intent(this@MainActivity,PaymentActivity::class.java)
startActivity(failIntent)
})
}
}
})
}
override fun onPaymentFailed(fail: TossPaymentResult.Fail) {
Log.d("zio", "결제 실패 !")
dialog(
"결제가 실패돼었습니다..",
"결제요청 결과",
customDialogBinding.dialogButton.setOnClickListener {
val failIntent =
Intent(this@MainActivity, PaymentActivity::class.java)
startActivity(failIntent)
})
}
}
)
}
} else {
Log.w("zio","No match found")
}
}else{
Toast.makeText(this,"QR코드를 다시 스캔해주세요",Toast.LENGTH_LONG).show()
return
}
}
fun dialog(message:String, title:String, OnClickListener: Unit) {
val alertDialog = AlertDialog.Builder(this)
.setView(customDialogBinding.customDialog)
.create()
customDialogBinding.dialogTitle.text = title
customDialogBinding.dialogMessage.text = message
customDialogBinding.dialogButton.text = "확인"
customDialogBinding.dialogMessage.visibility = View.VISIBLE
customDialogBinding.dialogButton.visibility = View.VISIBLE
alertDialog.show()
}
}