I'm building an android app similar to a facebook app, aimed to display various information stored in a database.
I'm using on the server-side a REST API, which returns responses based on various POST requests, with a facebook token authentification.
And on the client-side, I'm using the volley library to deal with network requests. I've tried numerous possibities but I'm searching for the most elegant way of communicating with the server, and since this is a trivial case, I thought you could maybe help me with this one...
Since I'm always checking fb tokens, and making similar POST requests, I considered adding a Connexion objet, which creates a volley request when prompted with an execute(POST parameters...); method, and calls a callback method when the response has arrived.
But I'm struggling to decide whether I should create a SessionManager object (Singleton or not ?) which can process ALL the data from session related responses (like check login, login...) based maybe on codes (for example Error 5xx for every type of response), and DO the intents.
Or I should process these responses in every activity, and do the intents there. Knowing they can maybe repetitive.
In short, I'm looking for a best practice to apply when the app has to process common responses, and not so uncommon responses for example.
Keep all the logic in the activities ? Create objects ?
Don't hesitate to post your opinion on the subject !
Thank you very much.
EDIT : Ended up using a Connexion object to process all the requests (with volley). As for the Intents, I kept all that logic in the activities and haven't used another controller. The result was not ugly. Mainly because I used a secondary route which does the authentification, so the server ALWAYS responds with a big error if you're an evil hacker.
First of all I am not working with Volley but with the Apache HttpClient, this should not matter for your question though.
Having the code which handles the Post Requests in your Activities is a bad solution. See:
Single Responsibility Principle
Your idea with creating a SessionManager is really good though. You can handle all the stuff in the SessionManager and not bother with it in your Activities. Additionally you should add classes for different purposes than managing the session. If you get all friends from a specific user you should create a FriendsController or FriendsManager.
Processing the answers can be done in a single class too. I assume that you receive JSON from your API as response. Create one class that takes the response and returns a JSONObject.
Although it is far from perfect feel free to take a look at my app. I am currently learning Android / Java so it might not be as perfect as one might expect. The classes to handle POSTs are called YYYController and not Manager. But this is just a naming convention I use:
My Android Project
Your calls can return an enum in which you store the different Callback types:
class Enum Callbacks {
SUCCESS,
CREATED,
UNPROCESSABLE_ENTITY
}
In your application you can use them like this:
Callbacks response = SessionManager.login();
if (response == Callbacks.SUCCESS) {
//your login logic here
}
Related
I am working on an android app with some networking aspects. There are places in the app that, when a button is pressed, a call is made to a server with a response full of data coming back. My question is regarding creating a robust flow where i have my network calls separated in their own class and all i do is instantiate a networking object such as new MyNetworkHelper(accessClientServer) and give it the name of a client server. This object would then instantiate the appropriate object (ClientServer or StudentServer or TeacherSever etc) to do with accessing that server and doing any database saving and returning a response to the MyNetworkHelper object which would return to the button that was pressed.
Is this the best way to do this kind of task?
What you propose is not unreasonable but could be more standardized using standard patterns such as your helper being a Singleton (and your additional servers as well if they are intended to be used in such a fashion). I would recommend you pick up a beginner book in Design Patterns and Architecture.
Here is one design/ best practices question..
I'm new to android development, and basically new to web/mobile solutions.
So, my question is - what are best practices when organizing structure of android application that get data from the remote server?
Should request to server go into one class that does communication with server (get and post requests), or should I look at my requests as data source, meaning that every data class manages it for itself?
or should I have more levels of abstraction - one level for acquiring data, other for model that uses some interfaces without knowing from what source data come from?
I'm curious how experienced android developers approach to these design issues...
Virgil Dobjanschi presentation is a good resource as pointed earlier, which basically tells you to run your requests from a background service so the activity does not get destroyed and to store your data in the database as early as possible.
For more technical details, the way I am doing it is to divide the app into three components:
1- Library to encapsulate the handling of the HTTP request and response (with ApacheHTTP), which can handle simple request/response and advanced features that might involve cookies (can be necessary for login) and modifying the HTTP header.
2- Marshal/Unmarsha layer, where I parse the server data (e.g. XML or JSON) and convert it to objects (i.e. models) that the rest of my app will deal with.
3- Persistence layer.
As per Dobjanschi's presentation, I usually make data requests run in a service not in a thread worker inside the activity.
Use one of the 3 models presented at this Google I/O talk. It provides you suggestions that will help you out on the whole process of definition of your app architecture. It'll also prevent you from making common mistakes beginners use to make:
http://www.youtube.com/watch?v=xHXn3Kg2IQE
This post will also help you out:
Need sample Android REST Client project which implements Virgil Dobjanschi REST implementation pattern
My client is an Android app and my service is an asp.net web api. I’m the only one using my service. I am trying to duplicate, in the Android-REST world what I am already doing in the Microsoft Windows Phone 7/ WCF SOAP world. I have numerous methods that both receive complex objects and return complex objects.
The WCF-SOAP world is simple. You can pass any complex arguments you want and return any complex results you want. Logically, it’s just a Remote Procedure Call.
But when I post questions about doing the same thing in REST, I’m told I should limit my services into GET, PUT, POST, and DELETE only. And that I should only do what is “proper” according to RFC2616. Some speak of this in almost a religious manner.
Forgeting about the religion, what’s wrong with using a GET for everything? Or what’s wrong with using a POST for everything? What I do does not fall into the simplistic RFC2616 categories. For instance I’m passing a thousand legs of a trip taken in a car and I’m getting back another version of that trip with erratic GPS errors smoothed out. Or, I’m sending a conversation in english and getting that conversation back in German.
In the android client I have the objects I want to send over HTTP already serialized into json strings by using Google-GSON. So my questions are…
How can I send these json strings to my REST Service as arguments in either GET or POST?
Is it possible and feasible to use just all GETs (or all POSTs) for all of my calls to my REST Service and how do I do that?
I have a more pragmatic question about this posted at sending a json string in a http url as I can’t find any examples anywhere of sending json strings over http GET or POST.
Thanks, Gary
Using the good HTTP verb is very usefull to simply know what to do when you request failed (for example) or just to do some specific stuff. If you sent a POST request, it's implicitly suppose that you have to parse your resource in order to obtain a stream which be sent via the request's body. In other hand, when you are retrieving data via GET, it's suppose that the request is gonna be sent back to you as a stream that you will mapped to your model, pojo, or anything else.
I can suggest you to use library such as RESTDroid. You can send POJO and receive POJO. It's a "resource oriented" library, so you can know at any moment if a particular local resource is remotely syncronized. Data persistence between local and remote is automatically handles.
RESTDroid is alpha released. You can have a look to RoboSpice. It's a powerful library to manage REST call but it's up to you to manage the persistency between local and remote resources.
1) The WCF-SOAP world is simple. You can pass any complex arguments you want and return any complex results you want. Logically, it’s just a Remote Procedure Call.
- IN REST:"You can pass any complex arguments you want and return any complex results you want too.
2a) Forgeting about the religion, what’s wrong with using a GET for everything?
In SOAP services WCF/or classical you are wrapping all requests into http POST so using single verb would end up to SOAP or - don't even think about it - your own communication protocol:-D
2b) You can technically compose GET request with non empty body - most of the servers ignore it by default though and it would be technically problematic to read it..
the other part of the question is answered by Pcriulan above
I am just learning about Android Development so excuse me if this is a bit off in nature.
I am wanting to make an app that interacts with a Database from my website, in a sense the two things will be one feeding the other. So with that. I am trying to figure out whats the best way to interact with my server. I don't want an app thats an app in a browser like environment I want to dev a full app that works independently of the site only sharing the DB and like features. So what would be my best approach?
Is building the app so it can post/get to php files on the server interacting basically through JSON/XML my best and or safest bet or is there a better approach that connects the App to the servers Database that doesn't require me to open the database to any ip that makes a request.
Just looking for opinions and suggestions here. I figure everyone who's going to see this is familiar with Android development and best practices where as I could and have surfed blogs and all else but the opinion seems to be 50/50 as to which is best.
I'm sure there are libraries out there for Android that help you with HTTP Get and Post, however, if you really want to understand what is going there are just a couple of classes you have to understand in order to make the necessary classes yourself.
First, get to know HttpClient, HTTPGet, HTTPPost, and HTTPResponse. Some of the later versions of Android have some nice other classes as well, but those four is pretty much all you need to get started.
You need to do something like this:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.myurl.com/api_name");
HttpResponse response = client.execute(request);
If you debug this (with a real URL of course), you'll notice that your app kind of freezes during client.execute(). This is the point at which the request has actually fired and the app is waiting for a response. Once you actually get the response, it isn't very difficult to get the data out of it.
Once you understand this, you'll want to get to know AsyncTask, which is endlessly useful for performing background tasks. You can find the documentation here: http://developer.android.com/reference/android/os/AsyncTask.html There is a great example of how to use this right at the top.
Using these two concepts together you can perform asynchronous HTTP requests. Basically, put your actual HTTP execute code in doInBackground of your AsyncTask. At the end of the doInBackground return your response, and then do what you want with your data in the AsyncTask's onPostExecute.
We've found that providing a proper RESTful web API that hits the database on the backend in whatever language you choose (be it PHP, RoR, whatever) provides a useful interface for any number of uses (your own website, mobile apps, etc).
Then it's a matter of your Android app interacting with the RESTful API, which is simply HTTP requests. Those can be encapsulated in helper classes to make them straightforward as well.
Based on my experience, the best framework for doing RESTFul things with Android is: Spring Android
From a client perspective, it provides all the tools needed to access secure RESTFul services. Since it is Spring, it provides nice abstractions over most of the boiler plate http code. As an example, it provides a clean way to perform a GET that returns json, and then serialize that to a POJO.
As an example:
RestTemplate restTemplate = new RestTemplate();
// Add Jackson JSON Message Converter to Template
restTemplate.setMessageConverters(
new ArrayList<HttpMessageConverter<?>>() {
{
add(new MappingJacksonHttpMessageConverter());
}
}
);
// Simple Conversion - pojo is now populated
MyPojo pojo = restTemplate.getForObject(url, MyPojo.class);
The approach you mention in the question: PHP on the server and JSON for requests/responses, does work. But getting it perfect can be tricky.
I found it helpful to have small request/reponse classes for each call on the Android side, like SaveNoteToServerRequest, SaveNoteToServerResponse classes which are just plain java objects with whatever fields are needed for the request/response. Then you can use a library like GSON to convert the request object to JSON and convert the http response from JSON to the response object.
On the PHP side you can create a small class for the response object, then json_encode at the end.
That way you're not directly manipulating JSON objects, just using your own plain java objects or php classes most of the time.
Hope that helps.
I'm writing an Android app which sometimes needs to request data through HTTP from a REST API. I'm using the Apache DefaultHttpClient for performing requests. Is there a way to write tests for this app and "replace" DefaultHttpClient's response when running the tests so that test results are always consistent?
As an example of the things I'd like to test, one of the web services I'm accessing takes a string and performs a text search, returning a paged list of objects. I need to test the cases where the list is empty, the list fits in the first page, or the list is larger than a page and the app needs to make several requests to get the complete list.
I'm not the developer of this web API nor can modify its responses, so I can't change what it returns. For the above example, if I want to test the case where the list returned is empty, I could just search for a string which I'm sure won't return any results, but the other two cases are harder because what the service can return is always changing.
I think ideally I would have a way to get a modified DefaultHttpClient when running tests, that returns a hardcoded result for requests to a given URL instead of actually doing the network request. This way I would always get consistent results independently of the real web service's response.
I'm currently using Robotium for testing but I'm open to using other tools too.
Yes, you can definitely "fake" responses when using the HttpClient framework. It's quite convoluted, and I will have to leave most of the details up to you, but I will give you a quick overview:
Implement ClientHttpRequestFactory, mainly so you can override the createRequest() method so you can...
Return your custom implementation of ClientHttpRequest, in which you can override the execute() method so you can ...
Return your custom implementation of ClientHttpResponse in which you will finally be able to return your fake response data, e.g. getBody() can return the content of a file, you can hardcode the headers in getHeaders(), etc.
The rest is figuring out how to best tie all these shenanigans to your service layer.
You might give Charles a try for something like this. Sorta a non-code solution.
http://www.charlesproxy.com/
I use the Charles' reverse proxies and the map local tool for things like this.
What you do is point your request at your local box on the reverse proxy port. Charles in turn can be configured to provide a static hard-coded flat file but to your app it looks like a 100% genuine web service response.
There are lots of other cool things you can do with Charles - watch traffic from your android app to and from your server and breakpoints (which allows you to tweak requests and responses before they are sent and received). Definitely worth checking out.
Another option is to use Dependency Injection so that you can change the HttpClient when running the tests. Check out Guice if you are interested.
I'm guessing you are interested in writing functional tests using the standard Android Junit testing framework. So you could just implement the parts of the API you are using on your own webserver and point at that server when running your tests.
If you'd prefer your tests to be self-contained, you could implement an Http server that runs on the device. Examples of using the Http server available in the Android class library are here and here.