Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. )

like image 602
user842225 Avatar asked Dec 05 '25 17:12

user842225


2 Answers

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.

like image 72
David Wasser Avatar answered Dec 08 '25 07:12

David Wasser


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();
    }
like image 39
King of Masses Avatar answered Dec 08 '25 05:12

King of Masses



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!