Why my code is not saving data using shared preferences? - android

I try to save the state of a Number Text View but is not working. At first I was thinking that the app was not reading my data because I copy the code from the oficial documentation. But after investigate a little more I look in android/data/ and there was not a folder called sad.whyIsNot.Saving, I tried many tutorials on youtube but I do not know why I am doing wrong. Can some one of you guys explain to me what is happening and how can I solve it?
This is the code for my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/vplayeras1"
android:layout_width="45dp"
android:layout_height="30dp"
android:layout_gravity="center_horizontal"
android:text="#string/valorDefectoVeces"
android:textSize="24sp" />
<Button
android:id="#+id/agrega1"
android:layout_width="149dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/playera1" />
</LinearLayout>
And this is the code of my MainActivity.
package sad.whyIsNot.Saving
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadData()
val btnPlayera1: Button = findViewById(R.id.agrega1)
btnPlayera1.setOnClickListener{aumenta1()}
}
private fun loadData(){
val sharedPref = getPreferences(Context.MODE_PRIVATE)
val valPlayera1 = sharedPref.getInt("VECES_PLAYERA1", 0)
}
private fun aumenta1() {
val resultText: TextView = findViewById(R.id.vplayeras1)
val resultInt = resultText.text.toString().toInt() + 1
resultText.text = resultInt.toString()
val sharedPref = getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt("VECES_PLAYERA1", resultInt)
commit()
}
Toast.makeText(this,"Se ha guardado!", Toast.LENGTH_LONG).show()
}
}

I don't see anything wrong with your code, I assume you know that loadData doesn't do anything with the data and you already tested if you have access to it?
Accessing the preferences outside of MainActivity might not work because getPreferences is bound to a specific activity.
If aumenta1 doesn't return I doubt that the value isn't put inside of the File, so I'd rather check if resultInt isn't 0 and that loadData really can't access the value

Related

Not Getting Edit Text Data

I am New to Android . I don't know how to get the data of EditText in Android .
Here is my Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity2">
<EditText
android:id="#+id/edOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/edSecond"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Here is my code :
val one=edOne.text.toString()
btnAdd.setOnClickListener{
val two=edOne.text.toString()
Log.e("Tag",one +" "+two)
}
one is calling from onCreate() method . and at the time of creation of you onCreate() you don't have any data in editText one .So you can't get any data from one if you have not added from xml .
So just move your one code into click listener.
val one=edOne.text.toString()
btnAdd.setOnClickListener{
val two=edOne.text.toString()
Log.e("Tag",one +" "+two)
}
You can access related View elements with findViewById and use them later.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
class MainActivity : AppCompatActivity() {
private lateinit var edOne : EditText
private lateinit var btnAdd : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
edOne = findViewById(R.id.edOne)
btnAdd = findViewById(R.id.btnAdd)
val one=edOne.text.toString()
btnAdd.setOnClickListener {
val two=edOne.text.toString()
Log.e("Tag",one +" "+two)
}
}
}

BindingAdapter is not working as expected

