Perform AsyncTask inside Class - java

I have a method inside of a class called
ChopraWisdom.GetQuote()
that pulls in some data from the interwebs. To use it I have to use an AsyncTask in my activity. Thats fine and all, but my Activity code now gets cluttered with the AsyncTask code.
I was hoping that I could hide the AsyncTask in my Class and then create another method called
ChopraWisdom.GetQuoteAsync()
But I'm not sure how to pass in "Actions" (I come from a .Net background) in order to handle the various UI updating that needs to take place.
In C# I would define the method signature as something like:
ChopraWisdom.GetQuoteAsync(Action preExecute, Action postExecute, Action updateProgress)
Questions:
Does java have something comparable to 'Action'?
What is the acceptable pattern for 'wrapping' Async functionality like this in Java?
I like clean code, but am I being to picky here?
Please provide examples.
EDIT - Added Example class
public class ChopraWisdom
{
public string GetQuote()
{
//...do stuff and return a string
}
}

You should really think about using Loaders instead of AsynkTask(with android support lib).
If you still want to use AsyncTask in your situation best way would be to create new interface Action(something like https://github.com/ReactiveX/RxJava/blob/1.x/src/main/java/rx/functions/Action0.java)
You could use RxJava in your project and use all they have https://github.com/ReactiveX/RxJava/tree/1.x/src/main/java/rx/functions
You could use https://github.com/evant/gradle-retrolambda in combination with (2) option to provide C# like lambdas in your java code.

Java does have something comparable to Action. It is called Function and only available in Java 8. The standard way for passing a function as parameter is to create an interface and provide it as a parameter. That way you can either pass in an instance of a class implementing that interface or create an anonymous class inline. You encounter the latter everywhere in Android (OnClickListener, etc ...)
I would highly recommend you to take a look at Android Annotations. It provides useful features like:
Dependency injection
View injection
OnClickListener via annotation
AsyncTask via annotation
...
And the best thing: everything is done at compile time through subclassing, therefore there is no performance impact and you can check what the framework is doing at any given point.
You are not too picky at all. Clean code is very important in Android development as you have to write a lot of boilerplate- / gluecode anyway.
Here are some other handy android frameworks that are definitely worth checking out:
GreenDao
Eventbus

Related

Class wrapper extending different base class

I have a Java project and now I also want to use this code for a GWT project so I don't have to write the same code twice. The problem is that some classes are not available in gwt, for example java.awt.geom.Rectangle2D.Double.
I was thinking of creating a wrapper class called RectangleWrapper that would extend either the standard Rectangle class or a gwt version of the same class.
In the shared code I would replace all my Rectangle2D.Double with my Rectangle and depending on a final boolean my wrapper class (compiler flags java) would either extend on or the other Rectangle class.
Is this even possible or is there a better way to do this?
I just took one of my GWT-project client-side classes and added the following lines:
if (false) {
String a = StringEscapeUtils.escapeHtml("lalala");
}
This obviously compiles just fine, but when I launch the GWT app I get this:
ERROR: Errors in 'file:/C:/gwtproject/src/main/java/package/ClientSideClass.java'
ERROR: Line 119: No source code is available for type org.apache.commons.lang.StringEscapeUtils; did you forget to inherit a required module?
So the answer would be no, you can't use a wrapper like that.
Is there any other way of achieving that? I highly doubt it.
One of the main features of GWT is replacing the old AWT/Swing desktop GUI components with a whole set of web GUI components designed for Javascript compatibility; there's no point in making the old components available or supported in any way.
If you were talking about utility libraries like Apache Commons, I could advise you to make an RPC call instead (client-side calls server-side where you can use anything you like, and return the results asynchronously), but that's not the case.

Which GWT EventBus should I use?

In the gwt-user.jar there are 2 EventBus interfaces and SimpleEventBus implmentations.
com.google.gwt.event.shared.EventBus and com.google.web.bindery.event.shared.EventBus
I'll refer to these as 'gwt.event' and 'web.bindery'.
Looking at the JavaDocs and source code I can see that the gwt.event merely wraps the web.bindery one. However the gwt.event implementation also hides a number of deprecated methods
So which implementation should I use? (I'm on GWT 2.4)
Generally you should use the one in com.google.web.bindery. The only version used to be in com.google.gwt.event, but when RequestFactory and AutoBeans were moved out of GWT itself and into com.google.web.bindery so they could work in non-GWT clients.
If you use the com.google.web.bindery version in your presenters and such, it will make it easier to use outside GWT apps, should you need to. You'll also not get deprecation warnings when passing that instance to PlaceController and other classes that use EventBus.
I know this question has already an answer but might be worth while adding the following. As I said in my comment above, Activity still needs the com.google.gwt.event.shared.EventBus class. To avoid deprecated warnings, I did the following (I use GIN):
public class GinClientModule extends AbstractGinModule {
#Override
protected void configure() {
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
...
}
#Provides
#Singleton
public com.google.gwt.event.shared.EventBus adjustEventBus(
EventBus busBindery) {
return (com.google.gwt.event.shared.EventBus) busBindery;
}
...
By doing this, you will always be using the object from the "new" version of Event bus in the bindery package.
If you use Activities, then you'll probably have to use the deprecated one, at least until they clean up the whole API: http://code.google.com/p/google-web-toolkit/issues/detail?id=6653.
To make the choice even more complex. I am using guava in my GWT application and the google guys have added yet another EventBus in there (even less feature complete).
Maybe those guys need to sit together and define ONE implementation to rule them all ?
Obviously I would like to avoid all dependencies on GWT for code that is not strictly used in GWT code, so the Guava one looked interesting to me.

What is the optimal way to share code between Activities with different base classes?

I have the following problem:
I have an abstract Activity class, lets call it MyAbstractActivity, that contains some code I'd like to reuse (for example: a standard service binder, common menu items, common initialization code, etc. etc.). Normally I would just use it to subclass my concrete activities and be done with it.
However, I occasionally need to use another supertype, such as a ListActivity or a MapActivity.
So the question is: how do I avoid duplicating that support code within an Activity, if I have to use another base class?
I have thought up of a solution based on the decorator pattern, like this one:
.
However, I see a problem with this approach:
What to do with protected methods (like onCreate())? Should I introduce an additional "bridge" class that makes them public for the purpose of the decorator, similarly to the way presented below (starting to look a bit byzantine...)?
Any other way?
I hope I made myself relatively clear. Thanks in advance for any feedback!
PS. Using static utility classes is not a good solution in my opinion, since it introduces a possibility of hard-to-identify programming bugs.
If I understand correctly, neither Fragments nor the Decorator Pattern are clean or appropriate solutions for what you want to accomplish. They were designed to solve other problems.
I find myself moving "support" code, or "framework" code, or "all that verbose, repetitive, boilerplate crap" to static utility methods. This isn't necessarily the approach I'd take on a non-Android project, but in my Android projects, it works pretty darn well.
Also, know that you don't need to subclass ListActivity to have a ListView.

Java API Question

I am trying to implement a custom Java widget using GWT.This requires me to copy a class from the GWT API and pasting it in my own new Class.(I am not sure if this is a right approach.Suggest me if its wrong to copy the API in my new class).The reason why i am doing this is i need to make modifications to the API,because the API does not provide me getter/setter's for a object.
But the problem with this is ,the API class uses many methods which have the protected access modifier.So when i paste this code in my package ,these methods are not recognized.I cannot even think of making my class a sub class (a workaround for protected access modifier) as the methods are from different classes and i cannot make my class a sub class of more than one class.
Can any one suggest me a work around for this scenario.I am trying to implement a widget whose functionality is similar to the browser's navigation widget(the place where we enter a website's url).Its similar to combining the functionality of ListBox+SuggestBox.
This is my previous question.That is what i am trying to implement.
Thanks
Derive a new widget by extending from Composite and then implement whatever functionality you need within that. e.g. If you need a ListBox to make suggestions then create one from inside your Composite and hook up whatever listeners you need to on the inner widget to drive suggestions.
A sample of a Composite widget is shown here.
There shouldn't be any reason to have to copy & paste existing source code. Indeed doing so is not going to get you far since most widgets in GWT are just wrappers HTML elements anyway with some plumbing to hook up to the event model.
It would really help if you provided some sample code, you should never have to copy and paste code from the API. What are you trying to extend and what variables within that class do you need access to and to do what? Usually there is a reason why variables are private and thats because messing with them will cause a break in functionality.

Where to put business logic in Eclipse RCP program

I'm writing a small application in RCP to wrap around the business logic in another (non-RCP) simulation library. I can access and use the library fine from any of my plugins, but I don't know where I should put the instance of the Simulation library so that, say, one of the command handlers can make calls to it.
From reading the docs it sounds like I should be storing 'global' information like this in the workbench - but I still don't really understand how to do that.
Help?
First, the business layer (BL) can and should reside in its' own plugin. That will provide decent decoupling between the layers.
Second, you should carefully decide what the interface should be and which classes are exposed. Ideally, you should mostly expose interfaces and data objects.
Finally, decide how the "hand shake" works. E.g., how to obtain the initial interface to the BL. Since it is a Plugin, it could have an Activator which loads it. You could add a method in the activator which returns the BL interface.
If you are looking for something more decoupled, you could create an extension point or deploy the BL as an OSGi service, but that's a bit of an overkill for you need.
If I understand you correctly, I see two ways:
Store the instance in the model plug-in itself, using ‘SimulationFactory.getInstance(String myAppId)‘. The passed String is a constant in you app that is always used, when obtaining the reference.
Define a new class e.g. GlobalAccess in you app that is initilized with an instance of your model and has some getter (whether you use a single instance again or only provide public static methods is a matter of taste).
The seocond way is similar to some classes in eclipse like platfom or platformui, where you can obtain initial references and navigate through the workbench.
edit
i just found a tutorial that might help you:
Passing Data between Plug-ins

Categories