How to send data from activity page to fragment page

20 Views Asked by At

I have a problem with passing the data from Main Activity to Home Fragment. If I click the submit button it will automatically showing the result data in the same page, not transfer to the Home Fragment class interface.

package com.example.dummy;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText nameEdit,mobileEdit;
    Button btn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nameEdit= findViewById(R.id.nameEdit);
        mobileEdit= findViewById(R.id.mobileEdit);
        btn = findViewById(R.id.submitBtn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            sendDatatoFragment();

        }
    });

    }

    private void sendDatatoFragment() {

        String name,mobile = "";

        name = nameEdit.getText().toString();
        mobile = mobileEdit.getText().toString();

        Fragment frag = new HomeFragment();

        Bundle bundle = new Bundle();

        bundle.putString("username", name);
        bundle.putString("usermobile", mobile);

        frag.setArguments(bundle);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.container,frag).commit();
    }

}
package com.example.dummy;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class HomeFragment extends Fragment {

    TextView details;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View view =  inflater.inflate(R.layout.fragment_home, container, false);
    
        details = view.findViewById(R.id.details);
    
       Bundle bundle= this.getArguments();
    
       details.setText("Name:" + bundle.getString("username") + "\nMobile:" + bundle.getString("usermobile"));
    
    
        return view;
    }

}

I want the result are display in HomeFragment class page. Not in the same place, because it makes the Main Activity and Home Fragment layouts pile up

0

There are 0 best solutions below