Activity calling a DialogFragment: Dialog does not always get dismissed - android

I have an Activity that calls a DialogFragment like this:
private fun showDeleteDetailDialog(itemView: View, categoryId: String, detailId: String) {
val dialog = DeleteDetailDialogFragment.newInstance(categoryId, detailId)
dialog.show(this#DetailsActivity.fragmentManager, "DeleteDetailDialog")
}
And this is the code for my DialogFragment (a click on the PositiveButton deletes an item in Firebase database):
class DeleteDetailDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Use the Builder class for convenient dialog construction
val categoryId = arguments.getString(ARG_CATEGORY_ID)
val detailId = arguments.getString(ARG_DETAIL_ID)
val builder = AlertDialog.Builder(activity)
builder.setMessage(R.string.delete_detail)
.setPositiveButton(R.string.delete, { dialog, id ->
deleteDetail(categoryId, detailId)
})
.setNegativeButton(R.string.cancel, { dialog, id ->
// User cancelled the dialog
})
// Create the AlertDialog object and return it
return builder.create()
}
private fun deleteDetail(categoryId: String, detailId: String) {
// get the detail reference for the specified category
val deleteRef = FirebaseDatabase.getInstance().getReference("details").child(categoryId).child(detailId)
// remove detail
deleteRef.removeValue()
// get the reference for the specified favorite, identified by detailId
val deleteFaveRef = FirebaseDatabase.getInstance().getReference("favorites").child(detailId)
// remove favorite
deleteFaveRef.removeValue()
}
companion object {
private val ARG_CATEGORY_ID = "category_id"
private val ARG_DETAIL_ID = "detail_id"
fun newInstance(categoryId: String, detailId: String): DeleteDetailDialogFragment {
val fragment = DeleteDetailDialogFragment()
val args = Bundle()
args.putString(ARG_CATEGORY_ID, categoryId)
args.putString(ARG_DETAIL_ID, detailId)
fragment.arguments = args
return fragment
}
}
}
When I call the Dialog, the Dialog window pops up. When I then click Cancel (the NegativeButton) the Dialog disappears as expected. When I click Delete (the PositiveButton), the Dialog disappears, again as expected.
BUT, after a successful Delete, when I call the Dialog again, a click on Cancel does not immediately dismiss the dialog; instead, the Dialog box pops up again and only disappears after a second click on Delete. There seems to be an issue with the FragmentManager. What am I missing here?

You should call
getDialog().dismiss()
NOTE
You should create a Custom Dialog within DeleteDetailDialogFragment .
class DeleteDetailDialogFragment : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View?
{
val rootView = inflater.inflate(R.layout.your_layout, container,false)
return rootView
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}

There's nothing wrong with the code above! Removing an item in Firebase database triggered an onDataChange event in my ValueEventListener which then called an updateUI function. Unfortunately, I had my onItemTouchListener handling onItemClick events (like my remove() instruction via DialogFragment) placed there, which worked fine as long as I didn't change any data in my Firebase database. But removing an item there triggered a loop that caused the "erratic" behavior of my code. The solution was to move the call to my onItemTouchListener (that handles onItemClicks) from the updateUI function to the onCreate section of my code. Huh, I learnt something!

Related

Custom DialogFragment with AlertDialog returns EditText as ""

