14

I'm trying to pass class name with extra, how to do that ?

Intent p = new Intent(StartScreen.this, Setting.class);
p.putExtra(" ",StartScreen.this);

I want to get the class name in Setting class but I don't want it to be String cause I'm going to use this class name like that :

Bundle extras = getIntent().getExtras();
extras.getString("class");
Intent i = new Intent(Setting.this, class);
startActivity(i);
Maroun
  • 94,125
  • 30
  • 188
  • 241
Jesus Dimrix
  • 4,378
  • 4
  • 28
  • 62
  • What do you want to achieve? – Stefan Mar 10 '13 at 15:47
  • i have setting activity that change the theme for application , so i need the setting activity to start the activity that called her when done . the reson i cant just use finish() is that i need the last activity to start all over again and not jst resume . – Jesus Dimrix Mar 10 '13 at 16:02

2 Answers2

20

you can use this code

Intent p = new Intent(StartScreen.this, Setting.class);
p.putExtra("class","packagename.classname");

and in setting class

Bundle extras = getIntent().getExtras();
String classname=extras.getString("class");
Class<?> clazz = Class.forName(classname);
Intent i = new Intent(Setting.this, clazz);
startActivity(i);
  • 2
    This should not be the preferred method, rather use Serializable or Parcelable (see [this answer](https://stackoverflow.com/a/34665086/5082708)) – Luka Govedič Jun 18 '18 at 09:59
13

A tidier way than the accepted answer would be to use Serializable or Parcelable.

Here is an example of how to do it using Serializable:

In your first activity...

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("EXTRA_NEXT_ACTIVITY_CLASS", ThirdActivity.class);
startActivity(intent);

Then in your second activity...

Bundle extras = getIntent().getExtras();
Class nextActivityClass = (Class<Activity>)extras.getSerializable("EXTRA_NEXT_ACTIVITY_CLASS");
Intent intent = new Intent(SecondActivity.this, nextActivityClass);
startActivity(intent);

Doing it with Parcelable is pretty much the same, except you would replace extras.getSerializable("EXTRA_NEXT_ACTIVITY_CLASS") in the above code with extras.getParcelable("EXTRA_NEXT_ACTIVITY_CLASS").

The Parcelable method will be faster, but harder to set up (as you need to make your third Activity implement Parcelable - see http://developer.android.com/reference/android/os/Parcelable.html).

ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253
  • 2
    Thanks you for this answer! It might be worth noting that this will work in the case of developing plugins as apposed to the approved answer. I am currently working on a plugin which popups a screen, which will need to know what class to open on completion of that screen. Class.forName will not work in this case because the plugin does not know of the class name. Parsing the class name as a serializable will. – Raymond May 06 '16 at 09:50