Search code examples
javaandroidevent-handlingjava-websocket

JAVA: How to listen to calling of event handler/How to get returned result of an event handler?


I am creating an Android chat application wherein I am using WebSockets and on top of that I want to create a custom implementation of Application protocol.

I am stuck in a situation.

Essentially, what I want is a way to know that an event handler method has been called in another class, fire up my own method in my class based on that and then get the result of that event handler method in my class.

How is that possible?

I researched a lot and found something like binding, event emitters, etc. Can someone point me to the right direction and provide some resources from where I can learn this technique?

This is what I have done so far:

public void connect(){

        try {

            setUpWebSocketHandler(handler);
           mConnection.connect(wsuri, handler);

        }
        catch (WebSocketException e) {

           Log.d("exception", e.toString());
        }


}


public void setUpWebSocketHandler(WebSocketHandler handler)
{
    handler = new WebSocketHandler(){

  //first method for websockethandler

        @Override
        public void onOpen() {


            //here i create a json format string to be sent to my         server that returns something afterwards
            String output = json.toString();
            Log.d("OUTPUT+" , output);
            Log.d("onOpen", "Status: Connected to " + wsuri);
            mConnection.sendTextMessage(output);
        }



//second method for websockethandler
        @Override
        public void onTextMessage(final String payload) {

            Log.d("onTextMessage", "Response: " + payload);
            JSONObject jsonObj = null;
            try {
                jsonObj = new JSONObject(payload);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {

                String type = jsonObj.getString("type");
                switch (type) {
                    case "xxx":
                        //authEvent
                        System.out.println("xxx");
                        break;
                    case "yyy":
                        //userOnlineEvent
                        System.out.println("yyy");
                        break;
                    case "zzz":
                        System.out.println("zzz");

                        break;
                    case "userListToken":

                        userList = getUserList(payload);

                        break;


                    default:
                        System.out.println("DefaultCase");
                        break;
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        }

//third method for websockethandler

        @Override
        public void onClose(int code, String reason) {
            Log.d("onClose", "Connection lost.");
        }

    };
}



public String getUserList(final String payload)
{
    final Thread connectthread;
    connectthread = new Thread(
            new Runnable()
            {
                public void run()
                {
                    try {
                        //here i create a URL, send post request to it and i get a response with userlist
                        HttpClient client = new DefaultHttpClient();

                        HttpGet post = new HttpGet(url);


                        HttpResponse response = client.execute(post);
                        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));


                        while ((userList = rd.readLine()) != null) {
                            System.out.println(userList);
                            Log.d("HTTP GET RESPONSE", "Response: " + userList);

                        }



                    } catch (JSONException | IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    );



    connectthread.start();
    try
    {
        connectthread.join();
    }
    catch (Exception e)
    {
        Log.i("error","Error!!");
    }

    System.out.println("userListToken");
    return userList;
}

I have another question. I got the userList using callbacks....The problem now is:

private class ProcessLogin extends AsyncTask<String, Void, String> {
    private ProgressDialog pDialog;
    String uname,password;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        uname = txtUsername.getText().toString();
        password = txtPassword.getText().toString();

        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setTitle("Contacting Servers");
        pDialog.setMessage("Logging in ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected String doInBackground(String... args) {

        String user = null;

        ifly.connect();


        user = userList;
        return user;
    }
    @Override
    protected void onPostExecute(String user) {
        try {

            if(user != null){






                //Intent i = new Intent("com.example.tabmainactivity");
                Log.d("Got it", "Response: " + userList);
                pDialog.dismiss();
                //startService(new Intent(getApplicationContext(),iFlyChatMessage.class));
                //startActivity(i);
                //finish();

            }else{
                // username / password doesn't match
                pDialog.dismiss();
                Toast.makeText(getApplicationContext(),
                        "Incorrect username/password", Toast.LENGTH_SHORT).show();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


public void processMessage(String userList)
{
       this.userList = userList;
}

I want the userList in postExecute so that i can send this userList to another activity. How do i stop doinbackground() to wait for callback to finish. If I use thread.sleep, the whole process stops, not even connect works.

Thanks


Solution

  • I'm not sure that I understood you correctly.

    You should use callback object.

    Something like:

    public interface MessageProcesor{
             public void processMessage(String message);
         }
    

    Your activity should implement this interface. And you should have MessageProcesor field in your "client" class. Your code should look something like this:

    private MessageProcesor callback;
    
    public void setUpWebSocketHandler(WebSocketHandler handler)
    {
        handler = new WebSocketHandler(){
    
      //first method for websockethandler
    
            @Override
            public void onOpen() {
    
    
                //here i create a json format string to be sent to my         server that returns something afterwards
                String output = json.toString();
                Log.d("OUTPUT+" , output);
                Log.d("onOpen", "Status: Connected to " + wsuri);
                mConnection.sendTextMessage(output);
            }
    
    
    
    //second method for websockethandler
            @Override
            public void onTextMessage(final String payload) {
    
                Log.d("onTextMessage", "Response: " + payload);
                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(payload);
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
    
                    String type = jsonObj.getString("type");
                    switch (type) {
                        case "xxx":
                            //authEvent
                            System.out.println("xxx");
                            break;
                        case "yyy":
                            //userOnlineEvent
                            System.out.println("yyy");
                            break;
                        case "zzz":
                            System.out.println("zzz");
    
                            break;
                        case "userListToken":
    
                            userList = getUserList(payload);
                            callback.processMessage(userList);
    
                            break;
    
    
                        default:
                            System.out.println("DefaultCase");
                            break;
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
    
    
            }
    
    //third method for websockethandler
    
            @Override
            public void onClose(int code, String reason) {
                Log.d("onClose", "Connection lost.");
            }
    
        };
    }
    
    
    
    public String getUserList(final String payload)
    {
        final Thread connectthread;
        connectthread = new Thread(
                new Runnable()
                {
                    public void run()
                    {
                        try {
                            //here i create a URL, send post request to it and i get a response with userlist
                            HttpClient client = new DefaultHttpClient();
    
                            HttpGet post = new HttpGet(url);
    
    
                            HttpResponse response = client.execute(post);
                            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    
    
                            while ((userList = rd.readLine()) != null) {
                                System.out.println(userList);
                                Log.d("HTTP GET RESPONSE", "Response: " + userList);
    
                            }
    
    
    
                        } catch (JSONException | IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
        );
    
    
    
        connectthread.start();
        try
        {
            connectthread.join();
        }
        catch (Exception e)
        {
            Log.i("error","Error!!");
        }
    
        System.out.println("userListToken");
        return userList;
    }
    

    You can pass "callback" as constructor param or via setter method.

    Hope this helps.