4

I want to use common progressBar which is used in all activities. This can be done by checking in if else statements like

if(mContext instanceOf ActivityA)
   {
     //Do Something   
   }else if(mContext instanceOf ActivityB)
   {
    //Do Something
   }

But I want to do Something like :

switch(mContext){
case mContext instaceOf ActivityA:
                    //Do Something
case mContext instanceOf ActivityB:
                    //DoSomething
}

How Can I Achive by checking context in switch

Ravi
  • 34,851
  • 21
  • 122
  • 183
Ritesh
  • 533
  • 2
  • 7
  • 18
  • 1
    `switch` cannot be used for matching conditions, only values. – Mohammed Aouf Zouag Jan 02 '16 at 10:50
  • yes I want use progressBar which is common for all activities, i just have to pass context and value to it. – Ritesh Jan 02 '16 at 10:56
  • @sparta . - so Is there any nice approach to check context rather than if else statements. – Ritesh Jan 02 '16 at 10:57
  • I think that `if/else`s are pretty fine in this case. – Mohammed Aouf Zouag Jan 02 '16 at 10:58
  • FWIW, there's probably a better way that a lengthy `if..else...` statements. It sounds as though you could, for instance, have a base `Activity` which `ActivityA` and `ActivityB` extends, and an `abstract` method that's called. – PPartisan Jan 02 '16 at 10:59
  • but you can still use switch without the conditions by extracting the class name as string from the context. Check my answer. – Viral Patel Jan 02 '16 at 11:00
  • i also tried to use this method for string but it's not allowed in switch, but we can find switch case support with string in jdk1.8 – Androider Jan 02 '16 at 11:05

2 Answers2

3

You can do it this way:

String className = mContext.getClass().getSimpleName();

switch (className) {
  case "ActivityA":
     //Do Something
  case "ActivityB":
     //DoSomething
}

Note: String support for switch was added only after JDK 7. If you are using an earlier version of Java you can use a few hacks on the above to get switch working. Some examples in the answers to this question.

Community
  • 1
  • 1
Viral Patel
  • 32,418
  • 18
  • 82
  • 110
1

You cannot use a switch statement to match conditions.

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67