Search code examples
javaandroidandroid-activityandroid-lifecycleandroid-menu

Unable to access member variable in onOptionsItemSelected in android activity


I am trying to open a certain URL passed from previous activity with the browser. Click on the redirect icon on the right side, open the expected web page.

enter image description here

Here are my codes.

public class DetailedProduct extends AppCompatActivity {
    private Menu menu;
    private String itemId;
    private String itemUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d("DetailedProduct-LifeCycle","------------onCreate------------");
        setTheme(R.style.AppTheme);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed_product);
        Intent intent = getIntent();
        String itemId = intent.getStringExtra("itemId");
        String itemUrl = intent.getStringExtra("itemUrl");
        Log.d("itemUrl", itemUrl);
        ActionBar actionBar = getSupportActionBar();
//        actionBar.setDisplayHomeAsUpEnabled(true);
        setTitle(itemId);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.v("Menu","----------menuCreate----------");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.detail_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.v("Menu", "-----------menuSelect---------");
        if(itemUrl==null){
            Log.v("Menu", "---------Cannot acquire predefined itemUrl---------");
        }
        else{
            Log.d("itemUrlInner", itemUrl);
        }

        switch(item.getItemId()){
            case R.id.redirect:

                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(this.itemUrl));
                startActivity(browserIntent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    ...
}

The issue is that itemUrl is null in the scope of onOptionsItemSelected.

I have assigned value to itemUrl in onCreate. However, as the log shows, it is null.

enter image description here

Hope for your help. Thanks a lot! :-)


Solution

  • In the onCreate method you are using a local variable.

    private String itemUrl;
    
    protected void onCreate(Bundle savedInstanceState) {
        ....
        //String itemUrl = intent.getStringExtra("itemUrl");  //It is a different variable!
        itemUrl = intent.getStringExtra("itemUrl");
    }