I have a custom DialogFragment that I'm using to capture user input that I will create a database entry with. I'm using EditText in an AlertDialog. I am trying to use a single activity for my application and the original tutorial I was studying was using multiple activities and intents but that seems outdated for most cases.
When I debug I find that the EditText is returning "" and is showing up as empty when I call TextUtils.isEmpty() in the MainActivity onDialogPositiveClick.
I've done a lot of combing through the forms here and I'm confused by:
1)many of the answers I find are in Java and not Kotlin
2)many mention onCreate but do not specify onCreateView vs. onCreateDialog or if there's just an onCreate that I need to override.
I have researched this and found answers that confuse me a bit about when and if I need to inflate the layout. This current itteration I didn't inflate it at all. I just set it in the AlertDialog builder.
Maybe it's the interface I'm not understanding. How am I supposed to pass information between the dialog and MainActivity? The interface seems to pass the dialog itself but I seem to be missing something when it comes to getting the EditText from the dialog.
My custom DialogFragment
class NewSongFragment : DialogFragment() {
lateinit var listener: NewSongListener
lateinit var editNewSong: EditText
lateinit var editBPM: EditText
interface NewSongListener {
fun onDialogPositiveClick(dialog: DialogFragment)
fun onDialogNegativeClick(dialog: DialogFragment)
}
/** The system calls this to get the DialogFragment's layout, regardless
of whether it's being displayed as a dialog or an embedded fragment. */
/*
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout to use as dialog or embedded fragment
return inflater.inflate(R.layout.fragment_new_song, container, false)
}
*/
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = context as NewSongListener
} catch (e: ClassCastException) {
// The activity doesn't implement the interface, throw exception
throw ClassCastException((context.toString() +
" must implement NewSongListener"))
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
// Use the Builder class for convenient dialog construction
val builder = AlertDialog.Builder(it)
//add inflater
//val inflater = requireActivity().layoutInflater;
//val view = inflater.inflate(R.layout.fragment_new_song, null)
builder
.setView(R.layout.fragment_new_song)
.setCancelable(true)
.setNegativeButton(R.string.cancel,DialogInterface.OnClickListener { dialog, id ->
dialog?.cancel()
})
.setPositiveButton(R.string.button_save,
DialogInterface.OnClickListener {dialog, _ ->
listener.onDialogPositiveClick(this)
})
// Create the AlertDialog object and return it
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
My MainActivity
class MainActivity : AppCompatActivity(),NewSongFragment.NewSongListener {
private val songViewModel: SongViewModel by viewModels {
SongViewModelFactory((application as SongApplication).repository)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//create view
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
val adapter = ItemAdapter(this,
ItemAdapter.OnClickListener { rating -> songViewModel.insertRating(rating) }
)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
//initialize data
songViewModel.allSongs.observe(this) { song ->
// Update the cached copy of the songs in the adapter.
song.let { adapter.submitList(it) }
}
// Use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true)
//add song button
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener {
showNewSongDialog()
}
}
private fun showNewSongDialog() {
// Create an instance of the dialog fragment and show it
val dialog = NewSongFragment()
dialog.show(supportFragmentManager, "NewSongFragment")
}
override fun onDialogPositiveClick(dialog: DialogFragment) {
// User touched the dialog's positive button
val editNewSong = dialog.view?.findViewById<EditText>(R.id.newSongTitle)
val editBPM = dialog.view?.findViewById<EditText>(R.id.newSongBpm)
if(TextUtils.isEmpty(editNewSong?.text)){
}else{
val newSong = Song(editNewSong?.text.toString(),100)
songViewModel.insertSong(newSong)
val rating = Rating(System.currentTimeMillis(),newSong.songTitle, 50)
songViewModel.insertRating(rating)
}
}
override fun onDialogNegativeClick(dialog: DialogFragment) {
// User touched the dialog's negative button
}
}
You are adding the layout with a resource identifier, so your call to get the view is returning null. (Why? The view is inflated internally and just handled differently.) Since you are using the AlertDialog to collect data, you will have to add an inflated view.
I am also going to suggest that you change the interface to hide the details of the dialog; There is no reason for the main activity to know the internal structure of the dialog. It just needs the song title and BPM and maybe some other stuff. You will find the code a little easier to understand and maintain.
Here is a slight rework. This code just captures the song title, but it can easily be extended to include other data as well.
In NewSongFragment:
interface NewSongListener {
fun onDialogPositiveClick(songTitle: String)
fun onDialogNegativeClick(dialog: DialogFragment)
}
val inflater = requireActivity().layoutInflater;
val view = inflater.inflate(R.layout.fragment_new_song, null)
builder
.setView(view)
.setCancelable(true)
.setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, id ->
dialog?.cancel()
})
.setPositiveButton(R.string.button_save)
{ dialog, _ ->
Log.d("Applog", view.toString())
val songTitle = view?.findViewById<EditText>(R.id.newSongTitle)?.text
listener.onDialogPositiveClick(songTitle.toString())
}
In MainActivity.kt
override fun onDialogPositiveClick(songTitle: String) {
// songTitle has the song title string
}
Android dialogs have some quirks. Here are a number of ways to do fragment/activity communication.
Because you are adding the dialog as a Fragment, you should use onCreateView to inflate the view, rather than trying to add a view in onCreateDialog.

