Created
August 10, 2021 16:13
-
-
Save vaibhavgoyal09/a3e5737c2d5d3d867c4f2b28f5dbef98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @AndroidEntryPoint | |
| class MainActivity : AppCompatActivity() { | |
| private lateinit var saveDataButton: Button | |
| private lateinit var clearDataButton: Button | |
| private lateinit var getDataButton: Button | |
| private lateinit var inputName: EditText | |
| private lateinit var inputAge: EditText | |
| private val viewModel by viewModels<DataViewModel>() | |
| override fun onCreate(savedInstanceState: Bundle?) { | |
| super.onCreate(savedInstanceState) | |
| setContentView(R.layout.activity_main) | |
| initViews() | |
| setClickListeners() | |
| } | |
| private fun setClickListeners() { | |
| saveDataButton.setOnClickListener { | |
| if (inputName.text.toString().isEmpty() || inputAge.text.toString().isEmpty()) { | |
| Toast.makeText(this, "Fill all the fields", Toast.LENGTH_SHORT).show() | |
| } else { | |
| val age: Int? = try { | |
| Integer.parseInt(inputAge.text.toString()) | |
| } catch (e: NumberFormatException) { | |
| e.printStackTrace() | |
| null | |
| } | |
| if (age == null){ | |
| Toast.makeText(this, "Enter Valid Age", Toast.LENGTH_SHORT).show() | |
| return@setOnClickListener | |
| } | |
| viewModel.saveName(inputName.text.toString()) | |
| viewModel.saveAge(age) | |
| } | |
| } | |
| clearDataButton.setOnClickListener { | |
| inputAge.setText("") | |
| inputName.setText("") | |
| } | |
| getDataButton.setOnClickListener { | |
| inputName.setText(viewModel.getName()) | |
| inputAge.setText(viewModel.getAge().toString()) | |
| } | |
| } | |
| private fun initViews() { | |
| saveDataButton = findViewById(R.id.buttonSave) | |
| clearDataButton = findViewById(R.id.buttonClear) | |
| getDataButton = findViewById(R.id.buttonGetData) | |
| inputName = findViewById(R.id.textName) | |
| inputAge = findViewById(R.id.textAge) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment