user842225
user842225

Reputation: 5989

create an instance of Activity with Activity class object

I have got an Activity class by:

Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());

String activityClassName = launchIntent.getComponent().getClassName();

Class<?> activityClazz = Class.forName(activityClassName);

Is it possible to create an instance of this Activity by using the activityClazz ? If so, how?

(My code is in a independent java class. Not in activity or service. )

Upvotes: 3

Views: 3646

Answers (3)

David Wasser
David Wasser

Reputation: 95578

Technically, you can create an instance of an Activity like this. However, this instance would be useless because its underlying Context would not have been set up.

The rule is that you should never ever create instances of Android components (Activity, Service, BroadcastReceiver, Provider) yourself (using the new keyword or other means). These classes should only ever be created by the Android framework, because Android sets up the underlying Context for these objects and also manages the lifecycle.

In short, your architecture is flawed if you need to create an instance of an Activity like this.

Upvotes: 6

shaikhmanzoor
shaikhmanzoor

Reputation: 89

yes. you can get the activity context by using below line of code

Activity activity = (Activity) getContext();

Upvotes: 0

King of Masses
King of Masses

Reputation: 18765

Class.forName() needs the fully qualified name - that is, the name of the package the class is contained in, plus the simple name of the class itself.

Assuming the package containing the class is called com.your.package, the code would have to be

    String className = "com.your.package.Tab3";  // Change here
     Object obj= null;
    try {
        obj= Class.forName(className).newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

Upvotes: 1

Related Questions