Tori
Tori

Reputation: 1356

StartActivity from a method

This is more of a Java question as it relates to Android.

My code includes a switch statement with 30 cases. The body of each case has the same format to start an intent relating to that case. I was trying to code the body as a method with the name of the class as an argument, but that code does not compile as the class name has to be hard coded in the intent.

Below is a section of the switch (the long way)

            switch(mState) {
    case 0:
               Intent myIntent = new Intent();
               myIntent.setClass(Home_ASM.this, Home_AS0.class);
               startActivityForResult(myIntent, 0);
               break;

    case 1:
              Intent myIntent1 = new Intent(); 
              myIntent1.setClass(Home_ASM.this, Home_AS1.class);
              startActivityForResult(myIntent1, 2);
              break;    

and I would like to code such:

            switch(mState) {
            case 0:
               myStart(Home_AS0.class,1);
               break;
            case 1:
               myStart(Home_AS1.class,2);
               break;

and the method

private void myStart(String state, int value) {
            Intent myIntent = new Intent();
            myIntent.setClass(Home_ASM.this, state);
            startAcivityForResult(myIntent, value);
            }

Any ideas on how I can make this work?

Upvotes: 0

Views: 114

Answers (3)

kosa
kosa

Reputation: 66637

You may try Class.forName("nameofClass");

EDIT: After edits, Jon Taylor answer is more appropriate than my answer. See: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#forName%28java.lang.String%29

Upvotes: 2

biddulph.r
biddulph.r

Reputation: 5266

We do a similar thing. our code looks a bit like this:

Switch Statement:

case 0:
      {
         launchActivity(ActivityOne.class, value);
         break;
      }

Method to launch activity:

private void launchActivity(Class<?> aClass, int value) {
        Intent intent = new Intent();
        intent.setClass(this, aClass);
        startActivityForResult(intent, value);
    }

You can easily adapt this to take your specific int value. Hope this helps!

Upvotes: 1

Jon Taylor
Jon Taylor

Reputation: 7905

Why not have a method

private void myStart(Class class, int value)

And just pass it a class instead of a string?

Upvotes: 2

Related Questions