What is the best way to handle multiple intentions in Android?

advertisements

We come across the following code or something similar in Android or Java many times. This code seems like containing repetitions and this is not a good practice at all. There must be some better way to do this. is there any shorter code to achieve this?

 Intent intent=null;
    switch (v.getId()) {
        case R.id.details:
            intent = new Intent(this, DetailsActivity.class);
            break;
        case R.id.apply:
            intent = new Intent(this, ApplyActivity.class);
            break;
        case R.id.edit:
            intent = new Intent(this, EditActivity.class);
            break;
        case R.id.upload:
            intent = new Intent(this, UploadActivity.class);
            break;
        case R.id.call:
            intent = new Intent(this, CallActivity.class);
            break;
    }
    startActivity(intent);


Make a table of ids to activity classes in a static initializer or constructor:

HashMap<Integer, Class<?>> map = new HashMap<>();
map.put(R.id.foo, Foo.class);  // repeat for each id/class pair

Then use the map instead of a switch:

startActivity(new Intent(this), map.get(v.getId()));