1

I want to pass some data from a fragment to an activity.

This question has been asked already many times, and this answer is the best i have found so far.

I have followed the official documentation, but I still haven't got any results. What I have so far in the fragment is:

public class DropPackageFourthFragment1 extends Fragment {

    public DropPackageFourthFragment1() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_drop_package_fourth_fragment1, container, false );

        passData("hellooooo");
        return  v;


    }

    //Pass data to activity
    OnDataPass dataPasser;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity a;
        if (context instanceof Activity){
            a=(Activity) context;


            dataPasser = (OnDataPass) a;
        }

    }


    public interface OnDataPass {
        public void onDataPass(String data);
    }
    public void passData(String data) {
        dataPasser.onDataPass(data);
    }
}

And in the main activity i have:

public class DropPackageFourth extends AppCompatActivity  implements DropPackageFourthFragment1.OnDataPass{


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

}

    @Override
    public void onDataPass(String data) {
        Log.d("LOG","hello " + data);
    }
}

The LogCat doesn't show anything, I feel like i'm missing something, but I cannot find what it is! Any help would be appreciated!

Community
  • 1
  • 1
Alvaro
  • 1,430
  • 2
  • 23
  • 41

2 Answers2

0

Use EventBus. https://github.com/greenrobot/EventBus or RxAndroid's PublishSubject https://github.com/ReactiveX/RxAndroid

jihoon kim
  • 1,270
  • 1
  • 16
  • 22
0

The code is in fact working, I was just filtering the LogCat and i wasn't seeing anything!

Alvaro
  • 1,430
  • 2
  • 23
  • 41