Andrew
Andrew

Reputation: 2157

How to send data from dialog to my activity kotlin?

I have at my app dialog which sends data to host activity. In Java I had to implement interface from this dialog and everything worked fine. At kotlin I saw that my listener isn't called anyway. At my dialog I have two buttons which call activity class:

okFilter.setOnClickListener(view1 -> {
            dismiss();
            Intent intent = new Intent(getContext(), HomeScreen.class);
            intent.putExtra("filter_data",data);
            intent.putExtra("id",4);
            startActivity(intent);
        });

and I have also interface:

public interface OnButtonClick {
        void onDialogClickListener(Integer job_type, HashMap<String, String> filter_data);
    }

but onDialogClickListener isn't used anyway :( Then I have implemented this interface at hosting activity:

override fun onDialogClickListener(job_type: Int?, filter_data: java.util.HashMap<String, String>?) {

        bottom_navigation_t.selectedItemId = R.id.full_jobAgent
        val jobList = JobList()
        val bundle = Bundle()
        bundle.putInt("offset", 1)
        bundle.putSerializable("filter_data", data)
        jobList.arguments = bundle
        transaction.replace(R.id.contentContainerT, jobList).addToBackStack(null).commit()
    }

and it doesn't work. This fun isn't called and I catch only intent data. In Java it worked, what I did wrong?

Upvotes: 1

Views: 2782

Answers (1)

Harshad Prajapati
Harshad Prajapati

Reputation: 830

Try this

Implement your interface in your activity.

class MainActivity : AppCompatActivity(), OnButtonClick {

override fun onDialogClickListener(job_type: Int,filter_data: HashMap<String, String>) {
    Log.e("MainActivity ",job_type+"")
    Log.e("MainActivity ",filter_data+"")
  }

}

And if you are using dialog fragment than just do this give context to interface object in onAttach.

class CustomDialog: DialogFragment() {
     var listener: OnButtonClick ? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as OnButtonClick
    }

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view: View =
            activity!!.layoutInflater.inflate(R.layout.your_dialog_view, container, false)

        view.button!!.setOnClickListener {
            listener!!.onDialogClickListener(your_job_type, your_map)
        }
        return view
    }
}

Upvotes: 3

Related Questions