Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android getActionBar vs getSupportActionBar?

Here is my code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){

    //android.support.v7.app.ActionBar actionBar = getSupportActionBar();
    //actionBar.setTitle("Android");

    ActionBar actionBar = getActionBar();
    actionBar.setTitle("Droid");
}

While using the getSupportActionBar() my app runs just fine with kitkat and other new versions but using getActionBar results into an error.

Here is error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.hide()' on a null object reference
            at com.github.domain.geoquiz.QuizActivity.onCreate(QuizActivity.java:57)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372

Why? From android documentations :

Caution: Be certain you import the ActionBar class (and related APIs) from the appropriate package:

If supporting API levels lower than 11: import android.support.v7.app.ActionBar

If supporting only API level 11 and higher: import android.app.ActionBar

Now why this app is crashing?

like image 721
Amit Tripathi Avatar asked Jan 17 '15 17:01

Amit Tripathi


2 Answers

If you are extending AppCompatActivity then you are providing backward support for older Android versions and for that you have to use getSupportActionBar().

If you are importing android.app.ActionBar then you have to use getActionBar() and if you are importing android.support.v7.app.ActionBar then you have to use getSupportActionBar().

Note: By using android.support.v7.app.ActionBar, you can provide backward support for older Android versions.

like image 149
Chintan Shah Avatar answered Oct 03 '22 02:10

Chintan Shah


If you are using AppCompat you always have to call getSupportActionBar() no matter which Android Version your App is running.

Which Android versions do you target?

I would advise you to use the new Toolbar instead of ActionBar, because it's way more flexible to use.

like image 34
carstenbaumhoegger Avatar answered Oct 03 '22 02:10

carstenbaumhoegger