0

I currently have a JSON file that I'm calling from a server that looks like this:

{"owner":
    [{
        "username":"test-user",
        "email":"test-user@localhost",
        "id":1,"phone_number":"5555555555",
        "images":null,
        "pets":
            [{
                "id":4,
                "species":"Canine",
                "breed":"Labrador Retriever",
                "dob":{"date":"2015-03-19 11:03:24.000000","timezone_type":3,"timezone":"America\/Toronto"},
                "colour":"Gold",
                "pure_bred":"true"
            },
            {
                "id":3,
                "species":"Feline",
                "breed":"Persian",
                "dob":{"date":"2015-02-19 11:09:57.000000","timezone_type":3,"timezone":"America\/Toronto"},
                "colour":"Grey",
                "pure_bred":"false"
            }]
    }]
}

My ArrayAdapter using an ArrayList displays my Owner entity well. It's exactly how I want it to look, however I'm having trouble properly extracting my Pets data. Because the pets have a ManyToOne relationship with the Owner entity, I will sometimes get more than one pet. Unfortunately, it seems that I can only display one pet with my ArrayAdapter for my Owner. Is there a method to retrieve all of my Pets entities and display them in individual LinearLayouts to avoid scrolling issues?

I think I'm on the right track, but I simply don't know how to proceed.

Thanks.

ASyncTask

[...]

protected List<OwnerModel> doInBackground(String... params) {
    List<OwnerModel> result = new ArrayList<OwnerModel>();

    try {
        URL u = new URL(params[0]);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("GET");

        conn.connect();
        InputStream is = conn.getInputStream();

        // Read the stream
        byte[] b = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while (is.read(b) != -1)
            baos.write(b);

        String JSONResp = new String(baos.toByteArray());

        JSONObject jObj = new JSONObject(JSONResp);
        JSONArray arr = jObj.getJSONArray(ModelConstants.OWNER);

        for (int i = 0; i < arr.length(); i++) {
            result.add(convertHeader(arr.getJSONObject(i)));
        }
        return result;
    } catch (Throwable t) {
        t.printStackTrace();
    }

    return null;
}

private OwnerModel convertHeader(JSONObject obj) throws JSONException {
    // owner variables
    String id;
    String username;
    String email;
    String image;

    Owner om = new Owner();

    JSONArray petsArray = obj.getJSONArray(ModelConstants.PETS);
    if (!petsArray.getJSONObject(0).isNull("id")) {

        int modelInt = petsArray.length();

        // pet variables
        String pet_id;
        String pet_species;
        String pet_breed;
        String pet_pure_bred;
        String pet_colour;



        for (int i=0; i < modelInt; i++) {

            JSONObject petsJSONObj = petsArray.getJSONObject(i);
            pet_id = petsJSONObj.getString(ModelConstants.PET_ID);
            pet_species = petsJSONObj.getString(ModelConstants.PET_MANUFACTURER);
            pet_breed = petsJSONObj.getString(ModelConstants.PET_BREED);
            pet_pure_bred = petsJSONObj.getString(ModelConstants.PURE_BRED);
            pet_colour = petsJSONObj.getString(ModelConstants.PET_COLOUR);

            om.setPet_id(pet_id);
            om.setPet_species(pet_species);
            om.setPet_breed(pet_breed);
            om.setPet_model_year(pet_model_year);
            om.setPet_pure_bred(pet_pure_bred);
            om.setPet_colour(pet_colour);

        }
    }

    return om;
}

@Override
    protected void onPostExecute(List<OwnerModel> result) {
        if (result != null) {
            super.onPostExecute(result);
            ownerAdapter.setOwnerList(result);
            ownerAdapter.notifyDataSetChanged();

            petsAdapter.setOwnerList(result);
            petsAdapter.notifyDataSetChanged();
        }
    }

Activity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_profile);

    ownerAdapter = new OwnerAdapter(this, 0, new ArrayList<OwnerModel>());
    petsAdapter = new OwnerAdapter(this, 1, new ArrayList<OwnerModel>());
    header = (ListView) findViewById(R.id.myProfile_header);
    header.setAdapter(ownerAdapter);

    pets = (ListView) findViewById(R.id.listview_pets);
    pets.setAdapter(petsAdapter);

    (new FetchOwnerTask()).execute(HOST + "access_token=" + token.getAccessToken());
}
5
  • 1
    We have no idea without seeing some code. Commented Mar 19, 2015 at 23:24
  • My edits don't seems to be going through... Commented Mar 19, 2015 at 23:46
  • Is this a master-detail thing where you have a list of owners, and clicking on an owner displays a list of that owner's pets? Commented Mar 20, 2015 at 0:37
  • @nasch It's more like an ExpandableListView, but not quite. Though, now that you mention it, I may be able to come up with a solution that is similar to that, just without a click listener. Commented Mar 20, 2015 at 0:50
  • 1
    Wow. That code has so many fails it's not even funny. From reading input byte at a time to constructing String without encoding, to swallowing the exception. Good JSON libraries (Jackson, GSON) would simply take that URL and allow reading content into matching POJO, Map, or a tree representation (JsonNode or such). Commented Mar 20, 2015 at 19:03

1 Answer 1

1
try {
        Object object = obj.opt(ModelConstants.PETS);
        if (object instanceof JSONArray) {
            ArrayList<Pet> petList = new ArrayList<Pet>();
            JSONArray msgList = (JSONArray) object;
            for (int i = 0; i < msgList.length(); i++) {
                Pet pet = new Pet();
                JSONObject petsJSONObj  = msgList.getJSONObject(i);
                String pet_id = petsJSONObj.getString(ModelConstants.PET_ID);
                pet.setPet_id(pet_id);
                String pet_species = petsJSONObj
                        .getString(ModelConstants.PET_MANUFACTURER);
                pet.setPet_species(pet_species);
                ......
                petList.add(pet);
            }
        }
        om.setPetList(petList);
    } catch (Exception e) {
        e.printStackTrace();
    }
Sign up to request clarification or add additional context in comments.

Comments

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.