skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.EditText;
    
    import androidx.fragment.app.Fragment;
    
    public class ConversationFragment extends Fragment {
    
        private EditText editText;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_conversation, container, false);
    
            // Initialize EditText
            editText = view.findViewById(R.id.editText);
    
            return view;
        }
    
        public String getEditTextValue() {
            return editText.getText().toString();
        }
    }
    

    MainActivity.java:

    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        private ConversationFragment conversationFragment;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Initialize the fragment
            conversationFragment = new ConversationFragment();
    
            // Add the fragment to the container
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, conversationFragment)
                    .commit();
    
            // Initialize Button
            Button button = findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Get EditText value from the Fragment
                    String editTextValue = conversationFragment.getEditTextValue();
                    onDataReceivedFromFragment(editTextValue);
                }
            });
        }
    
        public void onDataReceivedFromFragment(String data) {
            // Process the received data here
            Log.d("Data received in Activity", data);
        }
    }
    

    Method 2

    By using interface

    ConversationFragment.java:

        import android.os.Bundle;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.EditText;
    
        import androidx.fragment.app.Fragment;
    
        public class ConversationFragment extends Fragment {
    
            private EditText editText;
            private EditTextValueListener listener;
    
            public interface EditTextValueListener {
                void onEditTextValueChanged(String value);
            }
    
            public void setEditTextValueListener(EditTextValueListener listener) {
                this.listener = listener;
            }
    
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                    Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.fragment_conversation, container, false);
    
                // Initialize EditText
                editText = view.findViewById(R.id.editText);
    
                return view;
            }
    
            private void sendDataToActivity(String data) {
                if (listener != null) {
                    listener.onEditTextValueChanged(data);
                }
            }
    
            public void sendDataToActivity() {
                String data = editText.getText().toString();
                sendDataToActivity(data);
            }
        }
    

    MainActivity.java:

        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.Button;
    
        import androidx.appcompat.app.AppCompatActivity;
    
        public class MainActivity extends AppCompatActivity implements ConversationFragment.EditTextValueListener {
    
            private ConversationFragment conversationFragment;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
    
                // Initialize the fragment
                conversationFragment = new ConversationFragment();
    
                // Add the fragment to the container
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.fragment_container, conversationFragment)
                        .commit();
    
                // Initialize Button
                Button button = findViewById(R.id.button);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Call method in Fragment to send EditText value
                        conversationFragment.sendDataToActivity();
                    }
                });
            }
    
            @Override
            public void onEditTextValueChanged(String value) {
                // Process the received data here
                Log.d("Data received in Activity", value);
            }
        }
    

    Ensure that you also update the layout files (fragment_conversation.xml and activity_main.xml) accordingly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search