androidarraysclasstypedarray

Android - How to store array of classes in res xml


I want to store list of classes inside an xml on my res, so I can use it globally just using the index.

<resources>
    <array name="array_class">
        <class>Dashboard.class</class>
    </array>
</resources>

in my activity

int index = x; // i get the the index from database
TypedArray arrayClass = getActivity().getResources()
        .(R.array.array_class);
Class myClass = (Class) arrayClass.getString(index);

It throw me an error, cannot cast String to Class. Yeah I know, I cannot do that. So how the correct way to store array of classes on res? or any alternative way to call Class[] value globally??


Solution

  • Inside your resource file store full name of all classes including package name

    <resources>
        <array name="array_class">
            <class>com.example.Dashboard</class>
            <class>com.example.YourOtherClass</class>
        </array>
    </resources>
    

    Then in Java code, you can retrieve by the following method

    try {
        int index = x; // i get the the index from database
        TypedArray arrayClass = getActivity().getResources().(R.array.array_class);
        Class<?> act = Class.forName(arrayClass.getString(index));
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    

    Hope it helps