简体   繁体   中英

Get Android resource value from any class

I'm just starting with Android programming and I'm still a little confused with some concepts. I'll tell you what I'm trying to do using a simplified example:

I'm retrieving a list of cars from a remote server (PHP/MySQL/JSON) and showing them on a ListView.

This is the server response JSON structure:

{
    error: null,
    data: {
        cars: [
            {name: "Lamborghini Diablo", color_id: 1},
            {name: "McLaren F1", color_id: 2},
            {name: "Ferrari F355", color_id: 1}
        ]
    }
}

Then I wrote the Car class:

public class Car {

    public String name;
    public int color_id;
    public String color_name;

    public Car(JSONObject data) {
        try {
            this.name = data.getString("name");
            this.color_id = data.getInt("color_id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

And last, this is a piece of the strings.xml resource file:

<string-array name="color_names">
    <item>White</item>
    <item>Yellow</item>
    <item>Orange</item>
    <item>Red</item>
    <item>Black</item>
</string-array>

When I get the data from server, there is a for loop to create the instances of the Car class, one for each item in the JSONArray .

What I want to do is to get the color name from the <string-array> , using the property color_id as the array index, but I can't find a way to get the R.array resource from the Car class constructor.

How should I do this?

Thank You!

What I want to do is to get the color name from the , using the property color_id as the array index, but I can't find a way to get the R.array resource from the Car class constructor.

Your class has to know "about Context" since resources are available only from Context , so here you need a little modification in your constructor:

public Car(Context c, JSONObject data) {
   // do your stuff
}

Now, your class knows current Context so you're able to obtain data you need:

String name = c.getResources().getStringArray(R.id.arrayId)[<index>];

Hope it'll solve your problem.

You should provide context ot Car object or instantiate array from res in some util class with app context and provide API something like Utils.getColorNameByColorId(int color_id) . The last way is preferable because of performance - array will be instantiate only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM