5

Edit: I was actually able to get this to work and form, in my oppinion, a good example. The accepted answer is my example and feel free to leave comments if you need assistance or have advice.

I am very new to java and have just been introduced to events, handlers and listeners. I have found 3 good references online, however, i am still not seeing how i can implement this to solve my problem. (Also, this is being developed on the android. I doubt that will change the example, but thought i would let you know)

Links to sites i found helpful:
happy object
example depot
java world

Here is what i need, using arbitrary names and examples instead of plopping my hundreds of lines of code in here:

Here are my class and their uses:
MainUI - this creates the UI
Connect - this class performs a connection to a socket and starts receiving data
DataRobot - this class performs calculations on the data that is received and decides what to do with it
DataBuilder - this class gathers the data from the datarobot and once a certain amount is reached it sends that chunk to a remote database
DataSender - this class sends that data that is sent to it by the databuilder

I was implementing this with threads... =(
Someone i know suggested i use events. He gave me a great explanation, however, it was within 30 minutes and i do not see how i can implement it without seeing some better examples (he was also speaking from a C# background). I was wondering if someone out there with some great experience in java could use what i have above and show me what i need to do.

Here are the events that i have planned out:
dataReceived - this event happens in connect, this event fires when connect receives data when this event fires it sends the data to the data robots handler() function.
dataAnalyzed - this event happens in datarobot, this event fires when datarobot is done handling the data that was given to it, when this event fires it sends the data to the databuilder
dataBuilder - this event happens in databuilder, this event fires when databuilder has received a certain amount and is ready to send the data, when this event fires it sends the data to the datasender.

I am looking for an example here or at least a discussion on what should be done. One of the examples i found was the "happyfaceobject" example and it was pretty good. However, i am still having trouble implementing it in my design, since i am VERY new to java and events. Please assist me when you can and it will be greatly appreciated. This example would also help the community as a whole as there is a lacking of great java events examples.

Thanks in advance, if you need more info let me know.

prolink007
  • 33,872
  • 24
  • 117
  • 185
  • Also, if i figure this out before a great answer is given, i will post the example here for the community for future users who have the question. =P – prolink007 Jan 27 '11 at 16:46
  • 2
    I recommend reading about [Java naming conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html#367) as your class names are pretty confusing right now. – Sergei Tachenov Jan 27 '11 at 16:54
  • @Sergey, thanks for the suggestion. I have that bookmarked now. =) I will come back and edit this question with better naming convention when i get the chance. – prolink007 Jan 27 '11 at 18:23
  • I uploaded the example that i wrote up. It is working for me, can everyone please take a look at it and give suggestions on suggested improvements or maybe something that is bad practice? Thanks – prolink007 Jan 31 '11 at 19:28

2 Answers2

5

You're very new to Java - I think you're overcomplicating this and trying to swallow too much at once.

Forget about your grand design. Forget about UI. Forget about Android.

Start with a toy problem and build up.

Can you make a single Listener class that responds to an Event and a producer class to send that Event out? Can you see the action being taken? If you can't do that, you won't get far. When you have one working, move onto the next and see if you can get your design working with these simpler objects. Only when the whole thing is working should you worry about tying in the Android and UI elements.

Start with simple POJO models and you'll get further faster.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Got it working and have posted the example here. Take a look and if you have any advice, please let me know. – prolink007 Jan 30 '11 at 17:31
  • Fixed a problem that commonsware pointed out. I was wondering if you could take a look over the code i have posted for an answer and see if you can make any more suggestions. It was working and commonsware told me to take out the constructor for SmartApp, anything else? Thanks in advance! – prolink007 Feb 05 '11 at 21:07
  • You've already accepted an answer. What else do you require? – duffymo Feb 05 '11 at 22:45
1

I have got this working and it seems to be a great example. I will post the code below, hopefully it will help someone some day! =D PLEASE if you see that i have done something wrong, or know a better way, post some comments so i can correct it. Thanks

Basically every event you want to create needs an Event Object, Listener Interface, AddListener Function, RemoveListener Function, FireEvent Function and the Listeners. All of this can be seen in the examples below. If you have any questions, please post in the comments and if this helps you, feel free to upvote! =P

/* SmartApp.java */
public class SmartApp extends Activity 
{
    private ConnectDevice cD = new ConnectDevice();
    private DataRobot dR = new DataRobot();
    private DataBuilder dB = new DataBuilder();
    private DataSender dS = new DataSender();
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.intro);

    cD.addDataReceivedListener(new DataReceivedListener() {
        @Override
        public void dataReceivedReceived(DataReceivedEvent event) {
            // TODO Auto-generated method stub
            dR.analyzeData(event.getData());
        }
    });
    dR.addDataAnalyzedListener(new DataAnalyzedListener() {
        @Override
        public void dataAnalyzedReceived(DataAnalyzedEvent event) {
            // TODO Auto-generated method stub
            dB.submitData(event.getData());
        }
    });
    dB.addDataBuilderListener(new DataBuilderListener() {
        @Override
        public void dataBuilderReceived(DataBuilderEvent event) {
            // TODO Auto-generated method stub
            dS.sendData(event.getData());
        }
    });
      }
}  

/* ConnectDevice.java
 * This class is implementing runnable because i have a thread running that is checking
 * the contents of a socket. Irrelevant to events. */
public class ConnectDevice implements Runnable {

    private List _listeners = new ArrayList();
    private String data;

