vendredi 20 novembre 2020

How to use interfaces as listeners from and Dialoge in Android?

Good morning Ladies and Gentlemen,

I have a really big problem and can't go on. I don't know how I can use a interface in android as an event listener. I defined an interface ProfilePictureTakenEvent with the method onProfilePictureTaken. In an dialog, which is opened by a button click on a fragment, the user can take an Image with the camera. I used the method startActivityForResult for it. The result (the image) of this action I get in the fragment (the overriden method onActivityResult). Now my question: How can I show this picture in my dialog when I get the result in my fragment? I thought that I can use an event listener, but I don't know how and didn't find any Explanation.

Here my code:

UserFragment.tk

class UserFragment() : Fragment() {
    private var userFragment: UserFragment? = null
    private var profilePictureTakenEvent: ProfilePictureTakenEvent? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_user, container, false)
    }

    override fun onViewCreated(
        view: View,
        savedInstanceState: Bundle?
    ) {
        super.onViewCreated(view, savedInstanceState)

        this.userFragment = this

        val database = UserManagerDatabase(view.context)
        val repository = UserRepository(database)
        val factory = UserViewModelFactory(repository)

        val viewModel = ViewModelProviders.of(this, factory).get(UserViewModel::class.java)
        val adapter = UserAdapter(listOf(), viewModel)

        rvUsers.layoutManager = LinearLayoutManager(view.context)
        rvUsers.adapter = adapter

        var emailAddresses: List<String> = emptyList()

        viewModel.getAll().observe(viewLifecycleOwner, { userList ->
            adapter.users = userList
            emailAddresses = userList.map { user -> user.email }

            adapter.notifyDataSetChanged()
        })

        viewModel.getEmailAddresses().observe(viewLifecycleOwner, {emailAddresses = it })

        fBtnAddUser.setOnClickListener {
            AddUserDialog(view.context,
            object: UserCreateEvent {
                override fun onAddButtonClicked(user: User) {
                    viewModel.insert(user)
                }
            }, emailAddresses, userFragment).show()
        }
    }

    fun setProfilePictureTakenEvent(profilePictureTakenEvent: ProfilePictureTakenEvent) {
        this.profilePictureTakenEvent = profilePictureTakenEvent
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == AddUserDialog.REQUEST_IMAGE_CAPTURE) {
            this.profilePictureTakenEvent?.onProfilePictureTaken(data)
        }
    }
}

AddUserDialog.kt:

class AddUserDialog(
    context: Context,
    private var userCreateEvents: UserCreateEvent,
    private var emails: List<String>,
    private var parentFragment: UserFragment?
) : AppCompatDialog(context), ProfilePictureTakenEvent {

    companion object {
        const val REQUEST_IMAGE_CAPTURE = 1
    }

    private var imageData: Bitmap? = null

    override fun onProfilePictureTaken(data: Intent?) {
        this.ivProfilePicture.setImageBitmap(data?.extras?.get("data") as Bitmap)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_add_user)
        setTitle(context.getString(R.string.title_add_user))

        val editTextViews: Map<String, EditText> = mapOf(
            "first_name"            to dAddUserEdFirstName,
            "last_name"             to dAddUserEdLastName,
            "email"                 to dAddUserEdEmail,
            "password"              to dAddUserEdPassword,
            "password_confirmation" to dAddUserEdPasswordConfirmation
        )

        dAddUserBtnSave.setOnClickListener {
            val firstName               = dAddUserEdFirstName.text.toString()
            val lastName                = dAddUserEdLastName.text.toString()
            val username                = "${firstName.toLowerCase(Locale.GERMAN)}-${lastName.toLowerCase(Locale.GERMAN)}"
            val email                   = dAddUserEdEmail.text.toString()
            val password                = dAddUserEdPassword.text.toString()
            val passwordConfirmation    = dAddUserEdPasswordConfirmation.text.toString()

            var error = false
            val emptyFields: StringBuilder = StringBuilder()

            // Check if any EditText is empty
            editTextViews.forEach {(key, editTextView) ->
                val textEmpty: Boolean = editTextView.text.toString().isEmpty()

                if (textEmpty) {
                    error = true
                    emptyFields.append("${context.getString(AppHelper.stringTranslation(key))}, ")
                }

                AppHelper.updateBackground(context, editTextView, if (textEmpty) R.drawable.input_field_error else R.drawable.input_field)
            }

            if (error) {
                //AppHelper.showToastLong(context, context.getString(R.string.error_field_not_filled, AppHelper.commaStringToCorrectGrammatical(context, emptyFields.toString())))
                return@setOnClickListener
            }

            // Check if E-Mail address is valid
            if (AppHelper.invalidEmail(email)) {
                AppHelper.showToastShort(context, R.string.error_invalid_email)
                return@setOnClickListener
            }

            // Check if supplied E-Mail address is unique
            if (emails.contains(email)) {
                AppHelper.showToastShort(context, R.string.error_email_already_taken)
                return@setOnClickListener
            }

            // Check if password and password confirmation match
            if (password != passwordConfirmation) {
                AppHelper.showToastShort(context, R.string.error_password_confirmation_not_matching)
                return@setOnClickListener
            }

            //TODO: Password hashing

            // Creating the User
            val user = User(firstName, lastName, username, email, password)
            userCreateEvents.onAddButtonClicked(user)

            // Closing the dialog after calling the onClickEvent and data is valid
            dismiss()
        }

        btnTakeProfilePicture.setOnClickListener {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            try {
                parentFragment?.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            } catch (e: ActivityNotFoundException) {
                AppHelper.showToastLong(context, "Fehler")
            }
        }

        // Close dialog when cancel Button is clicked
        dAddUserBtnCancel.setOnClickListener { cancel() }
    }

}

ProfilePictureTakenEvent.kt:

interface ProfilePictureTakenEvent {
    fun onProfilePictureTaken(data: Intent?)
}

Thanks for your Help. Best regards,

Daniel

Aucun commentaire:

Enregistrer un commentaire