Question

I have a fragment that after clicking an item in the listview, loads a new fragment. If I use the backbutton to go back to the first fragment I get a FC with this error:

3-03 19:37:38.193  30258-30258/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.beerportfolio.beerportfoliopro.Portfolio$1.onItemSelected(Portfolio.java:93)
            at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
            at android.widget.AdapterView.selectionChanged(AdapterView.java:879)
            at android.widget.AdapterView.checkSelectionChanged(AdapterView.java:1043)
            at android.widget.AdapterView.handleDataChanged(AdapterView.java:1022)
            at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:180)
            at android.widget.Spinner.onMeasure(Spinner.java:441)
            at android.view.View.measure(View.java:16088)
            at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1226)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16088)
            at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:651)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5061)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2277)
            at android.view.View.measure(View.java:16088)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2109)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1219)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1403)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5849)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:786)
            at android.view.Choreographer.doCallbacks(Choreographer.java:586)
            at android.view.Choreographer.doFrame(Choreographer.java:546)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:771)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:158)
            at android.app.ActivityThread.main(ActivityThread.java:5789)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
            at dalvik.system.NativeStart.main(Native Method)

The code for this fragment is:

public class Portfolio extends Fragment implements PortfolioGetAllBeers.OnArticleSelectedListener {

    String beerId = "";
    String userName;
    String userID;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //set layout here
        final View theLayout = inflater.inflate(R.layout.activity_portfolio, container, false);
        setHasOptionsMenu(true);
        getActivity().setTitle("Portfolio");

        //get user information
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        userName = prefs.getString("userName", null);
        userID = prefs.getString("userID", null);

        final Spinner portfolioType = (Spinner) theLayout.findViewById(R.id.portfolioSpinner);
        portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {


            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

                String portfolioChoice = portfolioType.getSelectedItem().toString();


                Log.d("portfolio", portfolioChoice);

                PortfolioGetAllBeers.OnArticleSelectedListener thisOne;
                thisOne = Portfolio.this;

                if( portfolioChoice.equals("All")){


                    //todo: clear second spinner
                    LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
                    ll.removeAllViews();

                    //get userID
                    //get user data


                    //construct url
                    String url = "myurl1";


                    //async task goes here


                    PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
                    task.setOnArticleSelectedListener(Portfolio.this);
                    task.execute(url);

                }

                else if (portfolioChoice.equals("Brewery")){

                    LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
                    ll.removeAllViews();
                    LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
                    View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
                    Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
                    ll.addView(v); // add the view to the linear layout

                    //todo: get breweries and fill spinner
                    //get userID
                    //get user data
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
                    String userID = prefs.getString("userID", null);

                    //construct url
                    String url = "http://beerportfolio.com/app_getAllYourBreweries.php?u=" + userID;


                    //async task goes here
                    new PortfolioGetAllBreweries(selectedItemView.getContext(), thisOne).execute(url);



                }


                else if (portfolioChoice.equals("Style")){

                    LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
                    ll.removeAllViews();
                    LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
                    View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
                    Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
                    ll.addView(v); // add the view to the linear layout

                    //get userID
                    //get user data
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
                    String userID = prefs.getString("userID", null);



                    //construct url
                    String url = "myurl2";



                    //todo: async task goes here

                    new PortfolioGetAllStyles(selectedItemView.getContext(), thisOne).execute(url);

                }

                else if (portfolioChoice.equals("Rating")){

                    LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
                    ll.removeAllViews();
                    LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
                    View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
                    Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
                    ll.addView(v); // add the view to the linear layout

                    //get userID
                    //get user data
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
                    String userID = prefs.getString("userID", null);

                    //make array

                    //make array list for beer
                    final List<String> tasteList = new ArrayList<String>();
                    tasteList.add("1");
                    tasteList.add("2");
                    tasteList.add("3");
                    tasteList.add("4");
                    tasteList.add("5");

                    // Selection of the spinner
                    Spinner spinner = (Spinner) theLayout.findViewById(R.id.portfolioSpinner2);

                    // Application of the Array to the Spinner
                    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(selectedItemView.getContext(),   android.R.layout.simple_spinner_item,tasteList );
                    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
                    spinner.setAdapter(spinnerArrayAdapter);



                    //todo: add on select for spinner 2
//add on item selected
                    final Spinner portfolioType = (Spinner) theLayout.findViewById(R.id.portfolioSpinner2);
                    portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {


                        @Override
                        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

                            String portfolioChoice = portfolioType.getSelectedItem().toString();

                            //Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
                            final ListView lv = (ListView) theLayout.findViewById(R.id.allYourBeersList);
                            lv.setAdapter(null);

                            //get brewery beers
                            //get userID
                            //get user data
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
                            String userID = prefs.getString("userID", null);



                            try {

                                portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                            //construct url
                            String url = "myurl3";

                            Log.d("portfolio" , url);
                            //async task goes here
                            PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
                            task.setOnArticleSelectedListener(Portfolio.this);
                            task.execute(url);



                        }



                        @Override
                        public void onNothingSelected(AdapterView<?> parentView) {
                            // do nothing
                        }

                    });




                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // do nothing
            }

        });



        // Inflate the layout for this fragment
        return theLayout;

    }

    @Override
    public void onArticleSelected(String bID, String brewery){

        //code to execute on click
        Fragment Fragment_one;
        FragmentManager man= getFragmentManager();
        FragmentTransaction tran = man.beginTransaction();
        Fragment_one = new BeerPage();
        final Bundle bundle = new Bundle();
        bundle.putString("beerIDSent", bID);
        bundle.putString("breweryIDSent", brewery);
        Fragment_one.setArguments(bundle);
        tran.replace(R.id.main, Fragment_one);//tran.
        tran.addToBackStack(null);
        tran.commit();

    }

}

Line 92 that the error refers to is:

 LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);

No correct solution

OTHER TIPS

Do not refer to context this way.

Use:

Context ctx = getActivity();

And then use ctx where you use selectedItemView.getContext()

Instead of geting LayoutInflater from system service, try:

LayoutInflater inflater = LayoutInflater.from(ctx);

See if this helps :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top