Android ImageButton event does not execute all actions upon first click - java

I have a button to delete all data on my activity screen (a chart, database data and a textview) and to display a toast.
Pressing the button does everything apart from getting rid of the textview, which only happens upon a second press. The code is in onCreate. Why is this happening and how can I fix it? Thank you :)
findViewById<ImageButton>(R.id.delete_btn).setOnClickListener {
pieChart.visibility = View.GONE
textView.visibility = View.GONE
appsViewModel.removeAll()
Toast.makeText(this, "Successfully deleted all", Toast.LENGTH_SHORT).show()
}

As #mayurgajra made me realise, some other code interfered with the changes in the textView. I managed to fix this with a boolean. I set it to true within the ImageButton event, and now I only modify the textview visibility in my other code if the boolean is false.
private var deleted: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
...
findViewById<ImageButton>(R.id.delete_btn).setOnClickListener {
pieChart.visibility = View.GONE
totalUsage.visibility = View.GONE
deleted = true
appsViewModel.removeAll()
Toast.makeText(this, "Successfully deleted all", Toast.LENGTH_SHORT).show()
}
}
private fun otherMethod(){
...
if (!deleted) {
totalUsage.text = "Total usage today: $hour"
totalUsage.visibility = View.VISIBLE
}
}

Related

How to change text on the screen in a loop until user acts

I would like to build an activity, which displays a set of strings in a loop until the user clicks on the screen.
Any suggestions is greatly appreciated.
I am trying to do this in Kotlin, but Java advice is also welcomed.
I have built an activity with TextSwitcher and a variable (isClicked) that indicates whether the user has clicked on the screen. I set up a listener that sets the isClicked when user clicks. Then in a loop I check the value of isClicked and if it is not checked I change the value of the text.
class SelectionActivity : AppCompatActivity() {
var isClicked = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.selection)
val textSwitcher = findViewById<TextSwitcher>(R.id.selectionText)
textSwitcher.setFactory {
val textView = TextView(this)
textView.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
textView.textSize = 32f
textView
}
textSwitcher.setCurrentText("Start")
textSwitcher.setOnClickListener {
isClicked = false;
}
var i = 0;
while (isClicked) {
textSwitcher.setText(i.toString())
i++;
}
}
}
This does not seem to work. The app just hangs and becomes non-responsive. If I understand correctly, it might have something to do with activity class being in the UI thread and while loop being too heavy for it. However, I am not sure how this should be solved.

I added [viewbinding] but I can't find my [Button's id from xml file

I just can't get id from layout folder:
for more explain ;
in the code bellow that is in .kt file the radio_group is my id that is all red in code bellow :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get radio group selected item using on checked change listener
radio_group.setOnCheckedChangeListener(
RadioGroup.OnCheckedChangeListener { group, checkedId ->
val radio: RadioButton = findViewById(checkedId)
Toast.makeText(applicationContext," On checked change :"+
" ${radio.text}",
Toast.LENGTH_SHORT).show()
})
// Get radio group selected status and text using button click event
button.setOnClickListener{
// Get the checked radio button id from radio group
var id: Int = radio_group.checkedRadioButtonId
if (id!=-1){ // If any radio button checked from radio group
// Get the instance of radio button using id
val radio:RadioButton = findViewById(id)
Toast.makeText(applicationContext,"On button click :" +
" ${radio.text}",
Toast.LENGTH_SHORT).show()
}else{
// If no radio button checked in this radio group
Toast.makeText(applicationContext,"On button click :" +
" nothing selected",
Toast.LENGTH_SHORT).show()
}
}
}
// Get the selected radio button text using radio button on click listener
fun radio_button_click(view: View){
// Get the clicked radio button instance
val radio: RadioButton = findViewById(radio_group.checkedRadioButtonId)
Toast.makeText(applicationContext,"On click : ${radio.text}",
Toast.LENGTH_SHORT).show()
}
}
the radio_group is all red error and cant find the solution for that after build again and ctrl+enter
please help if there is better way...
This is not how you use view binding. The code you wrote is how you would do it with Kotlin synthetics, which is deprecated now. Enabling viewBinding requires more work than simply enabling it. I suggest reading the documentation here about how to do it:
Migrate from Kotlin synthetics to Jetpack view binding

