Send data from activity to fragment in Android

前端 未结 20 2701
悲哀的现实
悲哀的现实 2020-11-21 05:13

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 doInBa

20条回答
  •  臣服心动
    2020-11-21 05:35

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

    class StorageUtil {
      public static ArrayList employees;
    }
    

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

    //a field created in the sending fragment
    ArrayList 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() 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!

提交回复
热议问题