i am new to kotlin i was trying to make a bmi app from a course i binded the view and every thing is running fine but i think my onclicklistner is not working
below is my code can anyone check and see what is wrong
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if(binding.weightEditText.text.isNotEmpty() && binding.heightEditText.text.isNotEmpty()) {
binding.calculateButton.setOnClickListener {
val weight = binding.weightEditText.text.toString().toFloat()
val height = binding.heightEditText.text.toString().toFloat()
val myBMI = weight / (height * height)
binding.bmiValue.text = myBMI.toString()
if (myBMI < 18.5) {
binding.imageView.setImageResource(R.drawable.underweight)
} else if (myBMI >= 18.5 && myBMI < 24.9) {
binding.imageView.setImageResource(R.drawable.healthy)
} else if (myBMI >= 24.9 && myBMI < 29.9) {
binding.imageView.setImageResource(R.drawable.overweight)
} else if(myBMI>29.9) {
binding.imageView.setImageResource(R.drawable.obesity)
}
}
}
else{
Toast.makeText(this, "Add the asked field", Toast.LENGTH_SHORT).show()
}
}
}
When your activity is created, your edit text is probably empty. so callback of click not set for your button.
You need to check the editText into the clickListener callback.
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.calculateButton.setOnClickListener {
if(binding.weightEditText.text.isNotEmpty() && binding.heightEditText.text.isNotEmpty()) {
val weight = binding.weightEditText.text.toString().toFloat()
val height = binding.heightEditText.text.toString().toFloat()
val myBMI = weight / (height * height)
binding.bmiValue.text = myBMI.toString()
if (myBMI < 18.5) {
binding.imageView.setImageResource(R.drawable.underweight)
} else if (myBMI >= 18.5 && myBMI < 24.9) {
binding.imageView.setImageResource(R.drawable.healthy)
} else if (myBMI >= 24.9 && myBMI < 29.9) {
binding.imageView.setImageResource(R.drawable.overweight)
} else if(myBMI>29.9) {
binding.imageView.setImageResource(R.drawable.obesity)
}
}else{
Toast.makeText(this, "Add the asked field", Toast.LENGTH_SHORT).show()
}
}
}
}
Related
I have a simple android app, which is changing text and color of TextView depends on how much passengers i added. I want to create a sealed class for each state.
Here is the code of the current app:
class MainActivity : AppCompatActivity() {
private var counter = 0
private val maxPassengers = 50
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.seats.text = counter.toString()
binding.minusButton.setOnClickListener {
counter -= 1
checkAndSwitchState(counter)
}
binding.plusButton.setOnClickListener {
counter += 1
checkAndSwitchState(counter)
}
binding.resetButton.setOnClickListener {
counter = 0
it.visibility = View.GONE
checkAndSwitchState(counter)
}
}
private fun checkAndSwitchState(counter: Int) {
if (counter == 0) {
binding.minusButton.isEnabled = false
binding.textView.text = binding.textView.context.getText(R.string.green_text)
binding.textView.setTextColor(Color.parseColor("#00FF00"))
binding.seats.text = counter.toString()
}
if (counter in 1 until maxPassengers) {
binding.minusButton.isEnabled = true
binding.textView.text = "Осталось мест: " + "${maxPassengers - counter}"
binding.textView.setTextColor(Color.parseColor("#0000FF"))
binding.seats.text = counter.toString()
}
if (counter >= maxPassengers) {
binding.resetButton.visibility = View.VISIBLE
binding.textView.text = binding.textView.context.getText(R.string.red_text)
binding.textView.setTextColor(Color.parseColor("#FF0000"))
binding.seats.text = counter.toString()
}
}
}
So the question is how can i use binding outside MainActivity in sealed class
I'm coding a quiz app, the main problem here is when an option is clicked question is changed I want that if option is wrong question remain same option become red..
class Level1 : AppCompatActivity(),View.OnClickListener {
lateinit var binding: ActivityLevel1Binding
var mQuestionList=QuestionsAndAnswer.getQuestions()
lateinit var imageView: ImageView
private var mCurrentPosition: Int = 0 // this question in model class//
private var mSelectedOptionPostion: Int = 0 // this is current option where user clicked for answer///
lateinit var progress:ProgressBar
private lateinit var tvOptionOne:TextView
private lateinit var tvOptionTwo:TextView
private lateinit var tvOptionThree:TextView
private lateinit var tvOptionFour:TextView
lateinit var progressBar: ProgressBar
lateinit var tvProgressBar: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLevel1Binding.inflate(layoutInflater)
setContentView(binding.root)
mQuestionList=QuestionsAndAnswer.getQuestions()
setQuestion()
binding.tvOptionFour.setOnClickListener(this)
binding.tvOptionThree.setOnClickListener (this)
binding.tvOptionTwo.setOnClickListener (this)
binding.tvOptionOne.setOnClickListener (this)
binding.progressBar
}
private fun setQuestion() {
setDefault()
imageView=binding.quesImage
binding.apply {
val questions= mQuestionList[mCurrentPosition]
progressBar.progress = mCurrentPosition
tvProgressBar.text = "$mCurrentPosition" + "/" + progressBar.max
binding.quesImage.setImageResource(questions.image)
tvOptionOne.text = questions.optionOne
tvOptionTwo.text = questions.optionTwo
tvOptionThree.text = questions.optionThree
tvOptionFour.text = questions.optionFour
}
}
override fun onClick(v: View?) {
when(v?.id){
R.id.tvOptionOne->{
Selected(1,binding.tvOptionOne)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
val questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
}
else {
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
R.id.tvOptionTwo->{
Selected(2,binding.tvOptionTwo)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
val questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
mCurrentPosition
Toast.makeText(this,"wrong answer",Toast.LENGTH_SHORT).show()
}
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
R.id.tvOptionThree->{
Selected(3,binding.tvOptionThree)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
val questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
Toast.makeText(this,"wrong answer",Toast.LENGTH_SHORT).show()
}
else{
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
// at last question on wrong answer click no action happens like no wrong answer drawable file is called //
R.id.tvOptionFour->{
Selected(4,binding.tvOptionFour)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
var questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
}
else {
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
}
}
// here answers are maatched //
private fun AnswerView(answer: Int, drawAbleView: Int) {
when (answer) {
1 -> {
binding.tvOptionOne.background = ContextCompat.getDrawable(this, drawAbleView)
}
2 -> {
binding.tvOptionTwo.background = ContextCompat.getDrawable(this, drawAbleView)
}
3 -> {
binding.tvOptionThree.background = ContextCompat.getDrawable(this, drawAbleView)
}
4 -> {
binding.tvOptionFour.background = ContextCompat.getDrawable(this, drawAbleView)
}
}
}
private fun Selected(selected: Int, tv: TextView) {
setDefault()
mSelectedOptionPostion = selected
tv.setTextColor(Color.parseColor("#FF03DAC5"))
tv.setTypeface(tv.typeface, Typeface.BOLD)
tv.background = ContextCompat.getDrawable(this,
R.drawable.selected_tex_view)
}
private fun setDefault() {
val options = ArrayList<TextView>()
options.add(0, binding.tvOptionOne)
options.add(1, binding.tvOptionTwo)
options.add(2, binding.tvOptionThree)
options.add(3, binding.tvOptionFour)
for (option in options) {
option.setTextColor(Color.parseColor("#FF03DAC5"))
option.typeface = Typeface.DEFAULT
option.background = ContextCompat.getDrawable(this, R.drawable.round_text_view)
}
}
}
Try to change your onClick logic like this:
Note that I've declared a couple of methods to avoid code duplication
override fun onClick(v: View?) {
when(v?.id){
R.id.tvOptionOne->{
Selected(1, binding.tvOptionOne)
if(mCurrentPosition < mQuestionList.size){
setQuestion()
checkQuestion()
}
else startScoreActivity()
}
R.id.tvOptionTwo->{
Selected(2,binding.tvOptionTwo)
if(mCurrentPosition < mQuestionList.size){
setQuestion()
checkQuestion()
}
else startScoreActivity()
}
R.id.tvOptionThree->{
Selected(3,binding.tvOptionThree)
if( mCurrentPosition < mQuestionList.size){
setQuestion()
checkQuestion()
}
else startScoreActivity()
}
R.id.tvOptionFour->{
Selected(4,binding.tvOptionFour)
if( mCurrentPosition < mQuestionList.size) {
setQuestion()
}
else startScoreActivity()
}
}
}
private fun checkQuestion() {
var questions=mQuestionList?.get(mCurrentPosition)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
}
else {
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
mCurrentPosition++
}
}
private fun startScoreActivity() {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
I guess you should try moving
if (questions?.correctAnswer!=mSelectedOptionPostion) {
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
} else {
mCurrentPosition ++
setQuestion()
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
I have been stuck on this for over 2 weeks. I tried everything and search everywhere but nothing worked.
I have an android app with sqlite database.
I made a recyclerview with a custom adapter because every item in the recyclerview consists of 80 Textviews.
I want to print every row of the recyclerview in a seperate page but in the same document. when I try to print the rows of recyclerview, I get only the visible rows on the screen which is the first and the second row only while my recyclerview consists of at least 10 to 20 rows. I'm using the latest version of android studio and Kotlin.
here is what I have so far
this is my custom Adapter
class BianProductsAdapter(mCtx: Context,val bianproducts: ArrayList<LV_BProducts>) : RecyclerView.Adapter<BianProductsAdapter.ViewHolder>() {
val mCtx = mCtx
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val lbpid = itemView.bianproductid
val lbpproductname = itemView.bianproductname
val lbpproductunit = itemView.bianproductunit
val lbpproductquantity = itemView.bianproductquantity
val lbpproductoriginalprice = itemView.bianproductoriginalprice
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BianProductsAdapter.ViewHolder {
val v : View= LayoutInflater.from(parent.context).inflate(R.layout.lo_b_products,parent,false)
return BianProductsAdapter.ViewHolder(v)
}
override fun onBindViewHolder(holder: BianProductsAdapter.ViewHolder, position: Int) {
val df = DecimalFormat("###,###,##0.00")
val bianproduct : LV_BProducts = bianproducts[position]
holder.lbpid.text = bianproduct.lvbp_id.toString()
holder.lbpproductname.text = bianproduct.lvbp_product_name.toString()
holder.lbpproductunit.text = bianproduct.lvbp_unit.toString()
holder.lbpproductquantity.text = bianproduct.lvbp_quantity.toString()
holder.lbpproductoriginalprice.text = "$"+ df.format(bianproduct.lvbp_original_price.toFloat())
}
override fun getItemCount(): Int {
return bianproducts.size
}
}
and this is Activity.kt`
class BProductsActivity : AppCompatActivity() {
inner class MyPrintDocumentAdapter(private var context: Context)
: PrintDocumentAdapter() {
private var pageHeight: Int = 0
private var pageWidth: Int = 0
private var myPdfDocument: PdfDocument? = null
private fun drawPage(
page: PdfDocument.Page,
pagenumber: Int
) {
var pagenum = pagenumber
val canvas = page.canvas
pagenum++
val titleBaseLine = 72
val leftMargin = 54
val paint = Paint()
paint.color = Color.BLACK
val pageInfo = page.info
}
private fun pageInRange(pageRanges: Array<PageRange>, page: Int): Boolean {
for (i in pageRanges.indices) {
if (page >= pageRanges[i].start && page <= pageRanges[i].end)
return true
}
return false
}
override fun onLayout(
oldAttributes: PrintAttributes?,
newAttributes: PrintAttributes?,
cancellationSignal: android.os.CancellationSignal?,
callback: LayoutResultCallback?,
extras: Bundle?
) {
myPdfDocument = newAttributes?.let { PrintedPdfDocument(context, it) }
val height = newAttributes?.mediaSize?.heightMils
val width = newAttributes?.mediaSize?.heightMils
height?.let {
pageHeight = it / 1000 * 72
}
width?.let {
pageWidth = it / 1000 * 72
}
if (cancellationSignal != null) {
if (cancellationSignal.isCanceled) {
if (callback != null) {
callback.onLayoutCancelled()
}
return
}
}
if (totalpages > 0) {
val builder =
PrintDocumentInfo.Builder("print_output.pdf").setContentType(
PrintDocumentInfo.CONTENT_TYPE_DOCUMENT
)
.setPageCount(totalpages)
val info = builder.build()
if (callback != null) {
callback.onLayoutFinished(info, true)
}
} else {
if (callback != null) {
callback.onLayoutFailed("Page count is zero.")
}
}
}
override fun onWrite(
pages: Array<out PageRange>?,
destination: ParcelFileDescriptor?,
cancellationSignal: android.os.CancellationSignal?,
callback: WriteResultCallback?
) {
for (i in 0 until totalpages) {
if (pageInRange(pages as Array<PageRange>, i)) {
val newPage = PdfDocument.PageInfo.Builder(
pageWidth,
pageHeight, i
).create()
if (cancellationSignal != null) {
if (cancellationSignal.isCanceled) {
if (callback != null) {
callback.onWriteCancelled()
}
myPdfDocument?.close()
myPdfDocument = null
return
}
}
val page = myPdfDocument?.startPage(newPage)
val content: View = mybprv.get(i) //mybprv is the ID of my recyclerview
val measureWidth = View.MeasureSpec.makeMeasureSpec(
page!!.canvas.width,
View.MeasureSpec.EXACTLY
)
val measuredHeight = View.MeasureSpec.makeMeasureSpec(
page.canvas.height,
View.MeasureSpec.EXACTLY
)
content.measure(measureWidth, measuredHeight)
content.layout(0, 0, page.canvas.width, page.canvas.height)
if (page != null) {
content.draw(page.canvas)
}
myPdfDocument?.finishPage(page)
}
}
try {
if (destination != null) {
myPdfDocument?.writeTo(
FileOutputStream(
destination.fileDescriptor
)
)
}
} catch (e: IOException) {
if (callback != null) {
callback.onWriteFailed(e.toString())
}
return
} finally {
myPdfDocument?.close()
myPdfDocument = null
}
if (callback != null) {
callback.onWriteFinished(pages)
}
}
}
fun printDocument(view: View) {
val printManager = this.getSystemService(Context.PRINT_SERVICE) as PrintManager
val jobName = this.getString(R.string.app_name) + " Document"
printManager.print(jobName, MyPrintDocumentAdapter(this), null)
}
companion object{
lateinit var bpdbHandler: DBHandler
private var totalpages =0
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_b_products)
bpdbHandler = DBHandler(this,null,null,1)
populateList()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
//return super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.addbianproduct,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId==R.id.bainproductpage){
printDocument(mybprv) // mybprv is the id of my recyclerview
}
return super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
populateList()
}
private fun populateList() {
val productslist : ArrayList<LV_BProducts>? = intent.getStringExtra("bid")?.let { bpdbHandler.getBianProducts(this, it) }
val adapter = productslist?.let { BianProductsAdapter(this, it) }
val rv : RecyclerView = findViewById(R.id.mybprv)
rv.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL,false)
rv.adapter = adapter
rv.isNestedScrollingEnabled = false
if (productslist != null) {
totalpages = productslist.size
}
}
}
I get the exact records I want from the query and I can show all these records data in the recyclerview. My only problem is printing the recyclerview.
the number of pages printed = the number of rows returned by my query = the number of rows in my recyclerview
However, only visible rows which are row 1 and 2 get printed and the remaining pages are either a repetation of row 2 or empty
All your help is highly appreciated.
P.S: I know my code looks messy because it is a mix of two weeks searching and applying solutions from multiple sources until I got stuck where I am now.
Trying to show two Toasts with some info, but one of them isn't showing up.
The points of interest in the code below are functions showScore() and checkAnswer(). The first one doesn't show up its Toast, the second one does. The project builds successfully and the app is working on my phone (Android 9, aarch64).
I just started learning Android. Maybe it's something stupid simple, but I can't get the reason why it's not working.
class MainActivity : AppCompatActivity() {
private lateinit var trueButton: Button
private lateinit var falseButton: Button
private lateinit var nextButton: ImageButton
private lateinit var prevButton: ImageButton
private lateinit var questionTextView: TextView
private val questionBank = listOf(
Question(R.string.question_australia, true),
Question(R.string.question_oceans, true),
Question(R.string.question_mideast, false),
Question(R.string.question_africa, false),
Question(R.string.question_americas, true),
Question(R.string.question_asia, true)
)
private val answers = mutableMapOf<Question, Boolean>()
private var currentIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
trueButton = findViewById(R.id.true_button)
falseButton = findViewById(R.id.false_button)
nextButton = findViewById(R.id.next_button)
prevButton = findViewById(R.id.prev_button)
questionTextView = findViewById(R.id.question_text_view)
trueButton.setOnClickListener { view: View ->
checkAnswer(true)
}
falseButton.setOnClickListener { view: View ->
checkAnswer(false)
}
nextButton.setOnClickListener {
currentIndex = (currentIndex + 1) % questionBank.size
updateQuestion()
checkIfAnswered()
}
prevButton.setOnClickListener {
currentIndex = if (currentIndex > 0) (currentIndex - 1) else (questionBank.size - 1)
updateQuestion()
checkIfAnswered()
}
questionTextView.setOnClickListener {
currentIndex = (currentIndex + 1) % questionBank.size
updateQuestion()
checkIfAnswered()
}
updateQuestion()
}
private fun updateQuestion() {
val questionTextResId = questionBank[currentIndex].textResId
questionTextView.setText(questionTextResId)
}
private fun checkAnswer(userAnswer: Boolean) {
val question = questionBank[currentIndex]
val correctAnswer = question.answer
if (!answers.containsKey(question)) {
answers[question] = userAnswer
falseButton.isEnabled = false
trueButton.isEnabled = false
if (answers.size == questionBank.size) {
showScore()
}
} else {
return
}
val messageResId = if (userAnswer == correctAnswer) {
R.string.correct_toast
} else {
R.string.incorrect_toast
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show()
}
private fun checkIfAnswered() {
if (answers.containsKey(questionBank[currentIndex])) {
falseButton.isEnabled = false
trueButton.isEnabled = false
} else {
falseButton.isEnabled = true
trueButton.isEnabled = true
}
}
private fun showScore() {
var score = 0
answers.forEach {
if (it.key.answer == it.value) {
score += 1
}
}
val toastText = "You answered $score of ${questionBank.size}"
Toast.makeText(this, toastText, Toast.LENGTH_SHORT).show()
}
}
UDP: Tried to run on my friend's phone (Android 9, aarch64) and faced the same issue.
Thanks to one Android-related chat, I found the problem. The problem is that one Toast appears on top of another one. Generally, it's a bad idea to use Toasts this way. If you have a similar problem, consider using Snackbar.
I'm basically making a simple calculator app using Kotlin. I'm very new to programming so I'm not familiar with Java either.
Basically the app runs and I'm also attaching a screenshot of the App's layout along with the code on MainActivity. Everything works fine except the clear button. Ideally, I want the clear button to reset the value on the 1st widget(results widget) and let me start a new calculation. Like how a AC button works on a regular calculator. However, all it does is clear the value. It doesn't clear the calculation. When I select the next calculation it still adds/subtracts/multiplies/divides to the previous value that's already there in the results widget. It doesn't let me start a new calculation like how I would be able to do if I pressed AC on a regular calculator.
Hope what i'm saying makes sense. Please tell me how can I make this work. And again, I'm very new to programming so would really really appreciate it if someone can help me.
package academy.learnprogramming.calculator
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
private const val TAG = "MainActivity"
private const val STATE_PENDING_OPERATION = "PendingOperation"
private const val STATE_OPERAND1 = "Operand1"
private const val STATE_OPERAND1_STORED = "Operand1_Stored"
class MainActivity : AppCompatActivity() {
private var operand1: Double? = null
private var operand2: Double = 0.0
private var pendingOperation = "="
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listener = View.OnClickListener { v ->
val b = v as Button
newNumber.append(b.text)
}
button0.setOnClickListener(listener)
button1.setOnClickListener(listener)
button2.setOnClickListener(listener)
button3.setOnClickListener(listener)
button4.setOnClickListener(listener)
button5.setOnClickListener(listener)
button6.setOnClickListener(listener)
button7.setOnClickListener(listener)
button8.setOnClickListener(listener)
button9.setOnClickListener(listener)
buttonDot.setOnClickListener(listener)
val opListener = View.OnClickListener { v ->
val op = (v as Button).text.toString()
try {
val value = newNumber.text.toString().toDouble()
performOperation(value, op)
} catch (e: NumberFormatException) {
newNumber.setText("")
}
pendingOperation = op
operation.text = pendingOperation
}
buttonEquals.setOnClickListener(opListener)
buttonDivide.setOnClickListener(opListener)
buttonMultiply.setOnClickListener(opListener)
buttonMinus.setOnClickListener(opListener)
buttonPlus.setOnClickListener(opListener)
buttonNegative.setOnClickListener { view ->
val value = newNumber.text.toString()
if (value.isEmpty()) {
newNumber.setText("-")
} else {
try {
var doubleValue = value.toDouble()
doubleValue *= -1
newNumber.setText(doubleValue.toString())
} catch (e: NumberFormatException) {
newNumber.setText("")
}
}
}
val value = newNumber.text.toString()
buttonClear.setOnClickListener { view ->
val value = 0
if (value == 0){
result.setText("")
}
}
}
private fun performOperation(value: Double, operation: String) {
if (operand1 == null) {
operand1 = value
} else {
operand2 = value
if (pendingOperation == "=") {
pendingOperation = operation
}
when (pendingOperation) {
"=" -> operand1 =
operand2
"/" -> if (operand2 == 0.0) {
operand1 = Double.NaN
} else {
operand1 =
operand1!! / operand2
}
"*" -> operand1 = operand1!! * operand2
"-" -> operand1 = operand1!! - operand2
"+" -> operand1 = operand1!! + operand2
}
}
result.setText(operand1.toString())
newNumber.setText("")
}
override fun onSaveInstanceState(outState: Bundle) {
Log.d(TAG, "onSaveInstanceState: Called")
super.onSaveInstanceState(outState)
if (operand1 != null) {
outState.putDouble(
STATE_OPERAND1,
operand1!!
)
outState.putBoolean(
STATE_OPERAND1_STORED,
true
)
}
outState.putString(STATE_PENDING_OPERATION, pendingOperation)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
if (savedInstanceState.getBoolean(
STATE_OPERAND1_STORED,
false
)
) {
operand1 = savedInstanceState.getDouble(STATE_OPERAND1)
} else {
operand1 = null
}
pendingOperation = savedInstanceState.getString(STATE_PENDING_OPERATION, "=")
operation.text = pendingOperation
}
}
Try resetting the values of operand1 and operand2
buttonClear.setOnClickListener { view ->
val value = 0
operand1 = null
operand2 = 0.0
if (value == 0){
result.setText("")
}
}