Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7900511
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T08:59:20+00:00 2026-06-03T08:59:20+00:00

I have a Fragment with a constructor that takes multiple arguments. My app worked

  • 0

I have a Fragment with a constructor that takes multiple arguments. My app worked fine during development, but in production my users sometimes see this crash:

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment 
make sure class name exists, is public, and has an empty constructor that is public

I could make an empty constructor as this error message suggests, but that doesn’t make sense to me since then I would have to call a separate method to finish setting up the Fragment.

I’m curious as to why this crash only happens occasionally. Maybe I’m using the ViewPager incorrectly? I instantiate all the Fragments myself and save them in a list inside the Activity. I don’t use FragmentManager transactions, since the ViewPager examples I have seen did not require it and everything seemed to be working during development.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T08:59:22+00:00Added an answer on June 3, 2026 at 8:59 am

    Yes they do.

    You shouldn’t really be overriding the constructor anyway. You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

    For example:

    public static final MyFragment newInstance(int title, String message) {
        MyFragment f = new MyFragment();
        Bundle bdl = new Bundle(2);
        bdl.putInt(EXTRA_TITLE, title);
        bdl.putString(EXTRA_MESSAGE, message);
        f.setArguments(bdl);
        return f;
    }
    

    And of course grabbing the args this way:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        title = getArguments().getInt(EXTRA_TITLE);
        message = getArguments().getString(EXTRA_MESSAGE);
    
        //...
        //etc
        //...
    }
    

    Then you would instantiate from your fragment manager like so:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState == null){
            getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.content, MyFragment.newInstance(
                    R.string.alert_title,
                    "Oh no, an error occurred!")
                )
                .commit();
        }
    }
    

    This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.

    Reason – Extra reading

    I thought I would explain why for people wondering why.

    If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java

    You will see the instantiate(..) method in the Fragment class calls the newInstance method:

    public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
        try {
            Class<?> clazz = sClassMap.get(fname);
            if (clazz == null) {
                // Class not found in the cache, see if it's real, and try to add it
                clazz = context.getClassLoader().loadClass(fname);
                if (!Fragment.class.isAssignableFrom(clazz)) {
                    throw new InstantiationException("Trying to instantiate a class " + fname
                            + " that is not a Fragment", new ClassCastException());
                }
                sClassMap.put(fname, clazz);
            }
            Fragment f = (Fragment) clazz.getConstructor().newInstance();
            if (args != null) {
                args.setClassLoader(f.getClass().getClassLoader());
                f.setArguments(args);
            }
            return f;
        } catch (ClassNotFoundException e) {
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": make sure class name exists, is public, and has an"
                    + " empty constructor that is public", e);
        } catch (java.lang.InstantiationException e) {
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": make sure class name exists, is public, and has an"
                    + " empty constructor that is public", e);
        } catch (IllegalAccessException e) {
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": make sure class name exists, is public, and has an"
                    + " empty constructor that is public", e);
        } catch (NoSuchMethodException e) {
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": could not find Fragment constructor", e);
        } catch (InvocationTargetException e) {
            throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": calling Fragment constructor caused an exception", e);
        }
    }
    

    http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public and that that class loader allows access to it.

    It’s a pretty nasty method all in all, but it allows the FragmentManger to kill and recreate Fragments with states. (The Android subsystem does similar things with Activities).

    Example Class

    I get asked a lot about calling newInstance. Do not confuse this with the class method. This whole class example should show the usage.

    /**
     * Created by chris on 21/11/2013
     */
    public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {
    
        public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
            StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();
    
            final Bundle args = new Bundle(1);
            args.putString(EXTRA_CRS_CODE, crsCode);
            fragment.setArguments(args);
    
            return fragment;
        }
    
        // Views
        LinearLayout mLinearLayout;
    
        /**
         * Layout Inflater
         */
        private LayoutInflater mInflater;
        /**
         * Station Crs Code
         */
        private String mCrsCode;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mInflater = inflater;
            return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
        }
    
        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
            //Do stuff
        }
    
        @Override
        public void onResume() {
            super.onResume();
            getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
        }
    
        // Other methods etc...
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a fragment that I need to display on the screen. I want
Java Exception: http://hastebin.com/yiwecefifi.avrasm I have an object, that I call Category, that my fragment
I have a document created in a constructor, and during execution I'm filling it
I have a fragment which has its own state (selected buttons, etc). That state
I have a fragment class that extends Fragment and calls setHasOptionsMenu to participate in
I have this fragment that demonstrates the problem: <html> <head> <title>height query demo</title> <script
I have a fragment in an activity that I am using as a navigation
In an Android application I have a fragment implemented that overrides onViewCreated to set
I have a fragment shader with the following attributes: varying highp vec2 coordinate; precision
I have a fragment where I wish to call a method from the FragmentActivity

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.