PDA

View Full Version : This is the class cast exception



jamesfunny
03-10-2011, 12:53 AM
This is the exception I am getting while running my GPSsens application. Can any one please tell me what is the reason for this error


http://comp.uark.edu/~smandava/exception.jpg

alostpacket
03-10-2011, 02:08 AM
What kind of class is GPSsens?

It's hard to tell from that error, but did you extend Activity in the class?

jamesfunny
03-10-2011, 09:16 AM
It is a Service class not Activity

alostpacket
03-10-2011, 11:48 AM
Did you define it as a Service in your manifest? You really need to provide some more info/code otherwise I can only guess as to why :(

jamesfunny
03-10-2011, 02:40 PM
Hey I didn't define it in my manifest, but it extends Service class as shown in the code below.Do I need to define it as a Service in my manifest too? Please help me. This is my Thesis project . I need to submit this by this month end. My manifest file is in my next comment

public class GPSsens extends Service
{

/** Name of the service used for logging */
private static final String TAG = "SystemSensService";

/** Version of the JSON records */
private static final String VER = "1.4";


/** Types of messages used by this service */
private static final int USAGESTAT_MSG = 1;
private static final int UPLOAD_START_MSG = 2;
private static final int UPLOAD_END_MSG = 3;
private static final int BATHIST_MSG = 4;
private static final int PROC_MSG = 5;

/** String names of JSON records */
private static final String USAGESTAT_TYPE = "usage";
private static final String NETTRANS_TYPE = "transmission";
private static final String NETRECV_TYPE = "receive";
private static final String CPUSTAT_TYPE = "cpu";
private static final String GPSSTAT_TYPE = "gps";
private static final String SENSORSTAT_TYPE = "sensor";
private static final String BATTERY_TYPE = "battery";
private static final String SCREEN_TYPE = "screen";
private static final String NET_TYPE = "network";
private static final String CALL_TYPE = "call";
private static final String SYSTEMSENS_TYPE = "systemsens";
private static final String NETDEV_TYPE = "netdev";

/** Intervals used for timers in seconds */
private long USAGESTAT_INTERVAL;
private long BATHIST_INTERVAL;
private long PROC_INTERVAL;

/** Default values for timers in seconds */
private static final long DEFAULT_USAGESTAT_INTERVAL = 120000;
private static final long DEFAULT_BATHIST_INTERVAL = 120000;
private static final long DEFAULT_PROC_INTERVAL = 120000;

/** Power manager object used to acquire a partial wakeLock */
private PowerManager m_PM;

/** WakeLock object */
private PowerManager.WakeLock m_WL;


/** State variable set when a worker thread starts uploading */
private boolean mIsUploading;

/** Usage statistics object */
private Usage mUsageStat;

/** Battery History object */
private History mHistoryStat;

/** Proc object */
private Proc mProc;

/** Uploader Object */
//private SystemSensUploader mUploader;

/** Dumper Object -- used for debugging */
private SystemSensDumper mDumper;


/** Database adaptor object */
private SystemSensDbAdaptor mDbAdaptor;

/** Holds the IMEI of the device */
private String IMEI;


/** telephonyManager object */
private TelephonyManager telManager;

//private SystemSensLogger logger;

/** Battery information record for reporting to the activity */
private JSONObject batteryJson;

/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class LocalBinder extends Binder {
GPSsens getService() {
return GPSsens.this;
}
}

@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Log.i(TAG, "onStart");
}

@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");


// Set the default intervals for USAGE and BATHIST counters
USAGESTAT_INTERVAL = DEFAULT_USAGESTAT_INTERVAL;
BATHIST_INTERVAL = DEFAULT_BATHIST_INTERVAL;
PROC_INTERVAL = DEFAULT_PROC_INTERVAL;

mIsUploading = false;

mDbAdaptor = new SystemSensDbAdaptor(this);

mDumper = new SystemSensDumper(mDbAdaptor, this);

mUsageStat = new Usage();
mHistoryStat = new History(this);
mProc = new Proc();


try
{
mDbAdaptor.open();
}
catch (SQLException e)
{
Log.e(TAG, "Exception", e);
}

// Start getting process information
Message msg2 = mHandler.obtainMessage(BATHIST_MSG);
long nextTime = SystemClock.uptimeMillis()
+ BATHIST_INTERVAL;
mHandler.sendMessageAtTime(msg2, nextTime);

// Log a message indicating starting SystemSens
JSONObject sysJson = new JSONObject();
try
{
sysJson.put("state", "started");
}
catch (JSONException e)
{
Log.e(TAG, "Exception", e);
}


// Acquire a partial wake lock
m_PM = (PowerManager) getSystemService(Context.POWER_SERVICE);
m_WL = m_PM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"SystemSense");

