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"); } 

When using getSupportActionBar (), my application works fine with kitkat and other new versions, but using getActionBar results, an error occurs.

Here is the 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 the documentation for Android:

Caution: make sure you import the ActionBar class (and its associated APIs) from the appropriate package:

If API levels below 11 are supported: import android.support.v7.app.ActionBar

If only API level 11 and above is supported: import android.app.ActionBar

Now why is this app crashing?

+6
source share
2 answers

If you use AppCompat, you always need to call getSupportActionBar() no matter which version of Android your application is running.

What versions of Android are you targeting?

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

+11
source

If you extend AppCompatActivity , you provide back support for older versions of Android and for this you need to use getSupportActionBar() .

If you import android.app.ActionBar , then you should use getActionBar() , and if you import android.support.v7.app.ActionBar , then you should use getSupportActionBar() .

Note. . Using android.support.v7.app.ActionBar , you can provide back support for older versions of Android.

+2
source

Source: https://habr.com/ru/post/981152/


All Articles