【问题标题】:Unable to access member variable in onOptionsItemSelected in android activity无法访问 android 活动中 onOptionsItemSelected 中的成员变量
【发布时间】:2020-06-23 07:40:45
【问题描述】:

我正在尝试使用浏览器打开从先前活动传递的某个 URL。点击右侧的重定向图标,打开预期的网页。

这是我的代码。

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);
        }
    }
    ...
}

问题是itemUrlnullonOptionsItemSelected 范围内。

我已在onCreate 中为itemUrl 赋值。但是,如日志所示,它是null

希望得到您的帮助。非常感谢! :-)

【问题讨论】:

    标签: java android android-activity android-lifecycle android-menu


    【解决方案1】:

    onCreate 方法中,您使用的是局部变量。

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

    【讨论】:

    • 愚蠢的我!浪费我的2小时!谢谢
    【解决方案2】:

    您正在为 String itemUrl = intent.getStringExtra("itemUrl"); (一旦其范围完成后立即结束其生命的局部变量)分配值,但从 this.itemUrl (您的托管实体的字段)中读取它。您需要在同一个地方写入和读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多