Check if extras are set or not

前端 未结 5 1378
余生分开走
余生分开走 2020-12-13 01:28

Is there any way to check if an extra has been passed when starting an Activity?

I would like to do something like (on the onCreate() in the Activity):<

相关标签:
5条回答
  • 2020-12-13 02:04

    Use the Intent.hasExtra(String name) to check if an extra with name was passed in the intent.

    Example:

    Intent intent = getIntent();
    
    if (intent.hasExtra("bookUrl")) {
        bookUrl = b.getString("bookUrl");
    } else {
       // Do something else
    }
    

    Also, use Intent.getStringExtra(String name) directly on the intent to handle the NullPointerException if no extras were passed.

    0 讨论(0)
  • 2020-12-13 02:06
    if (this.getIntent().getExtras() != null && this.getIntent().getExtras().containsKey("yourKey")) {
       // intent is not null and your key is not null
    }
    
    0 讨论(0)
  • 2020-12-13 02:12

    I would use this solution in your case.

    String extraStr;
        try {
            extraStr = getIntent().getExtras().getString("extra");
        } catch (NullPointerException e ) {
            extraStr = "something_else";
        }
    
    0 讨论(0)
  • 2020-12-13 02:14

    Well, I had similiar problem. in my case the null point exception was happen when I checked if my bundle.getString() was equall to null.

    here is how IN MY CASE I solved it:

    Intent intent = getIntent();        
        if(intent.hasExtra("nomeUsuario")){
            bd = getIntent().getExtras();
            if(!bd.getString("nomeUsuario").equals(null)){
                nomeUsuario = bd.getString("nomeUsuario");
            }
        }
    
    0 讨论(0)
  • 2020-12-13 02:19

    I think you need to check when extras != null

    Bundle extras = getIntent().getExtras();
       if (extras != null) {
            String extraStr = extras.getString("extra");
        }else {
            extraStr = "extra not set";
        }
    
    0 讨论(0)
提交回复
热议问题