I am trying to add a custom binding to my TextView. Please find my code below
MainActivity.kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.builders.bindingadaptertest.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
val model = ViewModelProvider(this).get(MainViewModel::class.java)
}
}
MainViewModel.kt
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MainViewModel: ViewModel() {
var data = MutableLiveData<String>()
init {
data.value = "This works"
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.builders.bindingadaptertest.MainViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:customBind="#{viewModel.data}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
BindingAdapters.kt
#BindingAdapter("app:customBind")
fun customBind(view: TextView, data: String?) {
Log.d("DEBUG_CUSTOM", "Setting custom [$data] listner")
view.text = data
}
Doubt: When I run this project, The log cat shows the data passing to customBind is null.
2020-11-30 09:37:33.351 4682-4682/com.builders.bindingadaptertest D/DEBUG_CUSTOM: Setting custom [null] listner
Can anyone help me to get the correct data from ViewModel into the binding adapter?
It's null, because in your databinding viewModel is not set.
You forgot to add binding.viewModel = model
Also, some possible suggestions:
No need to leave the LiveData reference mutable, just use val
I'd prefer an extension function for the binding adapter: fun TextView.customBind(data: String?)
You should set a lifecycleOwner on your binding, otherwise your activity may keep an indirect reference on your vm, which will cause leaks on orientation changes

Compilation error while adding onClickListener for Button

I'm getting compilation errors when trying to add onClickListener for a Button in my Android application. The error is as below:
build failed 792 ms
Run build 690 ms
Load build 2 ms
Configure build 94 ms
Calculate task graph 41 ms
Run tasks 550 ms
null
/home/avinash/AndroidStudioProjects/JustJava
app/src/main/java
com/example/android/justjava/MainActivity.kt
Expecting member declaration
Expecting member declaration
Expecting member declaration
Expecting member declaration
Function declaration must have a name
Task :app:buildInfoGeneratorDebug
MainActivity.kt is as below:
package com.example.android.justjava
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
val order_button = findViewById<Button>(R.id.order_button)
//set listener
order_button.setOnClickListener {
//Action perform when the user clicks on the button.
Toast.makeText(this#MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
}
}
XML is as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity"
android:textAllCaps="true"
android:layout_marginBottom="16dp"
android:paddingLeft="16dp"
android:paddingTop="16dp"/>
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#000000"
android:textSize="16sp"
android:paddingLeft="16dp"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order"
android:layout_marginTop="16dp"
android:id="#+id/order_button"/>
Since your already using Kotlin, how about trying the More Kotlin style?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnLabel.setOnClickListener { Toast.makeText(this, "Toast", Toast.LENGTH_SHORT).show() }
}
You don't need findViewById() or anything else.
You'll need to import something like import kotlinx.android.synthetic.main.activity_main.*
but AndroidStudio can auto generate that for you.
Update your MainActivity like this
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle ? ) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val order_button = findViewById<Button> (R.id.order_button)
//set listener
order_button.setOnClickListener {
//Action perform when the user clicks on the button.
Toast.makeText(this #MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
}
}
}

android kotlin - app keep keeps stopping when i click the button

I start doing a simple android app for practice to calculate the age with Kotlin programming language, when i click the button the app, can someone help me with this and fix it to know where is my wrong because I am just very beginner
package com.calcult.age.agecalcult
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var ageInput = ageText.text.toString()
doIT.setOnClickListener{
var currentYear = Calendar.getInstance().get(Calendar.YEAR)
var getAge = currentYear-ageInput.toInt()
Toast.makeText(this, getAge, Toast.LENGTH_LONG)
}
}
}
XML FILE :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginEnd="148dp"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="148dp"
android:id="#+id/doIT"
android:text="#string/button_text1"
android:textSize="18sp"
app:layout_constraintHorizontal_bias="0.0" android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent" android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintVertical_bias="0.771"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/ageText" app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="215dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="85dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="84dp"
android:layout_marginBottom="250dp" app:layout_constraintBottom_toTopOf="#+id/doIT"/>
</android.support.constraint.ConstraintLayout>
As Vladyslav Matviienko said you're trying to get the text onCreate, what you need to do is something like this:
//Here the view is already created, so you'll be able to setup everything you need.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupListener()
}
//If you are learning, you should consider reading a bit about clean code,
//it's always nice that a function does just one job, that's why I broke the code
//below in two little functions. Have in mind, this code is not the best, but at the
//moment i don't have much time to write this.
private fun setupListener() {
doIT.setOnClickListener{
//Always be aware of the type of the variables, when i wrote the first answer i was
//trying to do a math operatiton using a string, so it would not work. =P
var currentYear = Calendar.getInstance().get(Calendar.YEAR)
var getAge = (currentYear-getAge().toInt()).toString()
Toast.makeText(this, getAge, Toast.LENGTH_LONG).show()
}
}
private fun getAge(): String {
return ageText.text.toString
}

App crashes in Android Studio using Kotlin

I have started from the very basic level in Android and have created a simple app to display Happy Birthday. But the App keeps crashing in both the Emulator and the Actual hardware(SAMSUNG NOTE 8).
Need help on how can i resolve the error.
Here is xml Code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.happybirthday.MainActivity">
<TextView
android:id="#+id/sample_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_margin="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
MainActivity Code :
package com.example.android.happybirthday
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Example of a call to a native method
sample_text.text = stringFromJNI()
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
}
You forget to typecast your TextView :
Try with below code :
val sample_text : TextView = findViewById<TextView>(R.id.sample_text) as TextView
Full Code :
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sample_text : TextView = findViewById<TextView>(R.id.sample_text) as TextView
sample_text .text = "Happy Birthday"
}
}

Categories

Resources