0
votes

I am using signalR android client in my app. The code was working fine all of a sudden, my code is unable to invoke server side funcitons. It gives java.lang.reflect.InvocationTargetException exception.

Here is my code,

public class SignalRService extends Service {

private microsoft.aspnet.signalr.client.hubs.HubConnection mHubConnection;
private microsoft.aspnet.signalr.client.hubs.HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder(); // Binder given to clients

public static final String BROADCAST_ACTION = "com.android.com.simplechatwithsignalr";

public SignalRService() {
}

@Override
public void onCreate() {
    super.onCreate();
    mHandler = new Handler(Looper.getMainLooper());
 //   GlobalBus.getBus().register(this);

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable e) {
            Log.i("hoo", "uncaughtException: " + e.getMessage());
        }
    });

}

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    int result = super.onStartCommand(intent, flags, startId);
    SubsrciptionHandlerAsync subsrciptionHandlerAsync = new SubsrciptionHandlerAsync();
    subsrciptionHandlerAsync.execute("run");
    return result;
}

@Override
public void onDestroy() {

    try {
        mHubConnection.stop();
    } catch (Exception e) {
        Log.i("destroying connection", "onDestroy: " + e.getMessage());
    }

 //   GlobalBus.getBus().unregister(this);
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    // Return the communication channel to the service.
    //  startSignalR();
    return mBinder;
}

/**
 * Class used for the client Binder.  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 {
    public SignalRService getService() {
        // Return this instance of SignalRService so clients can call public methods
        return SignalRService.this;
    }
}

/**
 * method for clients (activities)
 */


