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;

}

}

2 Answers 2

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 */
}
Sign up to request clarification or add additional context in comments.

9 Comments

"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?
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.
I have updated my question. For now I'm trying to make it basically work and after that - I will get to timestamp.
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...
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").
|
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.

1 Comment

Thanks! I will check that once I get the basic JSON - just want to know what am I doing in first place :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.