3

I need access a simple int variable which holds an editText element value. The value is stored as a public field on my Activity class. On my Service, I created an object from my activity class:

CheckActivity check = new CheckActivity();

and I am trying to access it by:

check.getFirstPosition();

but it returns zero. What should I do to pass the value from an Activity to a Service?

Kaan Demirel
  • 180
  • 1
  • 2
  • 16
  • 1
    https://www.youtube.com/watch?v=lnd0oPSzoJg that is a BIG question. A service can be bound or started, in the same process in which case you can simply use a public static variable on either side (service or activity) in a separate service you can use messengers or AIDL by the way activities are started as intents not CheckActivity check = new CheckActivity(); – Pomagranite May 02 '16 at 22:37
  • Making the variable static worked, thanks. – Kaan Demirel May 02 '16 at 22:48

3 Answers3

7

You need to use intent for passing data between different Android components be it Activity or Service.

Intent intent = new Intent(this, YourService.class);
intent.putExtra("your_key_here", <your_value_here>); 

And then start your service like this -

startService(intent);

Now you can use onBind() or onStartCommand() (depends on how you are using your service) to use the intent passed as an argument

String editTextValue = intent.getStringExtra("your_key_here");

You can use editTextValue anywhere you want now.

Shadab Ansari
  • 7,022
  • 2
  • 27
  • 45
  • You can get the Intent object through the Service's lifecycle methods, but unlike Activity, Service does not have a getIntent() method. – chRyNaN May 02 '16 at 23:09
6

You cannot create an object like that from your service. I think you are new to Java. When you do CheckActivity check = new CheckActivity() a new instance of your CheckActivity is created and no doubt it will return zero. Also you should never try creating objects of activities like this in android.

As far as your question is concerned you can pass your editText value to your service via a broadcast receiver.

Have a look at this.

Also if you have the editText value before creating the service you can simply pass it as intent extra , else you can use the broadcast approach.

In your service

broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equalsIgnoreCase("getting_data")) {
                    intent.getStringExtra("value")
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        // set the custom action
        intentFilter.addAction("getting_data"); //Action is just a string used to identify the receiver as there can be many in your app so it helps deciding which receiver should receive the intent. 
        // register the receiver
        registerReceiver(broadcastReceiver, intentFilter);

In your activity

Intent broadcast1 = new Intent("getting_data");
        broadcast.putExtra("value", editext.getText()+"");
        sendBroadcast(broadcast1);

Also declare your receiver in onCreate of activity and unregeister it in onDestroy

unregisterReceiver(broadcastReceiver);
Community
  • 1
  • 1
varunkr
  • 5,364
  • 11
  • 50
  • 99
  • Just curious, how can I use Broadcast Receiver on Service class to directly access editText value from some Activity class? – Kaan Demirel May 02 '16 at 22:52
  • Declare your broadcastReceiver inside your service as shown in the tutorial. Then from your activity pass an intent with action set to that of your broadcast receiver. In your service the intent will be received inside your receiver and you can extract the value from there. Its very basic stuff. Please upvote/ accept the answer if you find it useful. – varunkr May 02 '16 at 22:55
  • Thanks for the detailed explanation. Making my variable static worked for me but I really liked your approach. – Kaan Demirel May 02 '16 at 23:03
  • But how did you do that, by creating the activity object? Thnx for accepting btw !!! – varunkr May 02 '16 at 23:04
  • Just added 'static' to the variable on my Activity and I was able to access it on my Service by ActivityName.variableName – Kaan Demirel May 02 '16 at 23:05
  • @KaanDemirel BTW it's bad approach. – Shadab Ansari May 02 '16 at 23:16
  • @ShadabAnsari I also think that but there are answers on stackOverflow which say this shouldn't be a problem, strange, not sure whether one should use static variables like this in activities. Can you say why is it bad? I just know it is bad :D – varunkr May 02 '16 at 23:19
  • 1
    @varunkr The only reason for which I am reluctant to use static as much as possible is because those values persist and remain available throughout the app until the app is killed and that value sometimes may or may not be what you expect at later stage. – Shadab Ansari May 02 '16 at 23:28
  • Ok thnx, thats a valid reason !! – varunkr May 02 '16 at 23:29
0

CheckActivity check = new CheckActivity();

Never do this. Use Intent to create an activity instead.

What should I do to pass the value from an Activity to a Service?

You can pass it via Intent using context.startService() method. Or, you can bind to it and pass a value via reference.

You can also consider using a BroadcastReceiver or Handler.

Gennadii Saprykin
  • 4,505
  • 8
  • 31
  • 41