m_WL.acquire();

mDbAdaptor.createEntry( constructDataRecord(
sysJson, SYSTEMSENS_TYPE));

}

@Override
public void onDestroy() {

// Clear the message handler's pending messages
// mHandler.removeMessages(USAGESTAT_MSG);
mHandler.removeMessages(BATHIST_MSG);

// unregisterReceiver(mBatteryInfoReceiver);

mDbAdaptor.close();

// Log a message indicating killing SystemSens
JSONObject sysJson = new JSONObject();
try
{
sysJson.put("state", "killed");
}
catch (JSONException e)
{
Log.e(TAG, "Exception", e);
}

mDbAdaptor.createEntry( constructDataRecord(
sysJson, SYSTEMSENS_TYPE));

m_WL.release();
Log.i(TAG, "Killed");

}

private String constructDataRecord(JSONObject data, String type) {
// TODO Auto-generated method stub
JSONObject dataRecord = new JSONObject();

// First thing, get the current time
final Calendar c = Calendar.getInstance();
String timeStr = "" +
c.get(Calendar.YEAR) + "-" +
c.get(Calendar.MONTH) + "-" +
c.get(Calendar.DAY_OF_MONTH) + " " +
c.get(Calendar.HOUR_OF_DAY) + ":" +
c.get(Calendar.MINUTE) + ":" +
c.get(Calendar.SECOND);

try
{
dataRecord.put("date", timeStr);
dataRecord.put("time_stamp", c.getTimeInMillis());
dataRecord.put("user", IMEI);
dataRecord.put("type", type);
dataRecord.put("ver", VER);
dataRecord.put("data", data);
}
catch (JSONException e)
{
Log.e(TAG, "Exception", e);
}

return dataRecord.toString();

}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

/** This is the object that receives interactions from clients. */
private final IBinder mBinder = new LocalBinder();


/**
* Broadcast receiver for Battery information updates.
* An object of this class has been passed to the system through
* registerReceiver.
*
*/

private final Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
/* Get usage stat */
if (msg.what == USAGESTAT_MSG)
{

// DEBUG
//Log.i(TAG, "Received MSG" + msg.toString());

// Get system information here and insert to database
HashMap<String, Long> usageMap = mUsageStat.getStat();
mDbAdaptor.createEntry( constructDataRecord(
new JSONObject(usageMap),
USAGESTAT_TYPE));

// Schedule a new timer
msg = obtainMessage(USAGESTAT_MSG);
long nextTime = SystemClock.uptimeMillis()
+ USAGESTAT_INTERVAL;
sendMessageAtTime(msg, nextTime);
}
if (msg.what == BATHIST_MSG)
{
// Get send and receive information and insert to database
mHistoryStat.update();
JSONObject gpsMap = mHistoryStat.getGpsInfo();
// JSONObject sensorMap = mHistoryStat.getSensorInfo();

mDbAdaptor.createEntry( constructDataRecord(
gpsMap,
GPSSTAT_TYPE));

// Schedule a new timer
msg = obtainMessage(BATHIST_MSG);
long nextTime = SystemClock.uptimeMillis()
+ BATHIST_INTERVAL;
sendMessageAtTime(msg, nextTime);

}

}
};



