Saving a variable when exiting an application - android

I am really new to Android Studio(I just started yesterday) and I'm coding a sort of clicker game(in XML and kotlin).
I wanted the click counter (which is in a textview with a text at the begining) to save when leaving the app and loading when launching. I looked up savepreferences but I don't really understand how it works .. Could you guys help me please ?
`class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
var mCounter = 0
var txv = findViewById<TextView>(R.id.tx)
one.setOnClickListener {
//Play sound when click
mp.start()
//Increment click counter
mCounter++
txv.text = "Fixed mistakes: " + mCounter.toString()
}
}
}`
Any help is welcomed :)
EDIT: I posted some code that i did with savedpreferences but it is not fully functionnal. I would gladly appreciate some help ^^
EDIT V2: look at the comments for the solution

EDIT V2: I did it, here is the code
`class MainActivity : AppCompatActivity() {
//Counter lateinit initialisation
var mCounter by Delegates.notNull<Int>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Load la sauvegarde
loadData()
val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
var txv = findViewById<TextView>(R.id.tx)
//ON CLICK
one.setOnClickListener {
//Play le son quand on clique
mp.start()
//Compteur de click
mCounter++
txv.text = "Fixed mistakes: $mCounter"
saveData()
}
}
private fun saveData() {
val sharedPreferences = getSharedPreferences("sharedPrefs" , 0)
val editor = sharedPreferences.edit()
editor.putInt("INT_KEY", mCounter)
editor.commit()
}
private fun loadData() {
val sharedPreferences = getSharedPreferences("sharedPrefs" , 0)
mCounter = sharedPreferences.getInt("INT_KEY", 0)
}
}`

Related

Kotlin App Keeps crashing immediately when running

I am very new to programming in general and I have just started coding in Kotlin in Android Studio. I'm trying to build a simple "Check if number is even or odd" app but I'm not sure where I'm going wrong.
My app crashes immediately when I start it up on the emulator.
class MainActivity : AppCompatActivity() {
private lateinit var enternumber : EditText
private lateinit var button: Button
private lateinit var output: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
enternumber = findViewById(R.id.et_number)
button = findViewById(R.id.btn_click)
output = findViewById(R.id.tv_output)
val enternum: Int = enternumber.text.toString().toInt()
button.setOnClickListener {
if (enternum % 2 == 0)
output.text = ("Number is even")
else
output.text = ("Number is odd")
}
}
}
Any help is greatly appreciated.
First, learn to use the logcat to get helpful exception stacktraces for problem diagnosis. Unfortunately MyApp has stopped. How can I solve this?
One problem here is obvious. Move the
val enternum: Int = enternumber.text.toString().toInt()
inside the onclick listener. At onCreate() phase there's no content in the edittext and toInt() will surely fail. Upon click there might be a number.
Your app keeps crashing due to this:
val enternum: Int = enternumber.text.toString().toInt()
You have to create two number vals. One to display as a String, and one to use as an Int in your if statement that is combined with the String.
Here is some code that will accomplish what you are trying to do. I put it into a function just to make it more readable:
class MainActivity : AppCompatActivity() {
private lateinit var enternumber: EditText
private lateinit var button: Button
private lateinit var output: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.btn_click)
output = findViewById(R.id.tv_output)
button.setOnClickListener {
getEvenOrOdd()
}
}
fun getEvenOrOdd() {
enternumber = findViewById(R.id.et_number)
val displayNumber = enternumber.text.toString()
val newNum = displayNumber.toInt()
val even = "Number is even"
val odd = "Number is odd"
if (newNum % 2 == 0) {
output.text = even
} else {
output.text = odd
}
}
}

Why is the Android onCreate() method not called when the AVD is rotated?

My AndroidManifest.xml does not include anything that would cause this (that I know of).
I.e. it does not include:
android:configChanges="orientation"
Android Version: Chipmunk 2021.2.1 Patch 1
class MainActivity : AppCompatActivity() {
internal lateinit var tapMeButton: Button
internal lateinit var gameScoreTextView: TextView
internal lateinit var timeLeftTextView: TextView
internal var score: Int = 0
internal var gameStarted = false
internal lateinit var countDownTimer: CountDownTimer
internal val initialCountDown: Long = 5000
internal val countDownInterval: Long = 1000
companion object {
private val TAG = MainActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "onCreate called. Score is $score")
tapMeButton = findViewById(R.id.tapMeButton)
gameScoreTextView = findViewById(R.id.gameScoreTextView)
timeLeftTextView = findViewById(R.id.timeLeftTextView)
tapMeButton.setOnClickListener { view ->
if (!gameStarted) {
startGame()
}
incrementScore()
}
resetGame()
}
It's hard to help you without seeing your code. But check that is this line available in your code.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Maybe be you don't activate rotation in the top panel of your simulator.

Can't use SharedPreferences in intended activity

