Sujit Maiti
Sujit Maiti

Reputation: 27

Getting null value for Intent.getstringExtra()

I can't figure out why the app crashes on the device with following error:

msg: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference

On Android Studio, there's no error show, builds successfully. I pass the url to launch WebActivity in the following manner, where I even check if the string is null

MainActivity.java

if (getIntent().getExtras() != null) {
   if (getIntent().getStringExtra("LINK") != null) {
       Intent web = new Intent(this, WebActivity.class);
       web.putExtra("link", getIntent().getStringExtra("LINK"));
       MainActivity.this.startActivity(web);
       finish();
    }
}

WebActivity.java

Intent wb = getIntent();
final String url = wb.getStringExtra("link");
\\onCreate() method
if (savedInstanceState == null) {
    webView.post(() -> webView.loadUrl(url));
}

Is it because the getIntent() in WebActivity is outside the onCreate() method

Upvotes: 0

Views: 535

Answers (1)

user12517395
user12517395

Reputation:

Move this code inside onCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    Intent wb = getIntent();
    final String url = wb.getStringExtra("link");

    if (savedInstanceState == null) {
        webView.post(() -> webView.loadUrl(url));
    }
}

Upvotes: 1

Related Questions