Passing Values Between Activities

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Passing Values Between Activities

Postby waynesilver » Sat Feb 20, 2010 1:42 am

I am still having problems passing values between activities. I can pass values into a called activity, and use them in that called activity. When I want to pass values back from the called activity, when it is done, I can't access them.

I wrote a code example where class Foo calls an activity Bar and passes it a "blank" city. I want Bar to pass back the city name of Foo Bar when the user exits. This is so the calling program can use the new value, but when I try to use it, it is "blank".

Again, how do I pass a value back from the called program? What change(s) needs to be made to my code to get the new value back from the called program Bar?

I have studied the Notebook example and I don't think it applies.


Implementation of Foo, the calling program:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package android.test.Foo;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6.  
  7. public class Foo extends Activity {
  8.         public static boolean DEBUGING=true;
  9.         public String city="blank";
  10.         Intent i=null;
  11.        
  12.     /** Called when the activity is first created. */
  13.     @Override
  14.     public void onCreate(Bundle savedInstanceState) {
  15.         super.onCreate(savedInstanceState);
  16.         setContentView(R.layout.main);
  17.        
  18.         if (DEBUGING){android.util.Log.v("MAINCREATE", "City = " + city);};
  19.                 i=new Intent(Foo.this, Bar.class);
  20.                 i.putExtra("CITY", city);
  21.  
  22.                 startActivity(i);
  23.     }
  24.  
  25.          @Override
  26.          public void onResume() {
  27.                  super.onResume();
  28.                         city=i.getStringExtra("CITY");
  29.                 if (DEBUGING){android.util.Log.v("MAINRES", "City = " + city);};
  30.                
  31.          }
  32.  
  33. }
  34.  
  35.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


Implementation of Bar:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package android.test.Foo;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6.  
  7. public class Bar extends Activity {
  8.         static boolean DEBUGING=true;
  9.         Bundle b=null;
  10.         String city=null;
  11.        
  12.  
  13.     /** Called when the activity is first created. */
  14.     @Override
  15.     public void onCreate(Bundle savedInstanceState) {
  16.         super.onCreate(savedInstanceState);
  17.                 b=this.getIntent().getExtras();
  18.                 city=b.getString("CITY");
  19.         if (DEBUGING){android.util.Log.v("SUBCREATE", "City = " + city);};
  20.  
  21.         setContentView(R.layout.bar);
  22.        
  23.    }
  24.          @Override
  25.          public void onResume() {
  26.                  super.onResume();
  27.                  city="Foo Bar";
  28.                  b.putString("CITY", city);
  29.                 if (DEBUGING){android.util.Log.v("SUBRES", "City = " + city);};
  30.                  
  31.          }
  32.  
  33. }
  34.  
  35.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


The LOG looks like:
02-20 00:21:24.420: VERBOSE/MAINRES(265): City = blank
02-20 00:21:24.680: VERBOSE/SUBCREATE(265): City = blank
02-20 00:21:24.740: VERBOSE/SUBRES(265): City = Foo Bar
.
.
.
02-20 00:21:46.861: VERBOSE/MAINRES(265): City = blank
waynesilver
Developer
Developer
 
Posts: 28
Joined: Mon Jan 04, 2010 9:01 pm
Location: Seattle

Top

Postby mitutitu » Sat Feb 20, 2010 1:58 pm

Hi waynesilver,

If you want to get back value to calling activity from called activity you need to use startActivityForResult() instead of startActivity() and in the calling program you should implement the method onActivityResult() to catch the values returned from called activity.

Thanks,
mitu
Android is awesome!
User avatar
mitutitu
Senior Developer
Senior Developer
 
Posts: 113
Joined: Tue Jun 09, 2009 7:40 am
Location: St. John's, NL, Canada

Postby waynesilver » Sat Feb 20, 2010 4:08 pm

