简体   繁体   中英

Passing a file from Activity to fragment using Bundle

Ok So I'm trying yo pass any file from file manager(Activity) to the fragment. Here is my code:

               Bundle bundle = new Bundle ();
                    bundle.putString ("File", chosenFile);
                    Intent intent = new Intent (getApplicationContext (), UploadFragment.class);
                    intent.putExtras (bundle);
                    startActivity (new Intent (FileExplore.this, UploadFragment.class));

The app crashes in the Logcat is states unable to find explicit activity class. Which then gives me the line where the code error occurs which is startActivity(new Intent(.....). Is the error because I'm not sending the Intent correctly from Activity to a Fragment?

In the Fragment I have the following code under the button.setOnclickListener().

Intent intent = new Intent (getActivity (), FileExplore.class);
            startActivity (intent);

First of all you can't create fragment or send data to it using Intent.

You can put a fragment inside you activity by calling: getFragmentManager().beginTransaciton().add(R.id.id_of_container, new UploadFragment(), false).commit();

If you want to pass data from activity to fragment you do it on fragment creation using setArgument() method, for example:

Bundle bundle = new Bundle ();
bundle.putString ("File", chosenFile);

UploadFragment fragment = new UploadFragment();
fragment.setArguments(bundle);

getFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();

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