Grady-lad
Grady-lad

Reputation: 105

passing data with intents

Lately I have been playing around with intents and bundles. I thought I had them figured out, but I keep getting problems when passing data between intents I understand that you have to use bundles, but when I try implement a simple program to test this, I keep getting a null pointer exception. The program I made is just an activity which calls a service to create a string and then that activity should be able to get the string created by the service and toast it. Does anyone know what I am doing wrong here, cheers to anyone that can help. Here is the code below

Activity class

MyIntent = new Intent(this, GetLocation.class);
startService(MyIntent);

bundle = MyIntent.getExtras();  
test = bundle.getString("location");
Context context = getApplicationContext();
CharSequence text = test;
int duration = Toast.LENGTH_LONG;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

Service class

  Intent Int1 =new Intent(this,MapMock.class); 
   Bundle  b = new Bundle();
   String yeah = new String();
   yeah = "hello";
   b.putString("location", yeah);
   Int1.putExtras(b);

Upvotes: 0

Views: 229

Answers (2)

mcnicholls
mcnicholls

Reputation: 846

Services don't work this way.

The intent you send to the service via startService doesn't get updated and returned to the activity that starts it.

I think you need a bound service. Read here to find out more. This allows you to call functions and pass values back to the activity.

Upvotes: 2

jeet
jeet

Reputation: 29199

Looks like you are accessing intent date which you haven't put into intent,

like if you are starting activity from your service, and passing some data use:

Intent myIntent=getIntent();
bundle = MyIntent.getExtras();  
test = bundle.getString("location");
Context context = getApplicationContext();
CharSequence text = test;
int duration = Toast.LENGTH_LONG;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

Upvotes: 0

Related Questions