Kotlin - How to get value from button choice in Dialog?

I am in the process of creating a golf scorecard app.
Every hole's score is an empty textView, and that textView has a setOnClickListener to open the score picker dialog.
I want to get the score value from the score picker dialog.
Here is the dialog interface:
https://i.stack.imgur.com/VNVc1.png
Each button is corresponding to a score.
I know that each button will need a setOnClickListener, but my knowledge is limited about everything else afterward.
So my question is how to return that score value so I can display it in that specific the textView and add it to the player's total? Any suggestions would be very helpful.
Thank you for your time.
You can implement custom listner, that listner you need to
below code is for demo,
implement in diaglog fragment
//score for current hole dialog
class SomeDialog:DialogFragment() {
private var dl: CustomListener? = null
// interface to detect dialog close event
interface CustomListener {
fun closeEvent(id: String, valueToPass: Int)
}
fun customListerTrig(l: CustomListener) {
dl = l
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
button1.setOnClickListener {
dl?.closeEvent("golfDiag", 1)
this.dismiss()
}
button2.setOnClickListener {
dl?.closeEvent("golfDiag", 2)
this.dismiss()
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_some_dialog, container, false)
}
}
How i called and retrived button click event
val common = SomeDialog()
common.customListerTrig(object : CommonInfoDialog.CustomListener {
override fun closeEvent(id: String, buttonValueFromDialog: Int) {
// todo usebuttonValueFromDialog
}
})
//use fragment according where this dialog will be called.
common.show(this.childFragmentManager, "golfDiag")
May be this code is easy for you. Use Android dialog API to make your work easier.
/**
* e.g.
showPickScoreDialog(requireContext()) { score ->
Toast.makeText(context, "score[$score]", Toast.LENGTH_LONG).show()
}
*/
fun showPickScoreDialog(context: Context, callback: (Int) -> Unit) {
val defaultCheckedScore = -1
val scoreList = getScoreList()
MaterialAlertDialogBuilder(context)
.setTitle("Score For Current Hole:")
.setSingleChoiceItems(scoreList, defaultCheckedScore) { dialog: DialogInterface?, which: Int ->
val score = scoreList[which].toInt()
callback(score)
dialog?.dismiss()
}
.setNegativeButton("Cancel", null)
.show()
}
private fun getScoreList(): Array<String> {
val list = mutableListOf<String>()
for (i in 1..12) {
list.add(i.toString())
}
return list.toTypedArray()
}
So my question is how to return that score value so I can display it in that specific the textView and add it to the player's total? Any suggestions would be very helpful.
https://developer.android.com/guide/topics/ui/dialogs#PassingEvents

How to retrive data from DialogFragment with ViewModel and Room