Android data lost on theme change (Light/Dark mode)

Android: I have made a simple Todo list app using Kotlin. And the theme (Light/Dark) of this app is set to system default theme MODE_NIGHT_FOLLOW_SYSTEM. Now the problem is that when I changed theme to Dark mode(because my emulator's theme was set to Light theme previously), all added Todo items were gone and same when I changed to Light mode again. Then I noticed the size of my ArrayList became 0 (empty).
Here is screenshots to understand it better:
Light Mode
https://i.stack.imgur.com/eWbzO.png
after changing system theme to Dark
Dark Mode
https://i.stack.imgur.com/B9iqg.png
tasks are added to list: ArrayList when saveButton: Textview is clicked
class MainActivity : AppCompatActivity() {
var modified = false
private lateinit var listView: ListView
private lateinit var input: EditText
private lateinit var saveButton: TextView
private lateinit var cancelButton: TextView
private val list = ArrayList<String>()
private lateinit var listAdapter: CustomAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listView = findViewById(R.id.listView)
input = findViewById(R.id.input)
saveButton = findViewById(R.id.saveBtn)
cancelButton = findViewById(R.id.cancelBtn)
listAdapter = CustomAdapter(this, list)
listView.adapter = listAdapter
val warningToast = Toast.makeText(this,
"The text may be empty or contains only spaces",
Toast.LENGTH_LONG)
saveButton.setOnClickListener {
val text = input.text.toString()
// if text is empty or only contains blank
if (text.isEmpty() || text.isBlank()) {
warningToast.show()
return#setOnClickListener
}
if (!modified) {
// output list size 0 after changing theme
Log.d("MY_DEBUG", "size fo list is : ${list.size}")
list.add(input.text.toString())
} else {
// ...
}
input.text.clear()
listAdapter.notifyDataSetChanged()
}
// ...
}
}
I thought that this is because it triggers a uiMode configuration change when theme mode is changed. So, the activity is recreated automatically. I want to keep added items even after changing theme. Is there any way to prevent loss of added items. Thank you!
Changing theme recreates your activity and it reinitiates your list. It is not because of changing theme itself.
You have to save your data persistently, in a database or in a SharedPreferences instance with your own serialization method (like JSON).

useing shared preferences to save Button click state