    /* Constructor */
    public ConnectDevice() {// does some socket stuff here, irrelevant to the events}
    public void run() {// does some socket stuff here, irrelevant to the events}

    public synchronized void addDataReceivedListener(DataReceivedListener listener) {
        _listeners.add(listener);
    }
    public synchronized void removeDataReceivedListener(DataReceivedListener listener) {
        _listeners.remove(listener);
    }
    private synchronized void fireDataReceivedEvent(String temp) {
        DataReceivedEvent dRE = new DataReceivedEvent(this, temp);
        Iterator listeners = _listeners.iterator();
        while(listeners.hasNext()) {
            ((DataReceivedListener)listeners.next()).dataReceivedReceived(dRE);
        }
    }
    public interface DataReceivedListener {
        public void dataReceivedReceived(DataReceivedEvent event);
    }
}  

/* DataRobot.java */
public class DataRobot {
    /* This class is for analyzing the data */
    private List _listeners = new ArrayList();
    private String data;
    public boolean analyzeData(String temp) {
        /* Analyze the data
         * This function analyzes the data, as explained in the OP
         * This function fires the analyzed data event when finished
             * analyzing the data.
         */
        data = temp;
        fireDataAnalyzedEvent(data); // this fires the dataanalyzedevent
        return true; //for now this will always return true
    }

    public synchronized void addDataAnalyzedListener(DataAnalyzedListener listener) {
        _listeners.add(listener);
    }
    public synchronized void removeDataAnalyzedListener(DataAnalyzedListener listener) {
        _listeners.remove(listener);
    }
    private synchronized void fireDataAnalyzedEvent(String temp) {
        DataAnalyzedEvent dRE = new DataAnalyzedEvent(this, temp);
        Iterator listeners = _listeners.iterator();
        while(listeners.hasNext()) {
            ((DataAnalyzedListener)listeners.next()).dataAnalyzedReceived(dRE);
        }
    }
    public interface DataAnalyzedListener {
        public void dataAnalyzedReceived(DataAnalyzedEvent event);
    }
}  

/* DataBuilder.java */
public class DataBuilder {
    private List _listeners = new ArrayList();
    private String data;
    public boolean submitData(String temp) {
            /* Builds the data
             * This function builds the data, as explained in the OP
             * This function fires the databuilder data event when finished
                     * building the data.
             */
        data = temp;
        fireDataBuilderEvent(data); //firing the databuilder event when finished
        return true;
    }
    public synchronized void addDataBuilderListener(DataBuilderListener listener) {
        _listeners.add(listener);
    }
    public synchronized void removeDataBuilderListener(DataBuilderListener listener) {
        _listeners.remove(listener);
    }
    private synchronized void fireDataBuilderEvent(String temp) {
        DataBuilderEvent dRE = new DataBuilderEvent(this, temp);
        Iterator listeners = _listeners.iterator();
        while(listeners.hasNext()) {
            ((DataBuilderListener)listeners.next()).dataBuilderReceived(dRE);
        }
    }
    public interface DataBuilderListener {
        public void dataBuilderReceived(DataBuilderEvent event);
    }
}  

/* DataSender.java */
/* this class has no event, because it is done firing events at this point */
public class DataSender {
    private String data;
    public boolean sendData(String temp) {
        data = temp;
        return true;
    }
}  

Below here are the event objects for each event. I Have each of this defined in a separate file, not sure if that is good procedure or not.

/* DataReceivedEvent.java */
public class DataReceivedEvent extends EventObject{
    private String data;
    public DataReceivedEvent(Object source, String temp) {
        super(source);
        // TODO Auto-generated constructor stub
        data = temp;
    }
    public String getData() {
            // this function is just an accessor function
        return data;
    }
}  

/* DataAnalyzedEvent.java */
public class DataAnalyzedEvent extends EventObject{
    private String data;
    public DataAnalyzedEvent(Object source, String temp) {
        super(source);
        // TODO Auto-generated constructor stub
        data = temp;
    }
    public String getData() {
            // this function is just an accessor function
        return data;
    }
}  

/* DataBuilderEvent.java */
public class DataBuilderEvent extends EventObject {
    private String data;
    public DataBuilderEvent(Object source, String temp) {
        super(source);
        // TODO Auto-generated constructor stub
        data = temp;
    }
    public String getData() {
            // this function is just an accessor function
        return data;
    }
}
prolink007
  • 33,872
  • 24
  • 117
  • 185
  • 1
    Never implement a constructor on an activity. And, at the end of the day, you have a couple hundred lines of code that do absolutely nothing and are likely to get you into some bad patterns when you try to actually use this in an Android app. – CommonsWare Feb 05 '11 at 20:20
  • That is why this is posted here, is for someone to help me to figure this out. If you would be so kind to maybe fix my example to be the correct way, that would be great! Thanks, because im new to this and i am only guessing. – prolink007 Feb 05 '11 at 20:21
  • If i can't have that constructor, where do i add the listeners? Do i put them in the onCreate method? Could you please assist me? This implementation is working and seems to be fine, but if i am doing something wrong and you know how to fix, will you please post a solution? It would be greatly appreciated! Would be more than happy to accept your answer instead of mine, if it worked. =P – prolink007 Feb 05 '11 at 20:29
  • I removed the constructor for SmartApp and then added my listeneres in the OnCreate method, is that good practice? What else should i be correcting, any help would be greatly appreciated! – prolink007 Feb 05 '11 at 21:04
  • Like i said in my OP, this method is working for me and seems to be doing fine. However, if you have a better implementation and wouldn't mind changing my example to a more appropriate implementation that would be amazing! – prolink007 Feb 05 '11 at 21:18