I'm building an Android app that has different pages that mainly have some EditText. My goal is to handle the click on the EditText and shows a DialogAlert with an EditText, then the user can put the text, click "save" and the related field in the database (I'm using Room and I've tested the queries and everything works) will be updated. Now I was able to handle the text from the DialogFragment using interface but I don't know how to say that the text retrieved is related to the EditText that I've clicked. What is the best approach to do this?
Thanks in advance for your help.
Let's take this fragment as example:
class StaticInfoResumeFragment : Fragment(), EditNameDialogFragment.OnClickCallback {
private val wordViewModel: ResumeStaticInfoViewModel by viewModels {
WordViewModelFactory((requireActivity().application as ManagementCinemaApplication).resumeStaticInfoRepo)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val root = inflater.inflate(R.layout.fragment_static_info_resume, container, false)
wordViewModel.resumeStaticInfo.observe(viewLifecycleOwner) { words ->
println("test words: $words")
}
val testView = root.findViewById<TextInputEditText>(R.id.textInputEditText800)
testView.setOnClickListener{
val fm: FragmentManager = childFragmentManager
val editNameDialogFragment = EditNameDialogFragment.newInstance("Some Title")
editNameDialogFragment.show(fm, "fragment_edit_name")
}
resumeStaticInfoViewModel.firstName.observe(viewLifecycleOwner, Observer {
testView.setText(it)
})
return root
}
override fun onClick(test: String) {
println("ciao test: $test")
wordViewModel.updateFirstName(testa)
}}
Then I've the ViewModel:
class ResumeStaticInfoViewModel(private val resumeStaticInfoRepo: ResumeStaticInfoRepo): ViewModel() {
val resumeStaticInfo: LiveData<ResumeStaticInfo> = resumeStaticInfoRepo.resumeStaticInfo.asLiveData()
fun updateFirstName(resumeStaticInfoFirstName: String) = viewModelScope.launch {
resumeStaticInfoRepo.updateFirstName(resumeStaticInfoFirstName)
}
....
And the DialogFragment:
class EditNameDialogFragment : DialogFragment() {
private lateinit var callback: OnClickCallback
interface OnClickCallback {
fun onClick(test: String)
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
callback = parentFragment as OnClickCallback
} catch (e: ClassCastException) {
throw ClassCastException("$context must implement UpdateNameListener")
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val title = requireArguments().getString("title")
val alertDialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireContext())
alertDialogBuilder.setTitle(title)
val layoutInflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val alertCustomView = layoutInflater.inflate(R.layout.alert_dialog_edit_item, null)
val editText = alertCustomView.findViewById<EditText>(R.id.alert_edit)
alertDialogBuilder.setView(alertCustomView)
alertDialogBuilder.setPositiveButton(
"Save",
DialogInterface.OnClickListener { dialog, which ->
callback.onClick(editText.text.toString())
})
alertDialogBuilder.setNegativeButton("No") { _: DialogInterface, _: Int -> }
return alertDialogBuilder.create()
}
companion object {
fun newInstance(title: String?): EditNameDialogFragment {
val frag = EditNameDialogFragment()
val args = Bundle()
args.putString("title", title)
frag.arguments = args
return frag
}
}
}
Do you mean you just want to show a basic dialog for entering some text, and you want to be able to reuse that for multiple EditTexts? And you want a way for the dialog to pass the result back, but also have some way of identifying which EditText it was created for in the first place?
The thing about dialogs is they can end up being recreated (like if the app is destroyed in the background, and then restored when the user switches back to it) so the only real configuration you can do on it (without getting into some complexity anyway) is through its arguments, like you're doing with the title text.
So one approach you could use is send some identifier parameter to newInstance, store that in the arguments, and then pass it back in the click listener. So you're giving the callback two pieces of data in onClick - the text entered and the reference ID originally passed in. That way, the activity can handle the ID and decide what to do with it.
An easy value you could use is the resource ID of the EditText itself, the one you pass into findViewById - it's unique, and you can easily use it to set the text on the view itself. You're using a ViewModel here, so it should be updating automatically when you set a value in that, but in general it's a thing you could do.
The difficulty is that you need to store some mapping of IDs to functions in the view model, so you can handle each case. That's just the nature of making the dialog non-specific, but it's easier than making a dialog for each property you want to update! You could make it a when block, something like:
// you don't need the #ResId annotation but it can help you avoid mistakes!
override fun onClick(text: String, #ResId id: Int) {
when(id) {
R.id.coolEditText -> viewModel.setCoolText(text)
...
}
}
where you list all your cases and what to call for each of them. You could also make a map like
val updateFunctions = mapOf<Int, (String) -> Unit>(
R.id.coolEditText to viewModel::setCoolText
)
and then in your onClick you could call updateFunctions[id]?.invoke(text) to grab the relevant function for that EditText and call it with the data. (Or use get which throws an exception if the EditText isn't added to the map, which is a design error you want to get warned about, instead of silently ignoring it which is what the null check does)

EmptyDatabaseAlert showing twice

I have a Fragment that is a RecyclerView, its ViewModel that does a Room operation - add(). If the database is empty, that Fragment should show an AlertDialog that allows the user to either dismiss or create a new entry.
CrimeListFragment and relevant bits:
class CrimeListFragment:
Fragment(),
EmptyAlertFragment.Callbacks {
interface Callbacks {
fun onCrimeClicked(crimeId: UUID)
}
//==========
private var callback: Callbacks? = null
private lateinit var crimeRecyclerView: RecyclerView
private val crimeListViewModel: CrimeListViewModel by lazy {
ViewModelProviders.of(this).get(CrimeListViewModel::class.java)
}
//==========
override fun onAttach(context: Context) {
super.onAttach(context)
callback = context as Callbacks?
}
override fun onCreate(savedInstanceState: Bundle?) {}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
crimeListViewModel.crimeListLiveData.observe( //crimeListLiveData: LiveData<List<Crime>>
viewLifecycleOwner,
Observer { crimes ->
crimes?.let {
Log.i(TAG, "Retrieved ${crimes.size} crimes.")
updateUI(crimes)
}
}
)
}
override fun onDetach() {
super.onDetach()
callback = null
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {}
override fun onOptionsItemSelected(item: MenuItem): Boolean {}
override fun onCreateSelected() = createNewCrime()
//==========
private fun updateUI(crimes: List<Crime>) {
if(crimes.isEmpty()) {
Log.d(TAG, "empty crime list, show empty dialog")
showEmptyDialog()
}
(crimeRecyclerView.adapter as CrimeListAdapter).submitList(crimes)
Log.d(TAG, "list submitted")
}
private fun showEmptyDialog() {
Log.d(TAG, "show empty dialog")
EmptyAlertFragment.newInstance().apply {
setTargetFragment(this#CrimeListFragment, REQUEST_EMPTY)
show(this#CrimeListFragment.requireFragmentManager(), DIALOG_EMPTY)
}
}
private fun createNewCrime() {
val crime = Crime()
crimeListViewModel.addCrime(crime)
callback?.onCrimeClicked(crime.id)
Log.d(TAG, "new crime added")
}
//==========
companion object {}
//==========
private inner class CrimeHolder(view: View)
: RecyclerView.ViewHolder(view), View.OnClickListener {}
private inner class CrimeListAdapter
: ListAdapter<Crime, CrimeHolder>(DiffCallback()) {}
private inner class DiffCallback: DiffUtil.ItemCallback<Crime>() {}
}
My EmptyAlertFragment:
class EmptyAlertFragment: DialogFragment() {
interface Callbacks {
fun onCreateSelected()
}
//==========
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity!!)
builder.setPositiveButton("Create") {
_, _ ->
targetFragment?.let { fragment ->
(fragment as Callbacks).onCreateSelected()
}
}
builder.setNegativeButton("Cancel") {
dialog, _ ->
dialog.dismiss()
}
val alert = builder.create()
alert.apply {
setTitle("Crime list empty!")
setMessage("Do you want to create a new crime?")
}
return alert
}
//==========
companion object {
fun newInstance(): EmptyAlertFragment {
return EmptyAlertFragment()
}
}
}
And finally my MainActivity:
class MainActivity:
AppCompatActivity(),
CrimeListFragment.Callbacks {
override fun onCreate(savedInstanceState: Bundle?) {}
//==========
override fun onCrimeClicked(crimeId: UUID) {
val crimeFragment = CrimeDetailFragment.newInstance(crimeId)
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, crimeFragment)
.addToBackStack("crime")
.commit()
}
}
Basically the flow is this:
App launched, CrimeListFragment observes database, updateUI() gets called, database is empty so alert pops up aka EmptyAlertFragment gets shown, click on Create -> onCreateSelected() callback to CrimeListFragment.
onCreateSelected() calls createNewCrime() which uses ViewModel to add a crime (Room, Repository pattern), onCrimeClicked() callback to MainActivity.
MainActivity launches CrimeDetailFragment which shows either an existing or empty (new) crime for us to fill. We fill it and click back, crime gets saved: CrimeDetailFragment - onStop() { super.onStop; crimeDetailViewModel.saveCrime(crime) }
Database gets updated, CrimeListFragment observes database-change, updateUI() gets called, database is not empty so alert SHOULDN'T pop up but it does.
I click Create again, create second crime, tap back and the alert won't show again.
In other words the alert gets shown one time too many.
Logcat shows this:
`Retrieved 0 crimes`
`empty crime list, show empty dialog`
`show empty dialog`
`list submitted`
`*(I add a crime)*`
`new crime added`
`Retrieved 0 crimes` <--- Why? I just created a crime, Observer should notify and `updateUI()` should get called with a non-empty list
`empty crime list, show empty dialog`
`show empty dialog`
`list submitted`
`Retrieved 1 crimes.` <--- Correct behavior from here on out
Why does my dialog pop up twice instead of once?
This is due to how LiveData works: it caches and returns the last value before querying for updated data.
The first time your CrimeListFragment starts to observe the crimeListLiveData, it gets an empty list, correctly showing your dialog.
When you go to CrimeDetailFragment, the crimeListViewModel.crimeListLiveData is not destroyed. It retains the existing value - your empty list.
Therefore when you go back to your CrimeListFragment, onCreateView() runs again and you start observing again. LiveData immediately returns the cached value it had and Room asynchronously kicks off a query for updated data. Therefore it is expected that you first get an empty list before getting an updated, non-empty list.
You'll see the same behavior if you rotate your device while your EmptyAlertFragment is on the screen and the CrimeListFragment is behind it - you'll end up creating a second copy of your EmptyAlertFragment for the same reason. Then a third, fourth, fifth, etc. if you continue to rotate your device.
As per the Material design guidelines for dialogs, dialogs are for critical information or important decisions, so perhaps the most appropriate solution for your "Create a new crime" requirement is to not use a dialog at all, instead using an empty state in your CrimeListFragment alongside a Floating Action Button. Then, your updateUI method would simply switch between the empty state and your non-empty RecyclerView based on the count.
The other option is that your CrimeListFragment should keep track of whether you've displayed the dialog already in a boolean field, saving that boolean into the Bundle in onSaveInstanceState() to ensure it survives rotation and process death / recreation. That way you can be sure you only show the dialog just a single time for a given CrimeListFragment.

Kotlin DialogFragment editText editable always null

So, I'm using Kotlin extensions which is straightforward, but I can't get string from edittext
here is my code:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val v = activity.layoutInflater
.inflate(R.layout.dialog_group, null)
v.add_group_button.setOnClickListener(addListener)
return AlertDialog.Builder(activity)
.setView(v)
.create()
}
private var addListener: View.OnClickListener = View.OnClickListener {
val groupNameInput: String = view?.group_edit_text?.text.toString()
}
when I'm pressing add button groupNameInput always returns null why?
So finally I figure it out — on Dialog Fragment view will always be null, because its never created, but it's created and added to dialog view which means I need to call:
dialog.group_edit_text.text.toString()
Instead of:
view.group_edit_text.text.toString()

Categories

Resources