简体   繁体   中英

how to pass string data from activity to fragment?

I want to pass string value from activity to fragment. For that I'm using bundle for transferring string value.

PUT STRING ACTIVITY Passing string value :-

           Bundle bundle = new Bundle();
            bundle.putString("Value", resultp.get(CurrentProjectActivity.VALUE));
            Log.d(TAG, "Value  ::: " + resultp.get(CurrentProjectActivity.VALUE));
            // set Fragmentclass Arguments
            AmenetiesFragment fragobj = new AmenetiesFragment();
            fragobj.setArguments(bundle);

In log I got "Value" value as well.

GET STRING VALUE IN FRAGMENT (IT IS NOT WORKING).

     @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.activity_listview, container, false);
    Bundle bundle = this.getArguments();
    Log.d(TAG, "Value's value:)  ::: " + bundle);
    String strtext = bundle.getString("Value");
    return rootView;
}

In log I'm getting NULL value for BUNDLE. Please help me to resolve this Issue. Thanks in advance.

I advice you to follow this link1 and this . You should use interface. Check here

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in the Frament task

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

Suppose you want to send String data from Activity to Fragment

In Fragment.java file add the following code,

public static String name= null;

public void setName(String string){
name = string;
}

In MainActivity.java from which you want to send String add the following code,

String stringYouWantToSend;

Fragment fragment =  new Fragment();
fragment.setName(stringYouWantToSend);   

make public first in activity that object you required in fragment. then you can use like ((ACtivityName)getActivity()).objectName; i hope it help.this is not best way to pass data into fragment.

there are some other way also. create constructor of your fragment class and pass it and save in fragment like:

    public MyFragment(String data){
       this.data = data;
    }

also you can use as bundle @james answer.

EDIT:-

First Way

private class MyFeagment extends Fragment {
    private String data;
    private Object myObject;

    public MyFeagment(String data, Object anyObject) {
        this.data = data;
        this.myObject = myObject;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Log.i("My Fragment", "data :: " + data + " and myObject :"
                + myObject);
        return super.onCreateView(inflater, container, savedInstanceState);
    }
}

let's say it is your framgnet. and put this code in your activity

FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.fragment_container, new MyFeagment("My Data",
            "data"));
    transaction.commit();

The savedInstance variable will be empty the first time you run your app, it only gets filled when the onSaveInstanceState method is called, this usually happens when you rotate the screen, then savedInstance variable will be populated. Try this :

if(savedInstance != null){
  Log.d(TAG, "There's is something");
}else{
  Log.d(TAG, "Nothing in there");
}

First time in logcat you will see the first message, try turning your device and the message in the else will show.

As @james said, the recommended way is to use interfaces, or have a field class but this increases coupling and destroys the whole point of fragments.

Easiest Approach but not Recommended

You can access activity data from fragment:

Activity:

public class MyActivity extends Activity {

    private String myString = "hello";

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

    public String getMyData() {
        return myString;
    }
}

Fragment:

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        MyActivity activity = (MyActivity) getActivity();
        String myDataFromActivity = activity.getMyData();
        return view;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM