CoderTn
CoderTn

Reputation: 997

Passing data from activity to fragment in android is not working

I want to pass parameters from activity to fragment. This is the code from the activity:

public class MatchActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_match);
        Bundle bundle = new Bundle();
        bundle.putString("edttext", "From Activity");
        MarqueFragment fragobj = new MarqueFragment();
        fragobj.setArguments(bundle);

    }

}

This is the code from the fragment:

public class MarqueFragment extends Fragment {

    @Override
    public void onCreate ( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView ( LayoutInflater inflater, ViewGroup container,   Bundle savedInstanceState ) {
        View convertView=inflater.inflate(R.layout.fragment_marque, container, false);


            if (getArguments() != null) {
                String mParam1 = getArguments().getString("edttext");
                System.out.println("got this from MatchActivity "+mParam1);
            }else{
                System.out.println("got nothing");
            }     
}

I am not getting any arguments I don't know why. Notice : am not getting an error am getting "got nothing" as output.

Upvotes: 2

Views: 171

Answers (1)

John Joe
John Joe

Reputation: 12803

Change your code to this

Bundle bundle = new Bundle();
bundle.putString(edttext", "From Activity");
MarqueFragment fragobj = new MarqueFragment();
fragobj.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_marque, fragobj);
transaction.commit();

Upvotes: 1

Related Questions