11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

クラス間での値の受け渡し時に気をつけることgetExtra(), putExtra()

Posted at

他クラスに値を渡すときはputExtra()やgetIntent().getExtra()を使いますが、putされていない状態でgetした場合はgetExtra()の中身はnullになります。

ネット上で調べていると

if(getIntent().getStringExtra(“example").isEmpty()){
ーーーーーー
}else{  
ーーーーーー
}

と書かれたコードを何個か見かけましたが、このコードが出てくる以前にputExtra(“example”)が呼ばれてない時の値は0ではなくnullになるはずですのでこれだとクラッシュします。

よって


String home = getIntent().getStringExtra("home");
if (home != null) {// 定義されている
		ーーーーー
		} else {//まだ定義されていない
		ーーーーー
		}

とすれば定義されていないStringをif内で扱う時もクラッシュしません。

11
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?