/** Format a number of tenths-units as a decimal string without using a
* conversion to float. E.g. 347 -> "34.7"
*
* @param intVal
* @return String representing the decimal
*/
private final String tenthsToFixedString(int intVal) {
int tens = intVal / 10;
return new String("" + tens + "." + (intVal - 10*tens));
}

public JSONObject getBatteryInfo()
{
return batteryJson;
}


public String getHistInfo()
{
mHistoryStat.update();
/*
String result = "CPU: " + mHistoryStat.getCpuInfo().toString();

result += "\nRecv: " + mHistoryStat.getRecvInfo().toString()
+ "\nSent: " + mHistoryStat.getSentInfo().toString();
*/

mHistoryStat.update();
String result = "GPS: " + mHistoryStat.getGpsInfo().toString();

return result;
}




/**
* Spawns a worker thread to "try" to write the contents of the
* database in a flat file.
* Before starting the thread, checks if a worker thread is
* already trying to dump. If so, returns. Otherwise a new
* thread is spawned and tasked with the dump job.
*
* This should only be used for debugging. It should NOT be used
* along with the upload method. Either dump() or upload() should
* be called.
*
*/
private void dump()
{
if (!mIsUploading)
{
Thread uploaderThread = new Thread()
{
public void run()
{
// Send an immediate message to the main thread
// to inform that a worker thread is running.
mHandler.sendMessageAtTime( mHandler.obtainMessage(
UPLOAD_START_MSG),
SystemClock.uptimeMillis());


Log.i(TAG, "Worker thread started dump task");
mDumper.tryDump();

// Send an immediate message to the main thread to
// inform that the worker thread is finished.
mHandler.sendMessageAtTime( mHandler.obtainMessage(
UPLOAD_END_MSG),
SystemClock.uptimeMillis());
}
};

uploaderThread.start();

}
else
{
Log.i(TAG, "Dump in progress ...");
}
}


}

jamesfunny
03-10-2011, 02:41 PM
This is my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.gps"
android:versionCode="1"
android:versionName="1.0">

<uses-permission
android:name="android.permission.VIBRATE" />
<uses-permission
android:name="android.permission.BLUETOOTH" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission
android:name="android.permission.HARDWARE_TEST" />
<uses-permission
android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.CLEAR_APP_USER_DATA" />
<uses-permission
android:name="android.permission.READ_PHONE_STATE" />
<uses-permission
android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission
android:name="android.permission.ACCESS_CHECKIN_PROPERTIES"/>
<uses-permission
android:name="android.permission.RESTART_PACKAGES"/>
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"/>
<uses-permission
android:name="android.permission.BATTERY_STATS"/>
<uses-permission
android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission
android:name="android.permission.WAKE_LOCK"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".GPSsens"
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:label="SystemSensService"
android:name="SystemSensService">
</service>

</application>


</manifest>

alostpacket
03-10-2011, 07:12 PM
You're trying to launch a service as an Activity... The ClassCastException happens because the OS is trying to run the GPSsens as a subclass of Activity, while it's a subclass of Service.

you have:
<activity android:name=".GPSsens" ....

but

GPSsens extends Service

You dont have an activity for your app? Usually a service is a background task you're trying to perform for some UI.


Anyways your service tag should be like this:


<service
android:name=".GPSsens"
android:enabled="true"
android:exported="false"
/>


And you should have a separate class for the activity (the UI)


<activity android:name=".MyActivity" android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>




Then you typically start the service FROM the activity...

Though, I guess if you only want the service you can start from a broadcast receiver. Check out Activating Components and Broadcast Receivers.

http://developer.android.com/guide/topics/fundamentals.html#ActivatingComponents


By the way.... what the heck does this app do? You have all sorts of crazy permissions in there :)

jamesfunny
03-12-2011, 01:03 PM
Hey I did that and also made some changes. I don't get classcast exception now but I am getting security exception although I have declred all the required permissions. Here is the post of that problem http://androidcommunity.com/forums/f8/security-exception-50682/