2013-02-21 8 views
6

Ich frage mich, ob es möglich ist, Daten von z.B. Aktivität 2 und Aktivität 3 in Aktivität 1, die eine onActivityResult() haben, oder brauche ich für jede Aktivität eine Methode, die Daten zurückgibt?Handle Daten von mehreren Aktivitäten in einem onActivityResult()?

Aktivität 1 ist die Hauptaktivität für die Anwendung.

Aktivität 1:

// Handle return value from activity 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == Activity.RESULT_OK) { 
     String imageId = data.getExtras().getString("imageId"); 

     // Do something if data return from activity 2 ?? 

     // Do something if data return from activity 3 ?? 
    } 
} 

Activity 2

Intent intent = new Intent(); 
intent.putExtra("imageId", imagePath); 
setResult(RESULT_OK, intent); 
finish(); 

Aktivität 3

Intent intent = new Intent(); 
intent.putExtra("contactId", data); 
setResult(RESULT_OK, intent); 
finish(); 
+1

das ist, was requestCode für ist. – njzk2

Antwort

7

Satz requestCode in Ihrem startActivityForResult für Aktivität 1:

Aufruf Aktivität 2

Intent intent = new Intent(this, Activity2.class); 
startActivityForResult(intent,10); 

Aufruf Aktivität 3

Intent intent = new Intent(this, Activity3.class); 
startActivityForResult(intent,11); 

Nun, wenn Sie kommen, um onActivityResult prüfen, ob requestCode

wie:

public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 

     super.onActivityResult(requestCode, resultCode, data); 

     switch (requestCode) { 

      case (10): 
      { 
      // do this if request code is 10. 
      } 
      break; 

      case (11): 
      { 
      // do this if request code is 11. 
      } 
      break; 
    } 
+0

Ist super.onActivityResult (requestCode, resultCode, data); notwendig? –

+0

Abgeleitete Klassen müssen die Implementierung dieser Methode durch die Superklasse aufrufen. Wenn dies nicht der Fall ist, wird eine Ausnahme ausgelöst. – KDeogharkar

+0

Im Allgemeinen (nicht speziell in Android Sachen), wenn Sie ableiten, sollten Sie zu den Methoden der Superklasse aufrufen, wenn Sie nicht wissen, dass Sie nicht sollten. Es ist eine Entscheidung, die von Fall zu Fall getroffen werden muss, aber der Standard (würde ich sagen) wäre, dass Sie es tun. – KDeogharkar

6

No confusion check result code and request code ..

Beispiel:

0.123.
private static final int TWO = 2; 
private static final int THREE = 3; 

startActivityForResult(new Intent(this,Activity2.class),TWO); // one for Activity 2 
startActivityForResult(new Intent(this,Activity3.class),THREE); 

und

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == Activity.RESULT_OK) { 
     if(requestCode == TWO) { 
      // Activity two stuff 
     } else if(requestCode == THREE) { 
      // Activity three stuff 
     } 
    } 
}