Chapter 8 ClassCastException

Forums » Android - Learning Android book > Chapter 8 ClassCastException
February 18, 2012 1:42:35 PM PST (one year ago). Seen 590 times. One reply.
Photo Paul Mcilwaine
Digital Stampede
Member since Feb 18, 2012
Forum Posts: 1
In the UpdaterService class onCreate method the books gets us to link back to the YambaApplication class which we cast from Application to YambaApplication, however in the onCreate method when running a ClassCastException is thrown.

my onCreate method

Code:
@Override
public void onCreate()
{
super.onCreate();

this.yamba = (YambaApplication) this.getApplication();
this.updater = new Updater();

Log.d(TAG, "onCreated");
}


However doing a similar thing in the StatusActivity class is fine, what have I missed that would cause it to fail during the creation of the thread ?

If I don't cast it I can pull the Application class in so something is wrong with the YambaApplication class as far as I can tell.

YambaApplication class
Code:
package com.marakana.yamba;

import winterwell.jtwitter.Twitter;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

public class YambaApplication extends Application implements
OnSharedPreferenceChangeListener
{

private static final String TAG = YambaApplication.class.getSimpleName();
private SharedPreferences prefs;
private boolean serviceRunning;

public Twitter twitter;

public boolean isServiceRunning()
{
return serviceRunning;
}

public void setServiceRunning(boolean serviceRunning)
{
this.serviceRunning = serviceRunning;
}

@Override
public void onCreate()
{
super.onCreate();
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
this.prefs.registerOnSharedPreferenceChangeListener(this);
Log.i(TAG, "onCreated");
}

@Override
public void onTerminate()
{
super.onTerminate();
Log.i(TAG, "onTerminated");
}

public synchronized Twitter getTwitter()
{
if ( this.twitter == null )
{
String username = this.prefs.getString("username","");
String password = this.prefs.getString("password", "");
String apiRoot = this.prefs.getString("apiRoot","http://yambda.marakana.com/api");

if ( !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password) &&
!TextUtils.isEmpty(apiRoot) )
{
this.twitter = new Twitter(username,password);
this.twitter.setAPIRootUrl(apiRoot);
}
}

return this.twitter;
}

public synchronized void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
this.twitter = null;
}

}
March 4, 2012 10:17:49 PM PST (one year ago)
Photo Marko Gargenta
@MarkoGargenta
Marakana, Inc.
Member since Jan 19, 2007
Location: San Francisco
Forum Posts: 227
You need to remember to add android:name=".YambaApplication" to your <application ...> tag in AndroidManifest.xml. That should get rid of the ClassCastException.

Marko