Send data from activity to fragment in Android

2018-12-31 01:05发布

I have two classes. First is activity, second is a fragment where I have some EditText. In activity I have a subclass with async-task and in method doInBackground I get some result, which I save to variable. How can I send this variable from subclass "my activity" to this fragment?

19条回答
浮光初槿花落
2楼-- · 2018-12-31 01:10

Use following interface to communicate between activity and fragment

public interface BundleListener {
    void update(Bundle bundle);
    Bundle getBundle();
}

Or use following this generic listener for two way communication using interface

 /**
 * Created by Qamar4P on 10/11/2017.
 */
public interface GenericConnector<T,E> {
    T getData();
    void updateData(E data);
    void connect(GenericConnector<T,E> connector);
}

fragment show method

public static void show(AppCompatActivity activity) {
        CustomValueDialogFragment dialog = new CustomValueDialogFragment();
        dialog.connector = (GenericConnector) activity;
        dialog.show(activity.getSupportFragmentManager(),"CustomValueDialogFragment");
    }

you can cast your context to GenericConnector in onAttach(Context) too

in your activity

CustomValueDialogFragment.show(this);

in your fragment

...
@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        connector.connect(new GenericConnector() {
            @Override
            public Object getData() {
                return null;
            }

            @Override
            public void updateData(Object data) {

            }

            @Override
            public void connect(GenericConnector connector) {

            }
        });
    }
...
    public static void show(AppCompatActivity activity, GenericConnector connector) {
            CustomValueDialogFragment dialog = new CustomValueDialogFragment();
            dialog.connector = connector;
            dialog.show(activity.getSupportFragmentManager(),"CustomValueDialogFragment");
        }

Note: Never use it like "".toString().toString().toString(); way.

查看更多
路过你的时光
3楼-- · 2018-12-31 01:11

My solution is to write a static method inside the fragment:

public TheFragment setData(TheData data) {
    TheFragment tf = new TheFragment();
    tf.data = data;
    return tf;
}

This way I am sure that all the data I need is inside the Fragment before any other possible operation which could need to work with it. Also it looks cleaner in my opinion.

查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 01:12

Smartest tried and tested way of passing data between fragments and activity is to create a variables,example:

class StorageUtil {
  public static ArrayList<Employee> employees;
}

Then to pass data from fragment to activity, we do so in the onActivityCreated method:

//a field created in the sending fragment
ArrayList<Employee> employees;

@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
         employees=new ArrayList();

       //java 7 and above syntax for arraylist else use employees=new ArrayList<Employee>() for java 6 and below

     //Adding first employee
        Employee employee=new Employee("1","Andrew","Sam","1984-04-10","Male","Ghanaian");
        employees.add(employee);

      //Adding second employee
       Employee employee=new Employee("1","Akuah","Morrison","1984-02-04","Female","Ghanaian");
         employees.add(employee);

        StorageUtil.employees=employees;
    }

Now you can get the value of StorageUtil.employees from everywhere. Goodluck!

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 01:15

Very old post, still I dare to add a little explanation that would had been helpful for me.

Technically you can directly set members of any type in a fragment from activity.
So why Bundle?
The reason is very simple - Bundle provides uniform way to handle:
-- creating/opening fragment
-- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState()
-- app restoration after being garbage collected in background (as with reconfiguration).

You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward.
That's why the answer by @Elenasys is the most elegant and universal solution.
And that's why the answer given by @Martin has pitfalls

查看更多
永恒的永恒
6楼-- · 2018-12-31 01:15

In your activity declare static variable

public static HashMap<String,ContactsModal> contactItems=new HashMap<String, ContactsModal>();

Then in your fragment do like follow

ActivityName.contactItems.put(Number,contactsModal);
查看更多
梦寄多情
7楼-- · 2018-12-31 01:16

I´ve found a lot of answers here @ stackoverflow.com but definitely this is the correct answer of:

"Sending data from activity to fragment in android".

Activity:

        Bundle bundle = new Bundle();
        String myMessage = "Stackoverflow is cool!";
        bundle.putString("message", myMessage );
        FragmentClass fragInfo = new FragmentClass();
        fragInfo.setArguments(bundle);
        transaction.replace(R.id.fragment_single, fragInfo);
        transaction.commit();

Fragment:

Reading the value in the fragment

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        String myValue = bundle.getString("message");
        ...
        ...
        ...
        }

or just

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        String myValue = this.getArguments().getString("message");
        ...
        ...
        ...
        }
查看更多
登录 后发表回答