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?
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 yourCheckActivity
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
In your activity
Also declare your receiver in onCreate of activity and unregeister it in onDestroy
Never do this. Use
Intent
to create an activity instead.You can pass it via
Intent
usingcontext.startService()
method. Or, you can bind to it and pass a value via reference.You can also consider using a
BroadcastReceiver
orHandler
.You need to use intent for passing data between different Android components be it
Activity
orService
.And then start your service like this -
Now you can use
onBind()
oronStartCommand()
(depends on how you are using your service) to use theintent
passed as an argumentYou can use
editTextValue
anywhere you want now.