What is a better way to handle multiple intents in android?… here is a solution to the problem.
What is a better way to handle multiple intents in android?
We have come across the following code or something similar many times in Android or Java. This code seems to contain repetitions, which is not a good practice at all. There must be some better way to do this. Is there any shorter code to implement 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);
Solution
Create an ID table for the Activity class 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 map instead of switch:
startActivity(new Intent(this), map.get(v.getId()));