kristyna
kristyna

Reputation: 2117

Fill list with json data and get the values from it

While logging into my android application I'm downloading json, which has 4 objects. Each of them is stored to ArrayList.

For example, in database I have table payment_methods. Data from this table are one of four objects in json.

Here is how I store it.

public class PaymentMethods implements Serializable {

private static final long serialVersionUID = 6639477841337769107L;
ArrayList<PaymentMethod> payment_methods = new ArrayList<PaymentMethod>();

public ArrayList<PaymentMethod> getList(){
    return payment_methods;
}


public PaymentMethods(JSONObject json) throws ApiException{
    parseJson(json);
}

public void parseJson(JSONObject jObject) throws ApiException{
    try {
        @SuppressWarnings("unchecked")
        Iterator<String> iter = jObject.keys();
        while(iter.hasNext()) {
            PaymentMethod payment_method = new PaymentMethod();
            payment_method.payment_methods_id = iter.next();
            payment_method.payment_methods_name = jObject.getString(iter.next());
            payment_methods.add(payment_method);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}   



}

Works great. In file/class named PaymentMethod (just without the "s" at the end) are getters and setters.

The question: How can I access data from PaymentMethods anywhere from the app's code?

Upvotes: 1

Views: 557

Answers (2)

Mike Clark
Mike Clark

Reputation: 1870

Try using shared preferences, your data can be stored locally so this would avoid you to make an HTTP connection every-time and this data can be accessed anywhere throughout the App.

Upvotes: 1

T.Gounelle
T.Gounelle

Reputation: 6033

Make PaymentMethods a singleton and access it anywhere with

// in some other class
List<PaymentMethod> pml = PaymentMethods.getInstance().getList();

Since a singleton is global and needs to be initialised, if you need a thread safe implementation, look here for the different ways to do it right.

Upvotes: 1

Related Questions