6

I have a little problem. I want to start activity but in something other way. I know that

Intent i = new Intent(this, ActivityTwo.class); 

initialize intent and after that I can startActivity. But I want do something like that:

Intent i = new Intent(this, MyString.class);

I have no nameActivity.class, but I want change on string.class. How I can start activity when I have string name of class?

ρяσѕρєя K
  • 130,641
  • 51
  • 193
  • 212
user1302569
  • 6,941
  • 13
  • 45
  • 65
  • What exactly is the scenario? Are you trying to start an activity based on some STRING value which will be used as the name for the Activity to be launched? – Anukool Feb 13 '13 at 09:28
  • 1
    http://stackoverflow.com/questions/5754855/how-can-i-start-a-new-android-activity-using-a-string – baboo Feb 13 '13 at 09:28
  • 1
    You can use reflection but is it really necessary? –  Feb 13 '13 at 09:28
  • When you have for example ActivityFirst.class I want to have string instead ActivityFirst and this is necessary – user1302569 Feb 13 '13 at 09:29
  • Possible duplicate of [How can I start a new android activity using a string?](http://stackoverflow.com/questions/5754855/how-can-i-start-a-new-android-activity-using-a-string) – ThomasW Feb 27 '17 at 10:41

5 Answers5

8

Try this: startActivity(this, Class.forName(yourStringClass));

PaNaVTEC
  • 2,498
  • 1
  • 22
  • 36
6

Here is a code by which you can start activity using the name of the activity

Class<?> c = null;
if(StringClassname != null) {
    try {
        c = Class.forName(StringClassname );
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Intent intent = new Intent(mail.this, c);
startActivity(intent);

Here class name will be full name of the class with the package name. For example if your package name will be x.y.z and if you have Activity name called A then the full name of the Activity A will be x.y.z.A.

jlopez
  • 6,287
  • 2
  • 51
  • 90
4

You can look up a Class by name using Class.forName("MyString")

Bhavin Nattar
  • 3,133
  • 2
  • 20
  • 30
Clyde
  • 7,078
  • 3
  • 30
  • 52
2

Just use....

  Intent intent = new Intent().setClassName(activity,"packageName"+"className");
  startActivity(intent);
Nilesh
  • 983
  • 13
  • 21
1


Class<?> c =Class.forName("YOUR STRING" );
Intent intent = new Intent(FirstActivity.this, c);
startActivity(intent);
René Höhle
  • 25,733
  • 22
  • 69
  • 78
Anukool
  • 5,091
  • 8
  • 27
  • 41
  • The constructor Intent(TabsGenerator, Class) is undefined – user1302569 Feb 13 '13 at 09:32
  • 1
    Forgot to mention- the class name should be the fully qualified class name. Suppose the package name is com.something and the String is "THESTRING" then the fully qualified name will be - com.something.THESTRING .. Hope this helps – Anukool Feb 13 '13 at 09:52
  • @Anukool : Please Edit your answer and put this comment in it. – Kishor Pawar May 27 '15 at 11:15