3

I have following goal: From a list in main activity that extends ListActivity, I want to start other activities.

This is the code of the main activity:

public class SelectionWidgetsExampleActivity extends ListActivity {

    private Class[] demos = {ListViewDemo.class, ChecklistDemo.class};
    private ArrayAdapter<Class> aa;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        aa = new ArrayAdapter<Class>(this, android.R.layout.simple_list_item_1, demos);
        setListAdapter(aa);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = new Intent(this, demos[position]);
        startActivity(intent);
    }
}

My question is

How would you solve the issue of having list of classes to be executed outside the code of the main activity?

My first idea was to put it into xml resource file as string array. I can then easily create array of Strings from the resource, but don't know how to convert the string to the class - I need something like:

    SomeJavaClass.getMeClassFromString(demos[position])
Tomas
  • 459
  • 3
  • 15

1 Answers1

1

Do you need Class#forName(String className)? It will solve your issue.
But what's wrong with your initial (posted) solution? I'd rather keep it than use dynamic class loading, only would changed modifiers of demos to private static final.

ernazm
  • 9,208
  • 4
  • 44
  • 51
  • I just wasn't sure if using the Class type wasn't some bad practice. Also, I get a warning in the line where i declare `Class[] demos` saying Class is raw type, and I should use generics. However, when I change it to `Class[] demos = {...};` I get an error saying *Cannot create generic array of Class*. – Tomas Aug 12 '11 at 14:23
  • Interesting point. Searched a bit and found this thread http://stackoverflow.com/questions/749425/how-do-i-use-generics-with-an-array-of-classes. However, in your case I'd use `@SuppressWarnings("rawtypes")` since you don't care of actual class as they will be predefined and won't be even casted to `Activity`. – ernazm Aug 12 '11 at 14:37