Search code examples
javaandroidionic-frameworkcapacitor

How can i access Application in MainActivity which we get in Ionic Projects


I am trying to integrate Swrve plugin in my Android project. Following is the code which we get in MainActivity

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(MyPlugin.class);
    }});

    try {
      SwrveConfig config = new SwrveConfig();
      // To use the EU stack, include this in your config.
      // config.setSelectedStack(SwrveStack.EU);
      SwrveSDK.createInstance(this, <app_id>, "<api_key>", config);
    } catch (IllegalArgumentException exp) {
      Log.e("SwrveDemo", "Could not initialize the Swrve SDK", exp);
    }
  }
}

When i run the code i get following error

error: incompatible types: MainActivity cannot be converted to Application

The reference code on the site is following

public class YourApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        try {
            SwrveConfig config = new SwrveConfig();
            // To use the EU stack, include this in your config.
            // config.setSelectedStack(SwrveStack.EU);
            SwrveSDK.createInstance(this, <app_id>, "<api_key>", config);
        } catch (IllegalArgumentException exp) {
            Log.e("SwrveDemo", "Could not initialize the Swrve SDK", exp);
        }
    }
}

In ionic project i have MainActivity and not the

public class MainActivity extends BridgeActivity {

In documentation i have this

public class YourApplication extends Application {

and in initialization line This keyword is trying to refer to Application and not the MainActivity

SwrveSDK.createInstance(this, <app_id>, "<api_key>", config);

I dont have any knowledge about native code so i would appreciate if some one can guide me and explain me what the fix can be.


Solution

  • You need to create an Application class for that code.

    Make a new Java class and set it to extend Application:

    public class SomeApp extends Application {}
    

    Then add it to your AndroidManifest, in the application tag:

    <application
        ...
        android:name=".SomeApp">
    

    Then follow the setup guide, putting what's supposed to be in the Application class in the Application class you just created.