0

i am fetching a data from sqlite in android which is as follows

  URL                     PHONE
---------------------------------
/test/img1.png          98989898
/test/img1.png          61216121
/test/img2.png          75757575
/test/img2.png          40404040
/test/img3.png          36363636

now i want to create such a map which stores the data as follows

   /test/img1.png          [98989898 , 61216121 ]
   /test/img2.png          [75757575 , 40404040 ]
   /test/img3.png          [36363636]

so that i can pass the whole map to the function which function eventually in background pick up the image url and send the data to the arrays listed to the phone number. so how can i transform the data that i have fetched into the key to string array style ?

1 Answer 1

4

I'd create a Map<String, List<String>> (aka "multi-map"). You don't have to know how many phone numbers for a given URL before you start if you use List<String>. That's not so if you choose the array route.

Map<String, List<String>> results = new HashMap<String, List<String>>();
while (rs.next()) {
    String url = rs.getString(1);
    String phone = rs.getString(2);
    List<String> phones = (results.contains(url) ? results.get(url) : new ArrayList<String>());
    phones.add(phone);
    results.put(url, phones);
}

Google Collections has a multi-map that you can use out of the box, but I think you'll agree that this is sufficient.

If you want to store more items (e.g. name) you should start thinking about an object that encapsulates all of them together into one coherent thing. Java's an object-oriented language. You sound like you're guilty of thinking at too low a level. Strings, primitives, and data structures are building blocks for objects. Perhaps you need a Person here:

package model;

public class Person {
    private String name;
    private Map<String, List<String>> contacts;

    // need constructors and other methods.  This one is key
    public void addPhone(String url, String phone) {
        List<String> phones = (this.contacts.contains(url) ? this.contacts.get(url) : new ArrayList<String>());
        phones.add(phone);
        this.contacts.put(url, phones);
    }
}

I'll leave the rest for you.

If you go this way, you'll need to map a result set into a Person. But you should see the idea from the code I've posted.

Sign up to request clarification or add additional context in comments.

1 Comment

what if i want to store name field too ? name url [ phone1 , phone 2] ?

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.