2012-01-11 4 views
2

これが私の最初の活動で私のコードです:第一、第二、私は渡すことにしたい値ですnull値は、()

Intent i = new Intent(this, OtherScreen.class); 
    i.putExtra("id1", "first"); 
    i.putExtra("id2", "second"); 
    startActivity(i); 

。 と私はこれを持って私の他のクラスで:

Intent i = getIntent(); 
     Bundle extras = i.getExtras(); 
     String result = extras.getString("id1"); 
     System.out.println("yeah"+result); 

が、私はそれを実行した後、私の結果は、あなたが私を助けnull.Canのですか? このようにgetStringを記述すると、構文エラーが発生します。

String result = extras.getString(id1); //id1 cannot be resolved to a variable 
String result = extras.getString("id1","default value"); // remove argument 

答えて

6
Intent i = new Intent(yourcurrentactivity.this, OtherScreen.class); 

i.putExtra("id1", "first"); 
i.putExtra("id2", "second"); 
startActivity(i); 

Bundle extras = getIntent().getExtras(); 
if (extras != null) { 
    String result = extras.getString("id1");     
    System.out.println("yeah"+result); 
} 
+0

int型ではなく通過したとして動作しません)(extras.getString – Prasad

+1

@Prasad何ですか?私は別の値がnullである可能性を推測します。1)キー名が不一致です。2)i.putExtra経由で送信される前にヌルです。i.putExtraを実行する前に、値がnullでないことを確認してデバッグする必要があります。 –

+1

@smith私は2番目に1つの問題を持っていました。あなたは渡す前にnullについて語った – Prasad

0

あなたが試すことがあります。String result = extras.get("id1");

3

また、より精度のために、あなたは if(getIntent.hasExtras("id11")' before actually getting extras from the bundle and do some action if its null

0

を使用することができます私はまた、null値とのトラブルを抱えていました。 @ YuDroidの提案if (getIntent.hasExtras("id11")を使用することをお勧めします。 Bundle documentationを読んだとき、私が見つけたもう一つの安全点検は、しかし、文字列が存在しない場合は、それはnullを返されるのではなく、デフォルト値でそれを提供することができますその方法

getString(String key, String defaultValue) 

です。

@ AprilSmithの答えは、デフォルトの文字列値で変更されています。

Intent i = new Intent(yourcurrentactivity.this, OtherScreen.class); 

i.putExtra("id1", "first"); 
i.putExtra("id2", "second"); 
startActivity(i); 

Bundle extras = getIntent().getExtras(); 
if (extras != null) { 
    String result = extras.getString("id1", "myDefaultString"); // This line modified 
    System.out.println("yeah"+result); 
} 
0

誰もが、まだこのissue..hereを持っている場合は、あなたが最初のアクティビティに渡しているデータ型は、受信側で同じでなければなりませんソリューション

です。

D2Activity

'Intent myIntent = new Intent(D1Activity.this, D2Activity.class);' 
     'myIntent.putExtra("dval", dval);' 
     ' D1Activity.this.startActivity(myIntent);' 

Bundle extras = getIntent().getExtras(); 
    if (extras != null) {; 
     edval = extras.getInt ("dval"); 
    } 

ここでは、私は二つの値に1を取得しているしていると、他の1がNULLの文字列