Android: FutureTask cannot be cast to MyClass - android

Situation : A function calls a thread to send data to the server. This thread in turn spawns yet another thread, to obtain results from the server using ObjectInputStream().
Finally, this object is returned to the calling function by the spawned thread.
Note: The threads are Callable and are synchronized.
Problem : I get an exception, "FutureTask cannot be cast to MyClassName".
I didn't find a solution to this on the web. Any suggestions ?
Client Code:
public synchronized Object invoke(Object proxy, Method m, Object[] args) throws Throwable
{
try {
// Lots of if-else statements
//.........
else if (m.toString().contains("getPosition"))
{
if (!offload){
Log.d("DProxy","Sprite Redirection takes place here 6 "+m.invoke(v, args).toString());
//System.out.println("PROXY Tick Argument is ");
return m.invoke(v, args);
}
else
{
//Code to create THREAD on the Endpoint
if (endpoint !=null)
{
if (!serialized)
{
System.out.println("serializing via proxy itself 11");
this.endpoint.serialize(obj);
serialized = true;
}
Object[] args1 = new Object[args.length+1];
for (i=0;i<args.length;i++)
args1[i]=args[i];
args1[i]= m.toString();
// ** Error is thrown at this line below**
Vec2 tmp = (Vec2) this.endpoint.onClick(args1);
return tmp;
//return null;
}
else
System.out.println("Endpoint is NULL");
}
}
onclick() method.
public synchronized Object onClick(Object[] args) {
try {
latch.await();
ctr++;
Log.d("CLIENT","Sending Param to Client "+args[args.length-1].toString()+" "+ctr);
objectOutputStream.writeBoolean(false);
// TEMP Commented
objectOutputStream.flush();
objectOutputStream.reset();
objectOutputStream.writeObject(args);
Callable<Object> worker = (Callable<Object>) new ClientThread(thisSocket,ctr);
return executor.submit(worker);
}catch (Exception e)
{
Log.e("ENDPOINT Exception",e.toString());
}
Log.e("ENDPOINT","Returning blank Object");
return new Object();
}
class ClientThread implements Callable <Object>{//Runnable {
private int ctr;
public ClientThread(Socket socket, int ctr)
{
this.ctr = ctr;
}
public synchronized Object call() {
Vec2 res1 = null;
Double res2=null;
Object res = null;
try {
Log.v("CLIENT","Attempting to receive results from Server "+ctr);
res = objectInputStream.readObject();
if (res instanceof Vec2)
{
res1 = (Vec2) res;
Log.v("CLIENT", "Object received Vec2 "+ctr);
}
else if (res instanceof Double)
{
res2 = (Double) res;
Log.v("CLIENT", "Object received Double "+ctr);
}
else
if(res==null)
Log.v("CLIENT", "Object received is NULL "+ctr);
else
Log.v("CLIENT", "Object received of UNKNOWN Type "+ctr);
} catch (UnknownHostException e1) {
Log.e("CLIENT receive error 1",e1.toString());
} catch (IOException e1) {
Log.e("CLIENT receive error 2",e1.toString());
}
catch (Exception e)
{
Log.e("CLIENT receive error 3",e.toString());
}
if (res1 !=null)
return res1;
else
if (res2!=null)
return res2;
else
return res;
}
//}
}

Any object can not be casted to any class or interface except classes/interfaces it extends/implements. FutureTask implements interfaces RunnableFuture, Runnable and Future.

OK its gone now. I just implemented ClientThread's code as merely a function call !
Strange are the ways of Java.....

Related

Why do i have a null pointer exception on database calls and what can i do to solve?

new AsyncTask<Ticket, Void, List<TPVLine>>() {
#Override
protected List<TPVLine> doInBackground(Ticket... params) {
List<TPVLine> lines;
while (true){
Log.d(TAG, "Waiting for data base response");
try {
lines = params[0].getLines();
Log.d(TAG, "Data base response completed");
break;
}catch (SQLiteException | NullPointerException ex){
ActiveAndroid.clearCache();
Log.d(TAG, "Cleaning cache");
Log.wtf(TAG, ex.toString());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return lines;
}
#Override
protected void onPostExecute(List<TPVLine> aVoid) {
super.onPostExecute(aVoid);
linesTPV = new ArrayList<TPVLine>();
if (aVoid != null){
linesTPV = aVoid;
}
linesTPV.addAll(noSavedLines);
mainActivity.getTpvFragment().resetPrice();
notifyDataSetChanged();
if (linesTPV.size() == 0){
mainActivity.getTpvFragment().getListContainer().setVisibility(View.INVISIBLE);
mainActivity.getTpvFragment().getMessageContainer().setVisibility(View.VISIBLE);
}else {
mainActivity.getTpvFragment().getListContainer().setVisibility(View.VISIBLE);
mainActivity.getTpvFragment().getMessageContainer().setVisibility(View.INVISIBLE);
}
notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mainActivity.getCurrentTicket());
This are the calls, first in Ticket.java
public List<TPVLine> getLines() {
return new Select().from(TPVLine.class).where("Ticket = ?", this.getId()).execute();
}
The second is in TPVLine.java
public static List<TPVLine> getLines(Ticket ticket){
return new Select().from(TPVLine.class).where("Ticket = ?", ticket.getId()).orderBy("Id ASC").execute();
}
The issue is caused when i call TPVLine.class, i make sure first that Ticket != null. I'm using ActiveAndroid to manage the database
you are returning null instead of lines in your asynctask doInBackground event.
return lines;

Using android hidden functions to manage call states

I am a beginner in android programming.
I want to use the hidden method "getState()" of "com.android.internal.telephony.call" package to manage the state of an outgoing call such as activating, ringing, answering, rejecting and disconnecting.
But there is an error in the following code on the line indicated by "**".
Any help?
My code is :
import com.android.internal.telephony.*;
public class MainActivity extends Activity {
Class myclass;
ClassLoader cloader;
Method f;
Object o;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cloader = this.getClass().getClassLoader();
try {
myclass = cloader.loadClass("com.android.internal.telephony.Call");
// No error generated. "Call" class will be loaded.
}
catch (Exception e)
{
System.out.println(e.toString());
}
try {
f = myclass.getMethod("getState", null);
// No error generated.Method "f" will be assigned
} catch (Exception e) {
System.out.println(e.toString());
}
Constructor constructors[] = myclass.getDeclaredConstructors();
// There is one constructor only
Constructor constructor = null;
for (int i=0; i<constructors.length;i++)
{
constructor = constructors[i];
if (constructor.getGenericParameterTypes().length == 0)
break;
}
constructor.setAccessible(true);
try {
o = constructor.newInstance(null);
//*****an exception generated here.
//*****Exception is "java.lang.instantationexception"
}
catch (Exception e) {
System.out.println(e.toString());
}
try {
f = myclass.getMethod("getState", null);
// No error
} catch (Exception e) {
System.out.println(e.toString());
}
}
Don't try to call private members like this. It will not work across Android versions and even across manufacturer customized ROMs of the same version.

Throw exception and getting e null

I throw a exception with some message like:
public static ILSResponseEmailLookUPBO getILSUserAccounts(Resources res,
String email) throws TripLoggerCustomException,
TripLoggerUnexpectedErrorException {
String resp = null;
String lookupURL;
try {
lookupURL = TripLoggerConstants.ServerConstants.ILS_LOOKUP_URL
+ URLEncoder.encode(email, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new TripLoggerCustomException(
res.getString(R.string.error_try_again));
}
try {
resp = ConnectionManager.getInstance().httpRequest(lookupURL,
TripLoggerConstants.RequestMethods.GET);
} catch (IOException e) {
if (e.getMessage().equals(
res.getString(R.string.network_unreachable))
|| e.getMessage().equals(
res.getString(R.string.host_unresolved))) {
throw new TripLoggerCustomException(
res.getString(R.string.network_not_reachable));
} else {
throw new TripLoggerCustomException(
res.getString(R.string.email_notfound_ils));
}
}
here my else part execute.
And my exception class is:
public class TripLoggerCustomException extends Exception {
private String customMessage;
private static final long serialVersionUID = 1L;
public TripLoggerCustomException() {
super();
}
public TripLoggerCustomException(String message) {
super(message);
this.customMessage = (message == null ? "" : message);
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
}
And here i catch this exception:
private void manageLookUpActions(final String emailID) {
new Thread() {
public void run() {
try {
listILSAccounts = ILSLookupEmailBL.getILSUserAccounts(
getResources(), emailID);
} catch (TripLoggerCustomException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
} catch (TripLoggerUnexpectedErrorException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
}
}
}.start();
}
but here in catch of TripLoggerCustomException e is null.why?Can anyone help me?
After looking into multiple reports on StackOverflow, it seems like this is not an actual issue. Multiple people have been saying that it is a problem in the combination of the Eclipse debugger and the Android Emulator. That is why you don't get a NullPointerException, which you would definitely get if e was null.
So this is probably not an issue you have to worry about.

NullPointerException (etc) from Parcel.readException

Exceptions that look like this are confusing:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.os.Parcel.readException(Parcel.java:1437)
at android.os.Parcel.readException(Parcel.java:1385)
at com.yourpackage.ipc.IYourClass$Stub$Proxy.yourMethod(IYourClass.java:488)
at com.yourpackage.ipc.YourClassShim.yourMethod(YourClassShim.java:269)
I found a bunch of related questions for this, but none with the answer to "how do you debug this". So I'm making this Question/Answer.
By looking at the android source here and here you'll see that it can be throwing any of these (the NullPointerException is just what I had):
SecurityException(msg);
BadParcelableException(msg);
IllegalArgumentException(msg);
NullPointerException(msg);
IllegalStateException(msg);
RuntimeException("Unknown exception code: " + code + " msg " + msg);
But what's causing these?
What's going on here is that readException() is checking the IPC byte stream for a header that says that an exception occurred; if it finds one, then it throws a new exception of that type, with the same message, but missing the original stack trace. (It only actually knows a few exception types; anything else gets translated into a base RuntimeException.)
So where's the original exception coming from? Well, somewhere down in the guts of the real implementation of YourClass.yourMethod() -- not in any of the parcelable or IPC code. So go there, wrap the whole method in a try/catch, and log whatever you caught.
(Or set a breakpoint there if you've got remote process breakpoints working.)
I think android SHOULD provide more binder remote exception information
so i modify Parcel.java to wrap more binder remote exception information
public final void writeException(Exception e) {
int code = 0;
if (e instanceof SecurityException) {
code = EX_SECURITY;
} else if (e instanceof BadParcelableException) {
code = EX_BAD_PARCELABLE;
} else if (e instanceof IllegalArgumentException) {
code = EX_ILLEGAL_ARGUMENT;
} else if (e instanceof NullPointerException) {
code = EX_NULL_POINTER;
} else if (e instanceof IllegalStateException) {
code = EX_ILLEGAL_STATE;
}
writeInt(code);
StrictMode.clearGatheredViolations();
if (code == 0) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
// I replace writeString(e.getMessage()) with writeString(remoteExceptionToString(e))
writeString(remoteExceptionToString(e));
}
static String remoteExceptionToString(Exception e) {
final StringWriter sw = new StringWriter(1024);
final PrintWriter pw = new PrintWriter(sw, true);
pw.println();
e.printStackTrace(pw);
return sw.toString().replace("\n", String.format("\n(%5d %5d): ", Process.myPid(), Process.myTid()));
}
SerializeExceptionSecondService defination:
public class SerializeExceptionSecondService extends Service {
private static final String TAG = "SerializeExceptionSecondService";
public SerializeExceptionSecondService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return mServiceBinder;
}
private final ISerializeExceptionSecondService.Stub mServiceBinder = new ISerializeExceptionSecondService.Stub() {
#Override
public void throwException() throws RemoteException {
// TODO Auto-generated method stub
Log.e(TAG, "throwException");
throw new IllegalStateException("Cause1", new IllegalStateException("Cause2", new IllegalStateException("Cause3")));
}
#Override
public void noThrowException() throws RemoteException {
// TODO Auto-generated method stub
}
};
}
AndroidManifest.xml fragment:
<service
android:name=".SerializeExceptionSecondService"
android:enabled="true"
android:exported="true"
android:process=":second_remote" >
</service>
in this way, the binder exception logcat will look like the below:

Saving Parcelable data

I have a class which implements Parcelable, and could not implement Serializable because it contains some basic Android classes that I can not modify.
Some of the objects in this class are for example Location and PendingIntent (which are all conveniently Parcelable).
My problem is saving this information between the instances of my main Activity.
Currently, I'm holding a static reference to this class, which works well. But I assume that when I re-install the app, and probably when updates will come around, I won't be able to trust that this static member won't be re-initialized.
I tried to write this Parcelable to a file, but using marshall() is not always working (I'm getting Binder can't be marshalled error).
How can I safely save this information?
Thanks
Using static in your example leads to memory leaks and is not a good way to do anything.
I suggest using static only in 3 cases:
static final String or int - constants
on inner classes (so that they don't contain reference to outer class)
on util or in some cases (like CustomFragment.newInstance) factory methods
The question is why would you want to persist PendingIntent? Its usecase is for inter-process-communication.
I use a StateControl class to handle reading/writing to disc:
public class StateControl {
Context mContext;
Thread worker;
WriteObjectToFile writer;
// StateControl Constructor
public StateControl(Context context) {
mContext = context;
// Construct a writer to hold and save the data
writer = new WriteObjectToFile();
// Construct a worker thread to handle the writer
worker = new Thread(writer);
}// end of StateControl constructor
// Method to save the global data
public void saveObjectData(Object object, String key) {
if (object == null){
// I had a different action here
} else {
// Write the data to disc
writer.setParams(new WriteParams(object, key));
worker.run();
}
}// end of saveGlobalData method
// Method to read the Global Data
public Object readObjectData(String key){
Object returnData = (Object) readObjectFromFile(key);
if (returnData == null){
// I had a different action here
} else {
return returnData;
}
}// end of readGlobalData method
// Method to erase the Global data
public void clearObjectData(String key){
writer.setParams(new WriteParams(null, key));
worker.run();
}// end of clearGlobalData method
private class WriteObjectToFile implements Runnable {
WriteParams params;
public void setParams(WriteParams params) {
this.params = params;
}
public void run() {
writeObjectToFile(params.getObject(), params.getFilename());
}
private boolean writeObjectToFile(Object object, String filename) {
boolean success = true;
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = mContext.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e) {
success = false;
e.printStackTrace();
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
// do nothing
}
}// end of if
}// End of try/catch/finally block
return success;
}
}// end of writeObjectToFile method
private Object readObjectFromFile(String filename) {
ObjectInputStream objectIn = null;
Object object = null;
try {
FileInputStream fileIn = mContext.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e) {
// Do nothing
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
// do nowt
}
}
}
return object;
}
private static class WriteParams {
Object object;
String filename;
public WriteParams(Object object, String filename) {
super();
this.object = object;
this.filename = filename;
}
public Object getObject() {
return object;
}
public String getFilename() {
return filename;
}
}
}
Then invoke the public methods to kick off the writing/reading. For this version, I also having it taking place in a separate thread, but you could modify that if you needed to.
Binder
Most developers will not implement this class directly, instead using
the aidl tool to describe the desired interface, having it generate
the appropriate Binder subclass.
from the official documentation
Do you need to store the Binder object with the rest of your object? Maybe you can save your object without the Binder instance, and re-create the Binder object with aidl after you restore the object

Categories

Resources