i am working on comment section of an application like play store using mvvm,coroutine,kodein and DataBinding.i set login page in my main activity After the user presses the login button Comment Activity will become apparent.
I set recyclerview in comment activity. at end of every item i asked a question that was this review helpful or not. if not press no else press yes.i used shared preferences to save button state. for example when i clicked on yes button yesclicked(boolean variable) will be saved in sharedpref. till here everything works fine.
the problem--> i saved that state then i getYesButtonState() in onBindViewHolder method of recyclerview class and i said when activity recreated change the background color of yes button to #D5FFD7 for this purpose that you clicked on this before
but nothing happend and it didnt work
this code is for shared pref
val SPP_NAME = "ButtonState"
var buttonLocalState: SharedPreferences = context.getSharedPreferences(SPP_NAME, Context.MODE_PRIVATE)
fun setYesButtonState(isClicked: Boolean) {
val userLocalDatabaseEditor: SharedPreferences.Editor = buttonLocalState.edit()
userLocalDatabaseEditor.putBoolean("yesClicked", isClicked)
userLocalDatabaseEditor.apply()
}
fun setNoButtonState(isClicked: Boolean) {
val userLocalDatabaseEditor: SharedPreferences.Editor = buttonLocalState.edit()
userLocalDatabaseEditor.putBoolean("noClicked", isClicked)
userLocalDatabaseEditor.apply()
}
fun getYesButtonState(): Boolean? {
if (buttonLocalState.getBoolean("yesClicked", false) == false) {
return null
} else {
return true
}
}
fun getNoButtonState(): Boolean? {
if (buttonLocalState.getBoolean("noClicked", false) == false) {
return null
} else {
return true
}
}
fun clearButtonState() {
val userLocalDatabaseEditor: SharedPreferences.Editor = buttonLocalState.edit()
userLocalDatabaseEditor.clear()
userLocalDatabaseEditor.apply()
}
this is for recyclerview class:
//yes button clicked
yesbtn.setOnClickListener {
yesClicked = true
localStore.clearButtonState()
localStore.setYesButtonState(yesClicked)
val Helpful = 1
if (localStore.getYesButtonState() == true) {
nobtn.setBackgroundColor(Color.WHITE)
startColorAnimation(yesbtn)
activity.handler.postDelayed({
yesbtn.setBackgroundColor(Color.parseColor("#D5FFD7"))
nobtn.isClickable = true
}, 892.25.toLong())
}
try {
viewModel.deleteperson(
localStore.getUserName().toString(),
currentItem.id
).observe(mlifecycleOwner, Observer {
})
} catch (e: IllegalStateException) {
e.fillInStackTrace()
}
viewModel.feedback(
currentItem.id,
localStore.getUserName().toString(),
currentItem.description,
Helpful
).observe(mlifecycleOwner, Observer {
})
Toast.makeText(
context,
"thanks for your feedback",
Toast.LENGTH_SHORT
).show()
yesbtn.isClickable = false
}
//no button clicked
nobtn.setOnClickListener {
noClicked = true
localStore.clearButtonState()
localStore.setNoButtonState(noClicked)
val Helpful = 0
if (localStore.getNoButtonState() == true) {
yesbtn.setBackgroundColor(Color.WHITE)
startColorAnimation(nobtn)
activity.handler.postDelayed({
nobtn.setBackgroundColor(Color.parseColor("#D5FFD7"))
yesbtn.isClickable = true
}, 892.25.toLong())
}
try {
viewModel.deleteperson(
localStore.getUserName().toString(),
currentItem.id
).observe(mlifecycleOwner, Observer {
})
} catch (e: IllegalStateException) {
e.fillInStackTrace()
}
viewModel.feedback(
currentItem.id,
localStore.getUserName().toString(),
currentItem.description,
Helpful
).observe(mlifecycleOwner, Observer {
})
Toast.makeText(
context,
"please tell us why",
Toast.LENGTH_SHORT
).show()
it.isClickable = false
}
where i did wrong. thanks for your Help
try this
after the button click .. call notifyDataSetChanged(); in your adapter class

Bottom navigation icon only changing color when clicked twice?

When I click on an icon it doesn't change color unless I click it again, it goes to the activity but only the first icon remains highlighted. I have to click it again for the icon to change color. What is wrong with my code?
class ProfileActivity : BaseActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
val navigationBar = findViewById<BottomNavigationView>(R.id.navigation_bar)
navigationBar.setOnNavigationItemSelectedListener(navigation_bar)
}
private val navigation_bar = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.nav_profile -> {
// startActivity(Intent(this#ProfileActivity, ProfileActivity::class.java))
return#OnNavigationItemSelectedListener true
}
R.id.nav_explore -> {
startActivity(Intent(this#ProfileActivity, ExploreActivity::class.java))
return#OnNavigationItemSelectedListener true
}
R.id.nav_store -> {
startActivity(Intent(this#ProfileActivity, StoreActivity::class.java))
return#OnNavigationItemSelectedListener true
}
R.id.nav_board -> {
startActivity(Intent(this#ProfileActivity, BoardActivity::class.java))
return#OnNavigationItemSelectedListener true
}
}
false
} }
You are using activity. use Fragment. i think it will be solved.
You are using different activities for each item.
You have to handle the selected items in your activities with something like:
navigationBar.setSelectedItemId(R.id.nav_explore)

Categories

Resources