4

I am trying to make an Android class that creates a List of other apps, for later display, until now I have the following code for creating the List (taken from a google example):

public final class AppList {

public static List<App> list;

public static List<App> setupApp() {
    list.add(buildAppInfo(
            "Browsers",
            "chrome",
            "description",
            "Google Inc.",
            "com.android.chrome",
            "http://...",
            "http://..."
    ));
    list.add(buildAppInfo(
            "Browsers",
            "Firefox",
            "description",
            "Mozilla",
            "com.mozilla.firefox",
            "http://...",
            "http://..."
    ));
    [An so on...]

    return list;
}

private static App buildAppInfo(String category,
                                    String title,
                                    String description,
                                    String developer,
                                    String packageName,
                                    String iconImageUrl,
                                    String bgImageUrl) {
    App app = new App();
    app.setId(App.getCount());
    App.incCount();
    app.setTitle(title);
    app.setDescription(description);
    app.setDeveloper(developer);
    app.setCategory(category);
    app.setIconImageUrl(iconImageUrl);
    app.setBackgroundImageUrl(bgImageUrl);
    app.setPackageName(packageName);
    return app;
    }
}
//From here everything is handled in other activity

I will like instead to load the details dynamically from a web server that I can setup to feed either a JSONArray or an XML and then put that data on the list. For what I was reading I could use Volley, but I am not very experienced in Volley or Java in general (I am just learning in the road) so I don't have to much idea on how to proceed.

From the google developers site I found an example. I was thinking on add something like this:

public final class AppList {

public static List<App> list;

public static List<App> setupApp() {
    /*Json Request*/
    String url = "https://json_url/";
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    list.add(response);//ADD ITEMS TO LIST HERE
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    return list;
}

private static App buildAppInfo(String category,
                                    String title,
                                    String description,
                                    String developer,
                                    String packageName,
                                    String iconImageUrl,
                                    String bgImageUrl) {
    App app = new App();
    app.setId(App.getCount());
    App.incCount();
    app.setTitle(title);
    app.setDescription(description);
    app.setDeveloper(developer);
    app.setCategory(category);
    app.setIconImageUrl(iconImageUrl);
    app.setBackgroundImageUrl(bgImageUrl);
    app.setPackageName(packageName);
    return app;
    }
}

The data received from the server feed should be something like:

buildAppInfo(
            "Browsers",
            "Firefox",
            "description",
            "Mozilla",
            "com.mozilla.firefox",
            "http://...",
            "http://..."
    )
buildAppInfo(
            "Browsers",
            "Firefox",
            "description",
            "Mozilla",
            "com.mozilla.firefox",
            "http://...",
            "http://..."
    )
[...]
//BUT IN JSON FORMAT

My entire approach obviously doesn't work. Can someone please help me to achieve what I need? Thank you.

Valerie Castle
  • 113
  • 1
  • 11
  • You have to convert that JsonObject into array format, like ContentValues, hashMap and then give that array to your listview, directly JsonObject will not work. – Pratik Dasa Nov 26 '16 at 11:28

1 Answers1

2

The simplest set up for what you want to do requires:

A way to read content from a URL, parsing the received JSON array. For example, into a JSONArray or JSONObject (which you can get on mvnrepository):

public static JSONArray parseJsonFromUrl(String uri) throws IOException, JSONException {
    JSONArray array = null;
    try (Scanner sn = new Scanner(new URL(uri).openStream(), "UTF-8")){
      array = new JSONArray(sn.useDelimiter("\\A").next());
    }
    return array;
}

Mapping the received information to a List of specific App objects, e.g.:

public static List<App> getAppList(JSONArray array){
    List<App> appList = new ArrayList<>();
    for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            appList.add(buildAppInfo(object.getString("category"), object.getString("title"), object.getString("description"), object.getString("developer"), object.getString("packageName"), object.getString("iconImageUrl"), object.getString("bgImageUrl")));
    }
    return appList;
}

The approach for consuming XML is similar, using an XML parser instead (Check out How to read XML response from a URL in java? for details).

You can use more advanced tools such as Jackson Mapper or Spring RestTemplate for consuming the RESTful service, but I suggest starting with this simple approach until you get more familiar with the Java ecosystem.

[UPDATE]

I've made a quick demo using the code of this answer so you can tinker with it. You can also use it as a boilerplate to build the rest service you need using Spring Boot. (Check out https://elcodedocle-jsontest.herokuapp.com/apps for a live deployment of the latest passed travisCI build of the service)

[ANOTHER_UPDATE]

In case you are still clueless, here is a full android app consuming a list (json array of "app" json objects) served via RESTful service, using the code written on this answer from an android app (Yes, you can import this one as a fully functional android studio project): https://github.com/elcodedocle/android-resttest

Remember this is a basic example using the simplest way I can come up with for a beginner. If you keep coding for a while around the Java ecosystem you will discover more advanced tools that you might find more suitable for your project, once you have enough experience to be able to wrap your head around their correct usage.

Community
  • 1
  • 1
NotGaeL
  • 8,344
  • 5
  • 40
  • 70
  • Your example GitHub code will be great if could import that in Android Studio. – Valerie Castle Nov 27 '16 at 17:25
  • you can import it as a maven java project in IntelliJ's standard java IDE. I don't know if their Android Studio supports anything other than android projects (try to look for something like import... maven project from git repo). If not, there is no point on making the back end an android app, but you can take the resttest class as is an use it in your project (the only required dependecy is org.json which you can add to your gradle build as specified on the mvnrepository link – NotGaeL Nov 28 '16 at 00:33
  • (jackson and slf4j logger are also included an used on the main method to output the processed list nicely, but you can remove those lines and do what you actually want to do with the list instead) – NotGaeL Nov 28 '16 at 00:35
  • and you can still build and run this project as a test backend server for your android app from your command line using maven (no need for a fancy IDE, just edit the controller class if you want it to output something different, then repackage and relaunch the service using maven cli, leaving it ready to be consumed by your android studio project app) – NotGaeL Nov 28 '16 at 00:46
  • Check out https://github.com/elcodedocle/android-resttest if you want to see what I mean. – NotGaeL Dec 02 '16 at 08:59
  • Thank you very much, this will help me a lot :) – Valerie Castle Dec 02 '16 at 12:33