Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send arraylist from servlet to Android application

How can I send a array list from a servlet to an Android application?

like image 622
user1068895_CHU Avatar asked Nov 28 '11 07:11

user1068895_CHU


2 Answers

To the point, you need to convert it to a String in some standard format which can then be parsed and built using the existing libraries. For example, JSON, XML or CSV, all which are standardized and exchangeable string formats for which a lot of parsing/building libraries exist in a lot of programming languages.

Android has a builtin JSON parser in the org.json package. It has even a builtin XML parser in the org.xml.sax package. I'm not sure if there's a builtin CSV library, but there appears to be none. Java EE has in flavor of JAXB a great builtin XML parser, but it doesn't have a builtin JSON parser. Only the JAX-RS implementations (Jersey, RESTeasy, etc) provide a JSON parser. If you can change your servlet to be a JAX-RS webservice instead, you'll have the benefit of being able to return both XML and JSON with very minimal effort. See also Servlet vs RESTful.

Which format to choose depends on the sole functional requirements. For example, is the servlet supposed to be reused for other services? What are the target clients? Etcetera.

In any way, the JSON format is usually more terse and lately more popular than XML, so I'll just give a kickoff example which transfers the data in the JSON format and I'll assume that you really want to do it with a plain vanilla servlet instead of JAX-RS. For this example, you only need to download and drop a JSON library such as Gson in /WEB-INF/lib in order to convert Java objects to JSON in the servlet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

This will build and return the List in the following JSON format:

["item1","item2","item3"]

This is in turn parseable by org.json API in Android as follows:

String jsonString = getServletResponseAsStringSomehow(); // HttpClient?
JSONArray jsonArray = new JSONArray(jsonString);
List<String> list = new ArrayList<String>();

for (int i = 0; i < jsonArray.length(); i++) {
    list.add(jsonArray.getString(i));
}

// Now you can use `list`.
like image 174
BalusC Avatar answered Sep 28 '22 06:09

BalusC


If its a pull based model you can send the HTTP GET request to the servlet endpoint from your android app, and the HTTP Response could be a JSON object, created from an array list.

like image 34
Rajdeep Dua Avatar answered Sep 28 '22 07:09

Rajdeep Dua