Using AsyncTask With a Observer based Controller class (MVC Arch.) - java

I've been following this tutorial.Now, I have to fetch and parse some JSON from a web URL. For that I am thinking to use an AsyncTask for now (might try something else as well. Such as a separate thread. advice..?)
But am not able to decide and approach things for now as to how the AsyncTask can inform back to the controller about the state of execution (I thought of using a handler but that'll defeat the purpose of already used controller acting as a Observer for button click(s)..starting the AsyncTask as well) and where can I put the AsyncTask. Certainly not in the controller itself. As the controller has the sole responsibility of giving out commands/judging + it'll be a cluster f* :D
Any help in form of sample code clearly showing me how/what to accomplish is appreciated. Thanks

You can apply a simplified Observer pattern to your AsyncTask also. Here, your Controller becomes the Observer and AsyncTask will be the notifier. In your onPostExeccute of the AsyncTask, you notify your observers with the result. In your Controller, implement the update method and take action on the result.
Since usually AsyncTask needs to notify only one object, I follow the simpler Listener interface. Define a simple interface with a method called handleResult which takes appropriate data structure. My activity implements this interface (but in your case, it would be the controller) and adds code to handle the result. My AsyncTask stores this listener as a field and on completion of the task, calls the handleResult method.
But as you can see, it is very similar.

Related

Good design patterns for coding many HTTP requests in Android

In my app, i have lots of GET,POST, PUT requests. Right now, i have a singleton class that holds my downloaded data and has many inner classes that extend AsyncTask.
In my singleton class, i have also a few interfaces like this:
/**
* Handlers for notifying listeners when data is downloaded
*
*/
public interface OnQuestionsLoadedListener {
public void onDataLoadComplete();
public void onDataLoadingError();
}
Is there something wrong with this pattern (many inner classes that extend AsyncTask)?
Could it be done more efficiently with maybe just 1 inner class for every HTTP call (1 for GET, 1 for POST, ...)? If so, how to decide what to do after e.g. GET request?
As a whole, you should get away from AsyncTasks while preforming network requests.
Your AsyncTasks are linked to your Activity. That means, if your Activity stops, your AsyncTask stops.
This isn't the biggest problem when fetching data to show in that Activity, since you won't care that the fetching has stopped. But when you want to send some saved data to the server, and your user pressed 'back' or something like that before everything is sent, the data could be lost and not send.
What you want to have instead, is a Service which will keep running regardless of what happens to your Activities.
I'd advise you to take a look into RoboSpice. Even if you decide not to use it, reading what it does and why it does will give you a good insight on the pretty long list of reasons not to use AsyncTasks for network requests and why better to use Services.
If you use this, the rest of your question about efficiently network requesting is obsolete too, since they'll handle it for you the best way possible.
Nothing wrong with many async classes.
What ido is have a network layer,a service class. Send an intent to the service class with a resultreceiver object as part of intent. then in the service make http request in async task and send back the the result through result receiver object.
A good design is to abstract the ui (activity or fragment) from network access.
In a recently developed app I followed a similar scheme but in addition implemented a WebRequest class doing the actual GET, POST, PUT etc.
What I now have is a "Connector" class which has a whole lot of AsyncTask subclasses within.
In my implementation, however, I made them accept a Callback object to which each of those subclasses passes the Http result.
I think this is a valid if perhaps not ideal way.
What I imagine could be an improvement would be if I had just one subclass of Asynctask to which I would pass the request body (which is now built within those different tasks), the request url and method as well as the callback (which is, in my opinion a rather nice way to get the results).

Where should I invoke my swingworker in a Java MVC pattern

I have a program that is basically set up just like the one in this MVC example: http://www.leepoint.net/notes-java/GUI/structure/40mvc.html
In my program there is a process which takes quite a bit of time which freezes my GUI. I want to GUI to continuously update while the process is running. To do this I believe I need to use a SwingWorker. I don't know where in my MVC pattern I should be invoking this SwingWorker.
My thinking is that I should be running it in the MultiplyListener actionlistener of the controller. Would this be correct?
In this case, the model is a mathematical operation that evolves over time, perhaps by iteration. Clearly, the worker belongs in the model, as shown here. The setProgress() method will notify any PropertyChangeListener, and process() can notify any other listening view, as shown here.
Addendum: In the second example, the worker updates a different model: the chart's dataset named collection. The chart, in turn, listens to the dataset and updates itself in response to the change.
In the example cited, the controller installs action listeners on behalf of the model and view. In this related example, the GUI action listeners are local to their respective views. In either case, Action would be a suitable choice for encapsulation. The model notifies its observers when its internal state changes in response to user initiated actions.
I think that your SwingWorker belongs in the Control and I'll tell you why. I feel that the Model should be as View agnostic as possible and should be created with the idea that it can be used with different views and controls, and even with a completely different GUI library, if desired. For instance, you are currently wanting to use the Model in a Swing GUI, but what if later you want to use it in an Android application? In order to allow it to be used with as few modifications as possible, most code that is Swing-specific, such as a SwingWorker should reside in the Control or View.
For example, please check out this answer.

present live data in JTextArea using Swing

Don't know if it's stupid or reasonable question.
I have methods which returns float/int data (x,y,z positions) of the P5 Glove (if you know it).
I also have update method which responds to the glove pulling.
All i'm having trouble with is creating UI and presenting the data in text area, means every update the text areas presenting the data refreshed and present the data.
Since code isn't that short here are links to the class: Details presentation methods and update
let's say for now I want to present showActiveLedPosX() method which returns the X position as String.
the other classes are glove (using glove methods and creating glove object and UI).
Should I use different class for UI? or should I do it all on ShowGloveValues class
I've never created UI and therefore I'm kinda clueless here, Tried to read about it on numerous resource sites and still couldn't achieve what's needed.
1. Keep the UI thread apart from the Non-UI thread.
2. Event Dispatcher Thread is the UI thread, keep this thread to handle your UI only.
3. You can also use SwingWorker for this.
4. Swing is based on Mode View Controller. Moreover its better to divide your app packages also on the basis of MVC.
eg:
com.vivek.model; // Class responsible for Business Logic and Data
com.vivek.view; // Class responsible for the UI

How to make callbacks using AsyncTask android

I am making request to web service and have to do this extending AsyncTask for every methods. So how many methods i have in webservice that many classes i need to create in this way.
I found this topic how to make callback:
Making Callback
But there are shown one class callback, but what if i want that there would lots of callbacks in one class ?
The AsyncTask class has generic parameters for data that is passed between its methods. You can use a custom class to pass the data from one method to other.
Web-service access is usually done in 3 steps :
Retrieving the content (XML/JSON etc.)
Parsing the content
Reading the content.
You can pass the AsyncTask the URL to be fetched (As shown there)
In background you can retrieve content and parse it. The reading of content can be done in different code blocks which run on UI thread depending on the result parameter.

Newbie Java developer questions - inter class communication with events

Please forgive the very basic nature of this questions - but we all have to start somewhere. I've done some googling but all answers seem to relate to UI Events.
I am creating a very simple android app that will display your location on screen. I have my main class (HelloAndroid at the moment) that extends Activity and I have created a class LcoationUpdateHandler that listens for updates.
HelloAndroid holds an instance of LocationUpdateHandler so my question is how does the LocationUpdateHandler communicate with HelloAndroid.
In flex I would dispatch an event from one to the other but from the searching I have done this doesn't seem like a very java-y way of doing things?
Thanks for your help.
When your HelloAndroid instance creates an instance of LocationUpdateHandler it can pass a reference to itself in the constructor, which LocationUpdateHandler can store to use for future method calls in the case of events.
For these kinds of situations you don't really need to know what type of object instatiated LocationUpdateHandler. This is were interfaces come in, you can define an interface defining the event methods and implement that interface so that LocationUpdateHandler can keep a reference to that interface to deliver events.
If the situation is symmetrical, both classes can implement the same event interface.
It sounds like what you're looking for is the Observer pattern. The way it works is that observers register with the object that they are observing, such that they can be notified on events.
In your specific case, if you want LocationUpdateHandler to push information to HelloAndroid, it has to know about HelloAndroid. So your LocationUpdateHandler should at least contain a reference to HelloAndroid, but to generalize this, it should have a List of observers that all implement a common interface containing a callback function that would be called whenever LocationUpdateHandler has an update.

Categories

Resources