Marcus
Marcus

Reputation: 113

How do I use both CordovaActivity and AppCompatActivity in Android java code?

I'm making a Cordova plugin so I need to extend the MainActivity class with CordovaActivity. I also need to use AppCompatActivity. In a native app I extended MainActivity with AppCompatActivity and everything worked fine but in my Cordova plugin I'm not able to extend twice.

I'm trying to launch some code to keep running in the background. When I try this within onCreate:

appCompat = new AppCompatActivity();
Intent intent = new Intent(this, MyClass.class);
appCompat.startService(intent);

I define global variable:

private AppCompatActivity appCompat;

I get an error at runtime about the context (appCompat) being null. This is the actual error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

Does anyone know how I can use AppCompatActivity without using it as an extension?

(edit: I've attached the whole class for the sake of clarity)

public class MainActivity extends CordovaActivity {
    private AppCompatActivity appCompat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Context context = this.getBaseContext();
        Intent intent = new Intent(context, MyClass.class);
        appCompat = new AppCompatActivity();
        appCompat.startService(intent);  // CAUSES CRASH AT RUNTIME
    }
}

Upvotes: 2

Views: 2065

Answers (2)

Prateek Pande
Prateek Pande

Reputation: 505

I updated CordovaActivty class to extend AppCompatActivity, as i had to deal with Toolbar. I'm not sure if its the right approach, but it works fine for me.

Upvotes: 1

Marcus
Marcus

Reputation: 113

Well it turns out I don't need to use AppCompatActivity to run services in the background. I can simply use:

Intent intent = new Intent(this, MyClass.class);
startService(intent)

and it works just fine.

Upvotes: 0

Related Questions