Adam February 2016

How separate data obtained from server by unique separator?

I want to ask if there's some way to split data obtained from server by some unique separator.

Here is an example:

I use AsyncTask to send data to server and then I use echo command for sending those back to my application and in onPostExecute I split these data to needed result.

So let's say, that I want to get from server data for Name and Surname, so echo command on server will look like this: echo $name."&".$surname;

And then in onPostExecute I will split this data by "&" separator, but problem occurs when user writes to name or surname my separator "&" which I am using for split.

How can I avoid this issue?

Answers


Andreas Wenger February 2016

You need to escape the character you are using to separate the different entries in the content you are transmitting [1]. For example: My\&FirstName&MySecondName (In this case \ is used as escape character)

However, you don't need to reinvent all this stuff. There are several formats that you could use to transmit your data:

  • json
  • xml
  • csv

[1] https://en.wikipedia.org/wiki/Escape_character


Helix February 2016

Look into using JSON. It's a life saver for sending data. Android has native JSON support using a JSONObject.

Documentation

It essentially provides a formatter and parser for information placed within the object that are then accessible via keywords.

To write a json:

public String writeJSON() {
  JSONObject object = new JSONObject();
  try {
    object.put("name", "John");
    object.put("surname", "Doe");
    return object.toString();
  } catch (JSONException e) {
    e.printStackTrace();
    return null;
  }
} 

This will return a string that looks like:

{"name":"John","surname":"Doe"}

To read:

public void readJSON(String jsonString){
    try {
        JSONObject object = new JSONObject(jsonString);
        String name = object.getString("name");
        String surname = object.getString("surname");
    } catch (JSONException e){
        e.printStackTrace();
    }
}

Post Status

Asked in February 2016
Viewed 1,117 times
Voted 8
Answered 2 times

Search




Leave an answer