How to use dispatch actions on android - android

I am working on a project hosted on AppEngine, and for the browser client I am using the GWTP platform which implies using GIN (on the client) and GUICE on the server. Also, it uses Models, presenters, actions and events.
I am thinking of also writing an android client for the service but I don't know how to start because I don't know how to connect and exchange data with the webservice. I would have to use Actions and Action Handlers ( http://code.google.com/p/gwt-platform/wiki/GettingStartedDispatch ) which I use for the browser client. From Android I only know how to do it with RPC, and I can't make the connection, I don't know how to map classes from the device to the server.
For example, by using GWTP, if on the browser client I want to do something on the server, I implement an Action class, an ActionResult class ( both on the client ) and an ActionHandler class (on the server). To dispatch an action, I use the DispatchAsync interface and to get the result I use AsyncCallback.
Action (on the client ) - SendRoadNotification.java :
public class SendRoadNotification extends
ActionImpl<SendRoadNotificationResult> {
private RoadNotification roadNot;
#SuppressWarnings("unused")
private SendRoadNotification() {
// For serialization only
}
public SendRoadNotification(RoadNotification roadNot) {
this.roadNot = roadNot;
}
public RoadNotification getRoadNot() {
return roadNot;
}
}
ActionResult (on the client ) -- SendRoadNotfifcationResult.java :
public class SendRoadNotificationResult implements Result {
private RoadNotification roadNot;
#SuppressWarnings("unused")
private SendRoadNotificationResult() {
// For serialization only
}
public SendRoadNotificationResult(RoadNotification roadNot) {
this.roadNot = roadNot;
}
public RoadNotification getRoadNot() {
return roadNot;
}
}
ActionHandler ( on the server ) -- SendRoadNotificationActionHandler.java :
public class SendRoadNotificationActionHandler implements
ActionHandler<SendRoadNotification, SendRoadNotificationResult> {
static DataStore ds = DataStore.getDatastoreService();
#Inject
public SendRoadNotificationActionHandler() {
}
#Override
public SendRoadNotificationResult execute(SendRoadNotification action,
ExecutionContext context) throws ActionException {
//Here I am doing something with that action
}
#Override
public void undo(SendRoadNotification action,
SendRoadNotificationResult result, ExecutionContext context)
throws ActionException {
}
#Override
public Class<SendRoadNotification> getActionType() {
return SendRoadNotification.class;
}
}
The way I use those, is:
SendRoadNotification action = new SendRoadNotification(rn);
dispatchAsync.execute(action, sendRoadNotifCallback);
And the callback:
AsyncCallback<SendRoadNotificationResult> sendRoadNotifCallback = new AsyncCallback<SendRoadNotificationResult>() {
#Override
public void onSuccess(SendRoadNotificationResult result) {
}
#Override
public void onFailure(Throwable caught) {
Window.alert("Something went wrong");
}
};
How can I implement this in android ? Can somebody give me an example or had this problem before ?
I am using AppEngine sdk 1.6.4, GWT sdk 2.4.0, GWTP plugin for Eclipse and GPE plugin for Eclipse.

You might want to look at the source the GAE plugin for ADT generates for 'App Engine Connected Android apps' for inspiration. They are doing something similar by calling GWT endpoints using Android's HttpClient.
https://developers.google.com/eclipse/docs/appengine_connected_android

Related

Implementing platform functionality in a static class - Xamarin.Forms

I am not sure of the terminology for what I'm looking to do, so sorry in advance!
I've found a FilePicker plugin for Xamarin.Forms (https://github.com/Studyxnet/FilePicker-Plugin-for-Xamarin-and-Windows) that implements device-specific functionality for selecting files via the CrossFilePicker class.
The way to use leverage this functionality would be something like
CrossFilePicker.Current.OpenFile("Filename.txt");
The most important part of this for me is that CrossFilePicker.Current is static and can be accessible from anywhere in the shared layer of my Xamarin.Forms app.
I need to implement a class with the same characteristics. I want to leverage device Accessibility functionality (i.e. determining if a screen reader is enabled) and I need to be able to do so with a static class.
My eventual plan is to then wrap this static class so that I can use it for unit tests too.
I don't want to import device libraries into my shared project.
TLDR: I need a static class that implements device-specific functionality.
Any help would be greatly appreciated! Thank you :)
EDIT:
Here are the files I have currently implemented in my project
IAccessibilityService Located in the shared .NET project
namespace Bitspace.Services
{
public interface IAccessibilityService
{
public bool IsScreenReaderEnabled();
public void Announcement(string message);
public void NavigationAnnouncement(string message);
}
}
DeviceAccessibility.cs Located in the shared .NET project
using System;
namespace Bitspace.Services
{
public class DeviceAccessibility
{
private static Lazy<IAccessibilityService> Implementation = new Lazy<IAccessibilityService>(() => CreateAccessibilityService(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
public static IAccessibilityService Current
{
get
{
var curr = Implementation.Value;
if (curr == null)
{
throw new Exception();
}
return curr;
}
}
private static IAccessibilityService CreateAccessibilityService()
{
return new DeviceAccessibilityImplementation();
}
}
}
DeviceAccessibilityImplementation.cs Located in the Android project
using Android.Runtime;
namespace Bitspace.Services
{
[Preserve (AllMembers = true)]
public class DeviceAccessibilityImplementation : IAccessibilityService
{
public bool IsScreenReaderEnabled()
{
return true;
}
public void Announcement(string message)
{
}
public void NavigationAnnouncement(string message)
{
}
}
}
If I try to build the project, I get an error on the return new DeviceAccessibilityImplementation(); line in DeviceAccessibility.cs that says DeviceAccessibility.cs(25, 24): [CS0246] The type or namespace name 'DeviceAccessibilityImplementation' could not be found (are you missing a using directive or an assembly reference?)
However, CTRL Clicking on that line takes me to the DeviceAccessibilityImplementation.cs

MVVMCross Platform specific class that has method which returns instance of same class

Background: I'm trying to integrate Firebase into my MVVMCross app using its platform specific SDK's. The basic part of my setup is working, namely I can use the basic Firebase features to retrieve info from a Firebase database from within my viewmodel. It uses an interface in my PCL that has platform specific implementations in the UI projects.
Problem: I would like to, however, implement a method in my interface (and its implementations) that can deal with the fact that the Java SDK of Firebase has a class called "Firebase" with methods that return the same type ("Firebase"), such as the "Child" method in the Java SDK:
Firebase firebase = new Firebase("URI");
Firebase firebasechild = firebase.Child("test"); // Of same type!
firebasechild.DoStuff();
I'm trying to get similar functionality in my viewmodel:
firebase = Mvx.Resolve<IFirebaseConnection> ();
firebase.FirebaseConnection ("URI");
IFirebaseConnection firebasechild = firebase.Child("test");
firebasechild.DoStuff();
The relevant part of my interface in my PCL is:
public interface IFirebaseConnection
{
void FirebaseConnection (string URI);
IFirebaseConnection Child(string child); // Probably wrong?
void DoStuff();
}
My setup.cs in my Android UI project contains:
Mvx.RegisterType<IFirebaseConnection, FirebaseDroid>();
The platform specific implementation in Android is:
public class FirebaseDroid : IFirebaseConnection
{
protected Firebase firebase;
public void FirebaseConnection (string URI)
{
var mvxTopActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
Firebase.SetAndroidContext (mvxTopActivity.Activity);
firebase = new Firebase (URI);
}
public IFirebaseConnection Child (string child)
{
return firebase.Child (child); // This is obviously wrong
}
public void DoStuff(){// do something}
}
The above is obviously wrong since firebase.Child() is of type "Firebase" and not "IFirebaseConnection", or probably more correctly "FirebaseDroid". Is there a way to deal with methods of the same type as the class it is in when implementing platform specific services?
You could introduce a new private constructor.
public class FirebaseDroid : IFirebaseConnection
{
protected Firebase firebase;
public FirebaseConnection() {}
private FirebaseConnection (Firebase firebase)
{
SetFirebase(firebase);
}
public void FirebaseConnection (string URI)
{
SetFirebase(new Firebase (URI));
}
private void SetFirebase(Firebase firebase)
{
var mvxTopActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
Firebase.SetAndroidContext (mvxTopActivity.Activity);
this.firebase = firebase;
}
public IFirebaseConnection Child (string child)
{
return new FirebaseConnection(firebase.Child (child));
}
public void DoStuff(){// do something}
}

Logic of data transfer on an Android application uses Observer/Observable

Explanation:
I have an Android application which has developed by a colleague of me.
I need to chop off the application to make the logic/programmatic part to reside on a server as a Web Service and to make the remaining part to reside as a client on Android device.
The problem:
As you can see in the below code, Observer/Observable system is used.
1) First, i need to understand, if the Observer/Observable system is used only to establish a communication between Observer(Activity) and Observable.
2) If so, should i put the Manager's programmatic code into the Web Service, and communicate with the Activity using HTTP GET, POST protocols.
3) Or have i misunderstand everything?
public class MainActivity extends Activity implements Observer {
#Override
public void onCreate(Bundle savedInstanceState) {
view = new MainView(this);
ASensor aSensor;
aSensor = new ASensor(MainActivity.this);
aSensor.setListener(new Listener() {
#Override
public void onObjectDiscovered(List<AnObject> params) {
List<AnObject> myParams = new ArrayList<AnObject>();
TheManager.INSTANCE.feed(myParams);
}
});
}
#Override
public void update(Observable observable, Object data) {
if (observable instanceof TheManager) {
List<AnObject> objectList = (List<AnObject>) data;
String retValue = someProcessingMethod(objectList);
view.setRetValue(retValue);
}
}
}
public class TheManager extends Observable implements Serializable {
public static final TheManager INSTANCE = new TheManager();
public void feed(List<AnObject> params) {
List<AnObject> objectList = processParams(params);
notifyObservers(objectList);
}
}
In Google I/O 2010, Virgil Dobjanschi presented the talk Android REST Client Applications Design Pattern, which solves problems of keeping local data consistent to a remote database using SyncAdapters.
If you choose to store your data using a ContentProvider and synchronize it through a SyncAdapter, you may find a detailed description at Google Developers of how to:
Run the Sync Adapter When Server Data Changes
Run the Sync Adapter When Content Provider Data Changes
Run the Sync Adapter After a Network Message
Run the Sync Adapter Periodically
Run the Sync Adapter On Demand

Using TLS only with Retrofit in RoboSpice

I've got a basic setup using Robospice with Retrofit in a shell Android application making REST calls, parsing JSON response into a POJO and that I can then use to render in an Activity. I now want to use TLS only for transport security (not SSL). I've read that Retrofit with OkHttp can be used to achieve this but I don't know where to make the update in my code.
I have a basic interface:
public interface RandomAPI {
#GET("/users")
List<User> getUsers(#Path("owner") String owner, #Path("repo") String repo);
#GET("/users/{userid}")
User getUser(#Path("userid") int userID);
}
I have a Service:
public class RandomService extends RetrofitGsonSpiceService {
private final static String BASE_URL = "http://jsonplaceholder.typicode.com";
#Override
public void onCreate() {
super.onCreate();
addRetrofitInterface(RandomAPI.class);
}
#Override
protected String getServerUrl() {
return BASE_URL;
}
}
and finally a request:
public class RandomRequest extends RetrofitSpiceRequest<User, RandomAPI> {
private int userID;
public RandomRequest(int userID) {
super(User.class, RandomAPI.class);
this.userID = userID;
}
#Override
public User loadDataFromNetwork() throws Exception {
return getService().getUser(userID);
}
}
I'm guessing I need to update the Service but not really sure how. I really like the simplicity of this pattern so would like to keep it if possible. I can drop the OkHttp jars into the application but I don't know how to get at the actual implementation of the service, or how to add my custom one so that all requests use it.
Has any one had experience with this that could share some code snippets or point me to an example?
~~ EDIT ~~
Looking into the API for Robospice, looks like my request can just extend SpiceRequest, then within the loadFromNetwork() method I just do plain Retrofit and OkHTTP stuff. Is that the only way though? Thought there would be a way to set your own RestAdapter implementation in RetrofitSpiceService instead of just using the default.
So to do this is actually quite simple. Create a class which extends RetrofitGsonSpiceService and override the createRestAdapterBuilder() method.
e.g.
#Override
protected Builder createRestAdapterBuilder() {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(SERVICE_URL)
.setRequestInterceptor(requestInterceptor);
return builder;
}

Xamarin Using references for OKHttpNetworkHandler & AFNetworkHandler

I have been trying to implement ModernHttpClient as explained here: http://motzcod.es/post/78863496592/portable-class-libraries-httpclient-so-happy
the main problem is I cannot get it to recognise OkHttpNetworkHandler for Android or AFNetworkHandler for iOS - I don't know the using references for each. For Android I have System.Net.Http, ModernHttpClient and OKHttp. for iOS System.Net.Htp and ModernHttpClient. I have searched but cannot even find sample code that includes the usings
public class HttpClientHelper : IHttpClientHelper
{
private HttpMessageHandler handler;
public HttpMessageHandler MessageHandler
{
get { return handler ?? (handler = new OkHttpNetworkHandler()); }
}
}
public class HttpClientHelper : IHttpClientHelper
{
private HttpMessageHandler handler;
public HttpMessageHandler MessageHandler
{
get { return handler ?? (handler = new AFNetworkHandler()); }
}
}
Okay, seems you don't need any of that
Add the ModernHttpClient as a NuGet package to the PCL and then all you need to do is this
HttpClient client = new HttpClient(new NativeMessageHandler());
Works, and heaps faster than just HttpClient

Categories

Resources