There are two classes MainActivity and PickTimeForNotif in my project. In MainActivity getSharedPreferences works just fine, i can save my data and get it back. In PickTimeForNotif, however, the same method seems to do nothing.
Here's my simplified MainActivity class:
class MainActivity : AppCompatActivity(), ChangeCupDialogFragment.StringListener {
#SuppressLint("SetTextI18n")
//this is variable i'm saving
private var drankToday = 0
//function in which i save my value to SharedPreferences
private fun saveWaterCountToInternalStorage(clickCounter: Int) {
val sharedPref = this.getSharedPreferences("something", Context.MODE_PRIVATE)
with (sharedPref.edit()){
putInt(getString(R.string.clickCount), clickCounter)
apply()
}
}
//and here i get it from there
private fun loadWaterCountToInternalStorage(): Int {
val sharedPref = this.getSharedPreferences("something", Context.MODE_PRIVATE)
return sharedPref.getInt(getString(R.string.clickCount), drankToday)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
val setupNotifButton = findViewById<Button>(R.id.setupNotifButton)
setupNotifButton.setOnClickListener{
val notifIntent = Intent(applicationContext, PickTimeForNotif::class.java)
startActivity(notifIntent)
}
}
}
In setOnClickListener i intend my second activity PickTimeForNotif, here it is.
class PickTimeForNotif: AppCompatActivity(), TimePickerFragment.OnCompleteListener {
val APP_PREFERENCES = "settings"
private val SAVED_FROM_HOUR = "SetFromHour"
private var FROM_HOUR = 99
private fun saveTimeToInternalStorage(prefName1: String, Hour:Int) {
val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
with (sharedPref.edit()){
putInt(prefName1, Hour)
apply()
}
}
private fun loadTimeFromInternalStorage() {
val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
if (sharedPref.contains(APP_PREFERENCES)) {
sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.pick_time_activity)
saveTimeToInternalStorage(SAVED_FROM_HOUR, 1)
loadTimeFromInternalStorage()
Toast.makeText(applicationContext,"$FROM_HOUR", Toast.LENGTH_SHORT).show()
}
}
In the code above i'm trying to set value (1 for example ) to a SAVED_FROM_HOUR key and then get it back and assign to FROM_HOUR variable. However, the Toast shows 99, which means that new data wasn't loaded properly. I tried putting all code from loadTimeFromInternalStorage and saveTimeToInternalStorage to onCreate, but the result is same.
I also tried checking if the Preferences file exists after i call getSharedPreferences with
if (sharedPref.contains(APP_PREFERENCES))
but it does not.
So i'm asking to explain what am i doing wrong and why i can save the data in my MainActivity, but not in the second one. Thanks alot to anyone in advance!!
In loadTimeFromInternalStorage(), you are fetching the value but not assigning to variable like this:
private fun loadTimeFromInternalStorage() {
val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
if (sharedPref.contains(APP_PREFERENCES)) {
FROM_HOUR = sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR)
}
}
Also, in this line FROM_HOUR = sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR), the last parameter in getInt() method is the default value so you should make another constant for it or supply it 0.

How can I fix this? cant put setError to my editText

I make my first android app with Android Studio, and now I want to make a setError on my editText, but I cant, I only can put a toast
here is my code:
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 { calculateTip() }
}
private fun calculateTip() {
val stringInTextField = binding.costOfProduct.text.toString()
val stringInTextField1 = binding.amountOfProduct.text.toString()
if (stringInTextField.isEmpty()) {
Toast.makeText(this, "this cant be empty", Toast.LENGTH_SHORT).show()
return
}
val cost = stringInTextField.toDouble() / stringInTextField1.toDouble()
val tipPercentage = when (binding.productOptions.checkedRadioButtonId) {
R.id.option_normal -> 1.5
R.id.option_60 -> 1.6
R.id.option_70 -> 1.7
else -> 2.0
}
var product = tipPercentage * cost
val roundUp = binding.IVA.isChecked
if (roundUp) {
product = (tipPercentage * cost) * 1.21
}
val formattedTip = NumberFormat.getCurrencyInstance().format(product)
binding.result.text = getString(R.string.resultado, formattedTip)
}
}
You should use to setError()
Like this: stringInTextField.setError("this cant be empty")
For more information: Show Error on the tip of the Edit Text Android
you can use this following code according to your code:
if (stringInTextField.isEmpty()) { stringInTextField.setError("this cant be empty") return; }

Check if Input is empty doesnt work Kotlin

Hey guys i just started playing around with android studio and wanted to make an app that calculates the faculty of an input value. It works if i give it an Input Value but if not it crashes, so i tried to check if the input is empty but that didn´t solve the error. Here´s the code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Button = findViewById<Button>(R.id.button)
val Output = findViewById<TextView>(R.id.Output)
val Input = findViewById<TextView>(R.id.Input)
Button.setOnClickListener {
val num = Input.text.toString().toInt()
if(num.toString().isNotBlank()) {
var hilf = 1
for (i in 1..num.toString().toInt()) {
hilf *= i
}
Output.text = hilf.toString()
}
}
}
Do you guys have any idea how i could fix the problem?
First you check if the EditText is empty and then try to convert to Int:
if(!Input.text.toString().trim().isEmpty()) {
val num = Input.text.toString().toInt()
var hilf = 1
for (i in 1..num) {
hilf *= i
}
Output.text = hilf.toString()
}
Also you don't need
num.toString().toInt()
you can just use
1..num
because num's type is Int
you want to use the following:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Button = findViewById<Button>(R.id.button)
val Output = findViewById<TextView>(R.id.Output)
val Input = findViewById<TextView>(R.id.Input)
Button.setOnClickListener {
val num = Input.text.toString().toInt()
if(!Input.text.toString().isEmpty()) {
var hilf = 1
for (i in 1..num.toString().toInt()) {
hilf *= i
}
Output.text = hilf.toString()
}
}
}

Categories

Resources