I want to get Data to main activity from the fragment, my data is in the fragment, and when I click a button on the main activity, I need to grab that data within the main activity
I found a solution from StackOverflow, and here it is.
public void getFromUser(View view) {
ConversationFragment fragment1 = (ConversationFragment)getSupportFragmentManager().findFragmentById(R.id.container);
View frag=fragment1.getView();
EditText editText1 =(EditText) frag.findViewById(R.id.message);
String message=editText1.getText().toString();
sendMessage(message);
}
but few people have mentioned that it is a bad practice, then I heard of doing something like that with an interface, I am new to Java, so can someone mention a sample of getting data to the main activity from a fragment with a button click on a main activity
2
Answers
Use a ViewModel for this: https://developer.android.com/guide/fragments/communicate
then you can observe changes for the data and do whatever you want with it.
Yes onAttachFragment is deprecated from Android 9 you can use other methods to achieve similar functionality, depending on the context of the code. But as of now, that is not required as you are not doing any fragment transition.
Method 1
By using public function
ConversationFragment.java:
MainActivity.java:
Method 2
By using interface
ConversationFragment.java:
MainActivity.java:
Ensure that you also update the layout files (fragment_conversation.xml and activity_main.xml) accordingly.