Search code examples
androidvariablesoncreateoptionsmenu

Variable not updating in onCreateOptionsMenu method, android Java


I have an integer variable that is not being updated when a share intent is activated. What am I missing? Thanks.

Integer i1 is declared in the class:

private int i1;

Here is the onCreateOptionsMenu method

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.pun, menu);
        star = menu.findItem(R.id.action_favoritestar);
        init();

        MenuItem shareItem = (MenuItem) menu.findItem(R.id.menu_item_share);

        shareAction = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(intent.EXTRA_TEXT, "\"" + mLines.get(i1));

        shareAction.setShareIntent(intent);

        return true;
    }

The variable is modified when a button is pressed:

final Button btn1 = (Button) findViewById(R.id.next);
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                star.setIcon(R.drawable.starblank);

            Random r = new Random();
            i1 = r.nextInt(20 - 1) + 1;

            textView.setText(mLines.get(i1));

           }
    });

Solution

  • Found a solution. The share options menu was not being updated more than once. I called invalidateOptionsMenu() after each button press.