OK I put in the startActivityForResult and added an onActivityResult listener to receive the information. But the whole thing crashes on the return. It never makes it back to the calling program, where I am trying to pull out the values. I thought I would add a setResult in the called program, but that didn't change anything. I thought with all the nulls the log was reporting, I could clear it up by using setResult (int code, String data, Bundle extras), but I kept getting compile errors because that is not a method of activity.

I know this stuff is really simple, and you all have better things to do than debug my code, but I'd like to ask for a little more of your time. What did I miss this time? and how do I get this data back to the calling program?

Here is the new calling activity Foo:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package android.test.Foo;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6.  
  7. public class Foo extends Activity {
  8.         public static boolean DEBUGING=true;
  9.         public static int CITY=1;
  10.         public String city="blank";
  11.         Intent i=null;
  12.        
  13.     /** Called when the activity is first created. */
  14.     @Override
  15.     public void onCreate(Bundle savedInstanceState) {
  16.         super.onCreate(savedInstanceState);
  17.         setContentView(R.layout.main);
  18.        
  19.         if (DEBUGING){android.util.Log.v("MAINCREATE", "City = " + city);};
  20.                 i=new Intent(Foo.this, Dialogs.class);
  21.                 i.putExtra("CITY", city);
  22.  
  23.                 startActivityForResult(i,CITY);
  24.     }
  25.  
  26.          @Override
  27.          public void onResume() {
  28.                  super.onResume();
  29.                         city=i.getStringExtra("CITY");
  30.                 if (DEBUGING){android.util.Log.v("MAINRES", "city = " + city);};
  31.                
  32.          }
  33.        
  34.      protected void onActivityResult(int requestCode, int resultCode,
  35.              Intent data) {
  36.                         city=data.getStringExtra("CITY");
  37.                 if (DEBUGING){android.util.Log.v("ACTRESULT", "City = " + city);};
  38.          
  39.          }
  40. }
Parsed in 0.040 seconds, using GeSHi 1.0.8.4



Here is the called activity Bar:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package android.test.Foo;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8.  
  9. public class Bar extends Activity {
  10.      static boolean DEBUGING=true;
  11.      Bundle b=null;
  12.      String city=null;
  13.      Button ack=null;
  14.      
  15.      
  16.  
  17.     /** Called when the activity is first created. */
  18.     @Override
  19.     public void onCreate(Bundle savedInstanceState) {
  20.         super.onCreate(savedInstanceState);
  21.           b=this.getIntent().getExtras();
  22.           city=b.getString("CITY");
  23.         if (DEBUGING){android.util.Log.v("SUBCREATE", "City = " + city);};
  24.  
  25.         setContentView(R.layout.regions);
  26.         ack=(Button)findViewById(R.id.ackbutton);
  27.         ack.setOnClickListener(onAck);
  28.        
  29.    }
  30.       @Override
  31.       public void onResume() {
  32.            super.onResume();
  33.          
  34.       }
  35.  
  36.  
  37.          private View.OnClickListener onAck=new View.OnClickListener() {
  38.                  public void onClick(View v) {
  39.                    city="Foo Bar";
  40.                    b.putString("CITY", city);
  41.                      if (DEBUGING){android.util.Log.v("SUBONCLICK", "City = " + city);};
  42.                    setResult(RESULT_OK);
  43.                    finish();
  44.                  }
  45.          };
  46. }
Parsed in 0.041 seconds, using GeSHi 1.0.8.4


Here is the log:
02-20 06:34:32.235: VERBOSE/MAINCREATE(320): City = blank
02-20 06:34:32.295: VERBOSE/MAINRES(320): city = blank
02-20 06:34:32.385: VERBOSE/SUBCREATE(320): City = blank
02-20 06:34:45.056: VERBOSE/SUBONCLICK(320): City = Foo Bar

After I hit ack button to shut down Bar:


