Android App Development and Web Server Interactions - android

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.

Related

How does android retrieve data from a website?

I'm new to android, I'm trying to build an android app that is a front for a web portal. For example, Airbnb. They have a website, but they also have an android app that, using it's own layout, will show listings from their website.
There are many websites that teach how to or even directly convert your website to android apps. However, this will result in an app that loads too slowly and is unresponsive due to CPU usage.
Could anyone share any tutorial/guide to learn how to do this myself?
Million thanks.
To actually load data from a web server you're gonna need and API which usually delivers the proper date using JSON or XML format so that you can properly parse and display that data. Building this API is in it self a complete course on its own.
But connecting to and requesting data from the API is usually done using some networking libraries. These are some of the better know libraries for this purpose.
OkHttp: A complete library with a set of tools for handling network connections and HTTP requests.
RetroFit:Type-safe HTTP client for Android and Java by Square, Inc. which is built on top of OkHttp.
Async-Http-Client:
The Async Http Client library's purpose is to allow Java applications
to easily execute HTTP requests and asynchronously process the HTTP
responses. The library also supports the WebSocket Protocol. The Async
HTTP Client library is simple to use.
There tons of other good libraries.
its called webservices
Through android you get data in form of json from a web server and then return in custom view as you want.
Follow this link hope it will help
Step by Step Method to Access Webservice from Android
you would have to write an API/Web service or use if already exits to fetch data from web server. Basically the concept is that, the website itself must be pulling data from some database, so write an API which would fetch the data from same API and return JSON data and consume the API from your android app.
If you know PHP refere to this for the help :http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
You can write WebService, in programming it generally refers to a web page(ex. Airbnb), that can be called from your android application which can pass in data to it, or receive data from it.
WebService is basically like a 'method' or 'function' in a normal programming language; except you're calling it over the internet.
The first thing is you have to create a Web Service. The Web Service will be your "bridge" to consume the data from other Website like airbnb or others and return the data to your android through json format for example.
You can create a Web Service using many languages like C#, Java, PHP, etc. I would like to recommend you to use the language that you know the most.
You can try to google this
Cheers

Networking app architecture

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
}

Using REST to Send and Receive Complex Data

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

Android web app

What are the best ways to connect site and show it's data on an android application ? Also does I have to create anything on server where the site is for using JSON ? I am new to programming web android application's, though I searched a lot I didn't find anything which would explain me straight to the point.
You're on the solid ground starting out using JSON as the interchange between the two.
Alot of popular mobile apps like Twitter and Foursquare have restful APIs set up to interact with their mobile clients by exchanging HTTP requests that contain data formatted as JSON. Most of the communication between the two can be accomplished with HTTP requests using the standard GET and POST methods.
A good place to start would be setting up some server endpoints that output this data and then setting up your android app to request and parse this data just like a browser would. You just need to set the appropriate mimetypes on your server end (application/json).
Most modern server-side languages have implemented modules/functions that can take their native data structures and approximate them in serialized JSON (PHP's json_encode(), python's json.dumps() etc) These can be used to output data from within the app or database to your mobile client where it can be interpreted and used in the Java environment there.
To pass back JSON you need to set the mime type (http://stackoverflow.com/questions/477816/the-right-json-content-type), which is application/json.
If you are passing back JSON or XML then the client just needs to make the appropriate http call, most likely GET, perhaps POST, to actually retrieve the information.
You can use something like this as a starting point:
http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

Faking HTTP request responses for testing in Android

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.

Categories

Resources