0

I am unable to do any changes to the textview's value using a fragment's onCreateOptionsMenu. I am using a badge so i can change to value of the badge on the actionbar. But the app crashes!

this is my code:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        inflater.inflate(R.menu.navigation_drawer, menu);
        MenuItem item = menu.findItem(R.id.add);
        RelativeLayout badgeLayout = (RelativeLayout) item.getActionView();
        mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
        mCounter.setText("2");// THIS PART MAKES THE CODE CRASH
        super.onCreateOptionsMenu(menu, inflater);
    }

THIS IS THE ERROR THAT I GET:

   java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                                       at comb.example.shahid.carrottechapp.FragmentList.onCreateOptionsMenu(FragmentList.java:383)

Please help me solve this!

Shahid Sarwar
  • 1,060
  • 12
  • 25
  • Nope its not a duplicate. I am unable to get reference of the textview named as "mCounter" because its getting inflated by a menuItem. – Shahid Sarwar Jun 24 '16 at 09:05

1 Answers1

0

Solved it by using this code:

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.navigation_drawer, menu);
    MenuItem item = menu.findItem(R.id.add);
    RelativeLayout badgeLayout = (RelativeLayout) MenuItemCompat.getActionView(item);
    mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
    mCounter.setText("2");
    super.onCreateOptionsMenu(menu, inflater);
}
Shahid Sarwar
  • 1,060
  • 12
  • 25