2

I got this app that requires four places on screen to be up-to-date (title, address, date and image source).

So, I thought that maybe I could just makeup four different JSON files that app will read and if I would like to change what app is showing I would just change those JSON files that I'd have on my server.

Maybe something like this (file.json):

{"app": {
  "title": "Screen no. 1",
  "address": "Sesame Street",
  "date": "01-01-2014",
  "image": "http://myserver.com/image.jpg"
}}

and in Android app source of course there would be JSONParser that will get informations from "http://myserver.com/file.json". What do You think - would be that good enough or is there any better (and easier) solution? I tried to get to know Google Endpoints, but it's really cumbersome.

edit1: I got to this point where I use JSONParser custom class from here: How to parse JSON in Android In debug mode I found values from file.json to be downloaded so I have to read it somehow now - it prints "Got the address: " but without value:

Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                Log.i("ABCDE", "Start Thread");
                //JSON
                JSONParser jparser = new JSONParser();
                JSONObject data = jparser.getJSONFromUrl("http://myserv.com/file.json");                
                Log.i("AbCDE", "Afer getting JSON");
                //JSONObject data = new JSONObject(myDataJson); 

                String address = "";

                try {
                    address = data.getString("address");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Log.i("ABCDE", "Got the address: " + address);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

edit2: my XML suddenly stopped working (it validates and makes hierarchy tree well, but not every time):

{
   "party1": {
      "title": "Screen no. 1",
      "address": "Sesame Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   },
   "party2": {
      "title": "Screen no. 2",
      "address": "Oak Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   },
   "party3": {
      "title": "Screen no. 1",
      "address": "Sesame Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   },
   "party4": {
      "title": "Screen no. 1",
      "address": "Sesame Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   }
}

JSON validators says that it's okay or SyntaxError: unexpected token.

This is my JSONParser.java class:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

Community
  • 1
  • 1
jean d'arme
  • 4,033
  • 6
  • 35
  • 70

2 Answers2

2

Yes, obtaining data from your server as a JSON file seems to be the best and most lighweight way of solving this (although you provided little data on what the data should actually mean).

I would suggest using org.json library, as it will allow you to do something like this, cutting time on the parsing:

String myDataJson = ... /* Obtain the data here */
long lastChangeTimestamp = ... /* Obtain the last saved timestamp, probably from SharedPrefs */

JSONObject data = new JSOBObject(myDataJson);

long newTimestamp = data.getLong("ts");
if(newTimestamp > lastChangeTimestamp){ 

String title = data.getString("title");
String address = data.getString("address");
String date = data.getString("date");
String image = data.getString("image");

/* Do somtehing with the newly obtained data and save the new timestamp to SharedPrefs */
}
Kelevandos
  • 7,024
  • 2
  • 29
  • 46
  • "image" should provide address to the image on the server. Additionaly, I want to add comparison method at app startup so if there is no updates then it will not download anything. So "myDataJson" is already red file? – jean d'arme Dec 14 '14 at 11:40
  • Ok, so simply make an URL out of the image String created above and download the image. As for the comparison, make the first value of the json a long caled "timestamp" and update it to the current server time each time the json changes. Then, after download, check if the value changed and only then process the data. I will update the answer to give you the idea. – Kelevandos Dec 14 '14 at 11:42
  • I have updated my question. For now I'm trying to make it basically work and after that - I will get to timestamp. – jean d'arme Dec 14 '14 at 13:08
  • Ok, now it works. I had to remove "app" from JSON file on server. Don't know why I goes like this - though it will find it's way to the value... – jean d'arme Dec 14 '14 at 13:30
  • 1
    Adding "app" makes your json a value of a bigger json. If you wanted it there, it woud need to be something like JSONObject data = new JsonObject("myDataJson").getJSONObject("app"). – Kelevandos Dec 14 '14 at 14:16
  • Somehow this line suddenly crashes with NullPointerException: jobj = data.getJSONObject("party2"); – jean d'arme Dec 14 '14 at 15:38
  • I updated my question since I added JSONParser and json file. I You would be so kind and check this - appreciated :) – jean d'arme Dec 14 '14 at 17:38
  • See my comment above. If you want to have Party objects like this, you will need to getJSONObject("party" + i) from the main JSONObject for each one, where i is the operator of some loop. Only after that you will be able to extract the values. – Kelevandos Dec 14 '14 at 18:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/66855/discussion-between-kelevandos-and-jean-darme). – Kelevandos Dec 14 '14 at 18:13
1

Well, I have a very nice idea, i would suggest using the Gson library.

available from here, with perfect tutorial here

With Gson library you can simply convert JSON To/From java object ! Try to create class with name: app: app.java:

public class app {
public String title;
public String address;
public String date;
public String image;

public app() {
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}


}

Then try to use the Gson library, it will get the json file than using the .fromJSON function it will return an instance of app.java

I hope it will help you, best regards.

Ahmad MOUSSA
  • 2,729
  • 19
  • 31