David Walton
David Walton

Reputation: 293

ClassCastException starting AsyncTask in service

I'm getting this error when starting a service that starts an AsyncTask - and yet I have another similar service and AsyncTask that work ok. Both services are declared in the manifest. If anyone can suggest what might be the problem I'd appreciate it. After lots of reading I've assumed it's something to do with the structure/parameters of the AsyncTask, so I've tried a few variations with no joy yet - but I'm not sure I'm going in the right direction. I'm not explicitly extending an application anywhere.

09-04 09:13:46.444: E/AndroidRuntime(1190): FATAL EXCEPTION: main
09-04 09:13:46.444: E/AndroidRuntime(1190): java.lang.RuntimeException: Unable to start service couk.jit.currencycheck1.ServiceClassXML@4602fc20 with Intent { flg=0x4 cmp=couk.jit.currencycheck1/.ServiceClassXML (has extras) }: java.lang.ClassCastException: android.app.Application
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3063)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.access$3600(ActivityThread.java:125)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2096)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.os.Looper.loop(Looper.java:123)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at java.lang.reflect.Method.invokeNative(Native Method)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at java.lang.reflect.Method.invoke(Method.java:521)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at dalvik.system.NativeStart.main(Native Method)
09-04 09:13:46.444: E/AndroidRuntime(1190): Caused by: java.lang.ClassCastException: android.app.Application
09-04 09:13:46.444: E/AndroidRuntime(1190):     at couk.jit.currencycheck1.GetXMLTask.<init>(GetXMLTask.java:52)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at couk.jit.currencycheck1.ServiceClassXML.onStartCommand(ServiceClassXML.java:24)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3053)
09-04 09:13:46.444: E/AndroidRuntime(1190):     ... 10 more

This service works running the AsyncTask below it.

public class ServiceClass extends Service {
SharedPreferences prefs = null;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplication().getApplicationContext());
    boolean run = prefs.getBoolean("running", false);
    if (!run)
        stopSelf();
    else {
        new AsyncNetworkConnection(this.getApplication().getApplicationContext(), true).execute("");
    }
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
}

AsyncTask that works.

public class AsyncNetworkConnection extends AsyncTask<String, String, String> {

public AsyncNetworkConnection(Context ct, boolean asService) {
...
}

@Override
protected void onPostExecute(String result) {
...
}

protected String doInBackground(String... arg0) {
String result = null;
...
results = fetchHTML(arg0[0]);
return results;
}

private String fetchHTML(String urlStr) throws URISyntaxException,
        ClientProtocolException, IOException, Exception {
String result = null;
...
return result;
}

}

This is the service giving the error. If I comment out the 'newGetXMLTask' line, I don't get the error. If I replace it with the other AsyncTask I don't get the error (but of course subsequent errors). The log message is shown in logcat.

public class ServiceClassXML extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("DBG", "ServiceClassXML started");
    prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplication().getApplicationContext());
    boolean run = prefs.getBoolean("running", false);
    if (!run)
        stopSelf();
    else {
        new GetXMLTask(this.getApplication().getApplicationContext(), true).execute("abc");
//          new AsyncNetworkConnection(this.getApplication().getApplicationContext(), true).execute("");
    }
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
}

The basics of the AsyncTask that gives the error.

public class GetXMLTask extends AsyncTask<String, Void, List<RateData>> {

public GetXMLTask(Context ct, boolean asService) {
    this.context = (Activity) ct;   //as context can be cast to activity
    prefs = PreferenceManager.getDefaultSharedPreferences(context);
    dataSource = prefs.getInt("srcs", 0);
    runAsService = asService;
    restoredTextFrom = prefs.getString("fromCurr", null);
    restoredTextTo = prefs.getString("toCurr", null);
}

@Override
protected void onPostExecute(List<RateData> rates) {
...
}

@Override
protected List<RateData> doInBackground(String... urls) {
xml = getXmlFromUrl(url);
...
}

private String getXmlFromUrl(String urlString) {
...
return output.toString();
}
}

Manifest includes:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="couk.jit.currencycheck1.MainMenu"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:name="couk.jit.currencycheck1.ServiceClass"
        android:enabled="true" />
    <service
        android:name="couk.jit.currencycheck1.ServiceClassXML"
        android:enabled="true" />
...
</application>

Upvotes: 0

Views: 419

Answers (2)

Piyush
Piyush

Reputation: 18933

you should make varible for Context.

 Context ctx = getApplicationContext();

And use this ctx to in

 new GetXMLTask(ctx, true).execute("abc");

Upvotes: 0

Ritesh Gune
Ritesh Gune

Reputation: 16729

You are passing application context in

new GetXMLTask(this.getApplication().getApplicationContext(), true).execute("abc");

and you are casting it to Activity context like this.context = (Activity) ct;

This is giving you the exception

Caused by: java.lang.ClassCastException: android.app.Application

Upvotes: 3

Related Questions