public void startSignalR() {
    Platform.loadPlatformComponent(new AndroidPlatformComponent());
    String serverUrl = "https://signalr.shifa4u.com/";
    serverUrl = serverUrl + "signalr";

    String CONNECTION_QUERYSTRING = "access_token=" + "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6IjYzNyIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJzaGFoaWQubXJkQGhvdG1haWwuY29tIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS9hY2Nlc3Njb250cm9sc2VydmljZS8yMDEwLzA3L2NsYWltcy9pZGVudGl0eXByb3ZpZGVyIjoiQVNQLk5FVCBJZGVudGl0eSIsIkFzcE5ldC5JZGVudGl0eS5TZWN1cml0eVN0YW1wIjoiMDY0Mjk4YTktNWIzNy00MGIxLWI1OTEtMzQwNGUzYTQ5YTE5IiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQ3VzdG9tZXIiLCJ1aWQiOiIyNjM3IiwibmJmIjoxNTUxNzg4NDc2LCJleHAiOjE1NTI5OTgwNzYsImlzcyI6Imh0dHBzOi8vYXBpLnNoaWZhNHUuY29tIiwiYXVkIjoiYWFkNGRjMDczOWI2NGM1MjlhYjg2YzIxMjZlZDM0MWMifQ.q0OAU8L9YRjkP5ampzdp7Ji8Vy-Wjd0Wf0hs3kTg3pg" + "&Is_Guest_User=NO";

    mHubConnection = new microsoft.aspnet.signalr.client.hubs.HubConnection(serverUrl, CONNECTION_QUERYSTRING, false, new Logger() {
        @Override
        public void log(String message, LogLevel level) {
            System.out.println(message);
        }
    });

    mHubConnection.connected(new Runnable() {
        @Override
        public void run() {
            System.out.println("CONNECTED");
            Log.i("Initail Connect", "run: " + "Initial Connect");
        }
    });

    mHubConnection.closed(new Runnable() {
        @Override
        public void run() {
            Log.i("CLosed", "run: Disconnected");
        }
    });


    mHubConnection.error(new ErrorCallback() {
        @Override
        public void onError(Throwable throwable) {
            Log.i("Signal R throwable", "onError: " + throwable);
        }
    });


    String SERVER_HUB_CHAT = "IntegratedHUB";
    mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
    ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
    SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
    try {
        signalRFuture.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.e("SimpleSignalR", e.toString());
        return;
    }


    try {
        welcome();
        //  welcome();
    } catch (Exception e) {
        Log.i("Exception", "startSignalR: " + e.getMessage());
    }


    mHubProxy.on("connectionSucceeded", new SubscriptionHandler1<String>() {
        @Override
        public void run(final String msg) {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "connectionSucceeded", Toast.LENGTH_SHORT).show();

                    Log.i("connectionSucceeded", "run: " + "connectionSucceeded");

                    invokeUpdateCall("");
                }
            });
        }
    }, String.class);


    mHubProxy.on("guestConnectionSucceeded", new SubscriptionHandler1<String>() {
        @Override
        public void run(final String msg) {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "guest", Toast.LENGTH_SHORT).show();

                    Log.i("connectionSucceeded", "run: " + "guest");

                    invokeUpdateCall("");
                }
            });
        }
    }, String.class);


    mHubProxy.on("organizerConnectedForMobileClient", new SubscriptionHandler3<Long, String, String>() {

        @Override
        public void run(Long urgentCallId, String token, String resourceId) {
            Log.i("organizerConnected", "run: " + "organizerConnected");
            //  Toast.makeText(SignalRService.this, "Organizer connected", Toast.LENGTH_SHORT).show();

          /*  Shifa4U.mySharePrefrence.setUrgentCallId(urgentCallId);
            Shifa4U.mySharePrefrence.setToken(token);
            Shifa4U.mySharePrefrence.setResourceId(resourceId);


            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Events.ConnectWithDoctor connectWithDoctor =
                            new Events.ConnectWithDoctor("");
                    GlobalBus.getBus().post(connectWithDoctor);
                }
            });*/

        }


    }, Long.class, String.class, String.class);



    mHubProxy.on("connectionFailed", new SubscriptionHandler1<String>() {
        @Override
        public void run(final String msg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Connnection Failed", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }, String.class);



    mHubProxy.on("greatMessage", new SubscriptionHandler1<String>() {
        @Override
        public void run(final String msg) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Greatest message    " + msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }, String.class);
}

public void invokeOnConnectedHub(String message) {
    String SERVER_METHOD_SEND = "OnConnectedHub";

    if (mHubConnection.getState().toString().equals("Connected")) {

        try {
            mHubProxy.invoke(SERVER_METHOD_SEND).done(new Action<Void>() {
                @Override
                public void run(Void obj) throws Exception {
                    System.out.println("SENT!");
                }
            });
        } catch (Exception e) {
            Log.i("", "On Connected HUB: " + e.getMessage());
        }
    }
}



public void welcome() {
    String SERVER_METHOD_SEND = "Welcome";

    if (mHubConnection.getState().toString().equals("Connected")) {

        try {
            mHubProxy.invoke(SERVER_METHOD_SEND).done(new Action<Void>() {
                @Override
                public void run(Void obj) throws Exception {
                    System.out.println("SENT!");
                }
            });
        } catch (Exception e) {
            Log.i("", "On Connected HUB: " + e.getMessage());
        }
    }
}



public void invokeUpdateCall(String message) {
    String SERVER_METHOD_SEND = "UpdateCallRoom";
    //  mHubProxy.invoke(SERVER_METHOD_SEND);
    try {
        mHubProxy.invoke(SERVER_METHOD_SEND).done(new Action<Void>()
        {
            @Override public void run(Void obj) throws Exception
            {
                System.out.println("SENT!");
            }
        });
    }
    catch (Exception e)
    {
        Log.i("", "UpdateCallRoom: "+e.getMessage());
    }
}

}

class SubsrciptionHandlerAsync extends AsyncTask {

@Override
protected String doInBackground(String... strings) {
    try {
        SignalRService signalRService = new SignalRService();
        signalRService.startSignalR();
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
}

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

}

Here is the stack trace.

I/System.out: serverSentEvents - Found new data: data: {"C":"d-8BC122A6-B,1F|IU,0|IV,1","M":[{"H":"IntegratedHUB","M":"greatMessage","A":["Welcome"]}]}

serverSentEvents - Trigger onData: {"C":"d-8BC122A6-B,1F|IU,0|IV,1","M":[{"H":"IntegratedHUB","M":"greatMessage","A":["Welcome"]}]}

HubConnection - Received data: 

I/System.out: MessageId received: d-8BC122A6-B,1F|IU,0|IV,1 Invoking OnReceived with: null HubConnection - Processing message

I/System.out: HubConnection - Getting HubInvocation from message

I/System.out: HubConnection - Message for: integratedhub

I/System.out: HubConnection - Invoking event: greatmessage with arguments

["Welcome"] I/System.out: HubConnection - Error: java.lang.reflect.InvocationTargetException

I/Signal R throwable: onError: java.lang.reflect.InvocationTargetException

I/System.out: serverSentEvents - Response received serverSentEvents - Read response to the end

I/System.out: serverSentEvents - Trigger onData with data: {"I":"0"}

1
Was java upgraded on your machine(s)? It could be a lot of different issues like a certificate expiring. I would start by using a sniffer like wireshark or fiddler to get a better diagnostic message and to find out if the issue is on the client or server end. - jdweng
I updated my android studio version. Maybe the java version was updated too. - Ali Imran Bangash
Make sure the code re-compiles completely. The dependencies i the compiler do recognize Net Library updates and may not work after an update. I usually recommend making a copy of the project bin folder and then delete the bin folder. This will force the compiler to recompile everything. - jdweng
I have created a new project and implanted this again. Still the same issue. New project always compiles everything for the first time. So, i don't think it's a recompilation issue. - Ali Imran Bangash

1 Answers

0
votes

On function not works and throw exception when it calls. Use subscribe function instead of that. That's work for me.

 hub.subscribe("name of your event").addReceivedHandler(new Action<JsonElement[]>(){
       @Override
       public void run(JsonElement obj) throws Exception  {
          // do something
       }
    });