02-20 06:34:53.425: ERROR/AndroidRuntime(320): Uncaught handler: thread main exiting due to uncaught exception
02-20 06:34:53.455: ERROR/AndroidRuntime(320): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {android.test.Foo/android.test.Foo.Foo: java.lang.NullPointerException
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.app.ActivityThread.deliverResults(ActivityThread.java:3329)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3371)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.app.ActivityThread.access$2700(ActivityThread.java:119)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1893)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.os.Handler.dispatchMessage(Handler.java:99)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.os.Looper.loop(Looper.java:123)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.app.ActivityThread.main(ActivityThread.java:4363)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at java.lang.reflect.Method.invokeNative(Native Method)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at java.lang.reflect.Method.invoke(Method.java:521)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at dalvik.system.NativeStart.main(Native Method)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): Caused by: java.lang.NullPointerException
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.test.Foo.Foo.onActivityResult(Foo.java:36)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.app.Activity.dispatchActivityResult(Activity.java:3828)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): at android.app.ActivityThread.deliverResults(ActivityThread.java:3325)
02-20 06:34:53.455: ERROR/AndroidRuntime(320): ... 11 more
waynesilver
Developer
Developer
 
Posts: 28
Joined: Mon Jan 04, 2010 9:01 pm
Location: Seattle

Postby mitutitu » Mon Feb 22, 2010 6:02 am

Hi waynesilver,

I think something is wrong in your code. From your Foo Activity the intent is not correct :

Code: Select all
i=new Intent(Foo.this, Dialogs.class);


Here you targeting the wrong activity I guess. You should use
Code: Select all
Bar.class
instead of
Code: Select all
Dialogs.class
.

I hope your prob will be solved :)

Thanks,
mitu
Android is awesome!
User avatar
mitutitu
Senior Developer
Senior Developer
 
Posts: 113
Joined: Tue Jun 09, 2009 7:40 am
Location: St. John's, NL, Canada

Re: Passing Values Between Activities

Postby Marchu » Fri Apr 15, 2011 2:30 am

Yep.. i know this post is somewhat old, but i was stumblin upon it on my search for a solution.

I needed a light and easy way to have a return value from a Listactivity click, but ended up after 8 hours of experimenting with broadcast receivers with lots of complex code for 1 click...

I had totaly overlook the startActivityForResult method, what i can use for this, and thanks to this post i have my click value returned tot the calling activity, with just a few lines of code.

To put in my 2 cents, i have a little addition to the last comment, because i think (even this post is old), a post can better end with some right piece of code.. (maybe it save a new androidy some time :-))

For method setResult(RESULT_OK) you can better use setResult(RESULT_OK, returnIntent).
If you don't put the return intent in the setResult method, the returned intent will be null inside the onActivityResult receiver.

To make it perfect you can also make a switch..case block, that depends on the request code , so you can get return values for different actions inside the called activity or for different activities.

How i would do this with the above code.. (only changed code)

Calling activity
Code: Select all
i=new Intent(Foo.this, Bar.class);
startActivityForResult(i, MY_REQUEST);

First you don't need to put the extra value allready, if the called activity doesn't do anything with it.
Second the request code is a unique int, for the result value. You can use this inside a switch when returned.


Inside the called (List)Activity, you return the clicked value.
Code: Select all
city="Foo Bar";

Intent returnIntent = getIntent();
returnIntent.putExtra("CITY", city);
this.setResult(RESULT_OK, returnIntent);
    
finish();

Here a new intent is made, that is the intent from the called activity, with a extra value included.
The result will be the result code (RESULT_OK), with this intent.


Last (but not least..), we will catch the returnIntent inside the Calling activity.
Code: Select all
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
  switch (requestCode) {
      case 1: // from the same calling request
            Bundle res = data.getExtras();
            city = res.getString("CITY");
            if (DEBUGING){android.util.Log.v("ACTRESULT", "City = " + city);};

      default:
             // do nothing
      }
}

You need to get the extra value from a Bundle inside the intent.
Then you can get the value from the bundle. (not directly from the intent)

I know this post was old, and Android have changed lot of things, but this worked for me.

Cheers..
Marchu
Junior Developer
Junior Developer
 
Posts: 22
Joined: Sat Sep 27, 2008 4:11 pm
Location: Netherlands

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests