将标题设置为操作栏时出现空指针异常

getting Null pointer exception while setting the title to action bar

Error:Caused by: java.lang.NullPointerException: Attempt to invoke   
virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference

尝试使用 getSupportActionBar() 也无法解决异常 请帮我解决这个问题

我试过 v7 版本的 ActionBarActivity,用 AppCompactActivity 扩展 class 仍然无法解决。

在模拟器和真实设备上执行相同的问题。 打开应用程序后,不幸的是 "app" 停止工作。

package pizzandburger.hfad.com.pizzaandburger;

        import android.app.Activity;
        import android.app.Fragment;
        import android.app.FragmentManager;
        import android.app.FragmentTransaction;
        import android.content.Intent;
        import android.content.res.Configuration;
        import android.os.Bundle;
        import android.support.v4.widget.DrawerLayout;
        import android.support.v7.app.ActionBarDrawerToggle;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;
        import android.widget.ShareActionProvider;


        public class MainActivity extends Activity {

            private String[] titles;
            private ListView drawerList;
            private DrawerLayout drawerLayout;
            private ActionBarDrawerToggle drawerToggle;
            private ShareActionProvider shareActionProvider;
            private int currentPosition=0;
            private class DrawerItemClickListener implements  ListView.OnItemClickListener{

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectItem(position);
                }
            };

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                titles=getResources().getStringArray(R.array.items);
                drawerList=(ListView)findViewById(R.id.drawer);
                drawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
                drawerList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1,titles));
                drawerList.setOnItemClickListener(new DrawerItemClickListener());
                if(savedInstanceState!=null){
                    currentPosition=savedInstanceState.getInt("position");
                    setActionBarTitle(currentPosition);
                }
                else{
                    selectItem(0);
                }
                drawerToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.open_drawer,R.string.close_drawer){
                    @Override
                    public void onDrawerClosed(View view){
                        super.onDrawerClosed(view);
                        invalidateOptionsMenu();
                    }
                    @Override
                    public void onDrawerOpened(View drawerView){
                        super.onDrawerOpened(drawerView);
                        invalidateOptionsMenu();
                    }
                };
                drawerLayout.setDrawerListener(drawerToggle);
                getActionBar().setDisplayHomeAsUpEnabled(true);
                getActionBar().setHomeButtonEnabled(true);
                getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
                    @Override
                    public void onBackStackChanged() {
                        FragmentManager fragmentManager=getFragmentManager();
                        Fragment fragment=fragmentManager.findFragmentByTag("visible_fragment");
                        if(fragment instanceof TopFragment){
                            currentPosition=0;
                        }
                        else if(fragment instanceof PizzaFragment){
                            currentPosition=1;
                        }
                        else if(fragment instanceof BurgerFragment){
                            currentPosition=2;
                        }
                        else if(fragment instanceof OtherFragment){
                            currentPosition=3;
                        }
                        else if(fragment instanceof BeveragesFragment){
                            currentPosition=4;
                        }
                        setActionBarTitle(currentPosition);
                        drawerList.setItemChecked(currentPosition,true);
                    }
                });

            }
            private void selectItem(int position){
                Fragment fragment;
                currentPosition=position;
                switch (position){
                    case 1:
                        fragment=new PizzaFragment();
                        break;
                    case 2:
                        fragment=new BurgerFragment();
                        break;
                    case 3:
                        fragment=new OtherFragment();
                        break;
                    case 4:
                        fragment=new BeveragesFragment();
                        break;
                    default:
                        fragment= new TopFragment();
                        break;
                }
                FragmentTransaction ft=getFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment, "visible_fragment");
                ft.addToBackStack(null);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
                setActionBarTitle(position);
                drawerLayout.closeDrawer(drawerList);
            }

            @Override
            public void onConfigurationChanged(Configuration newConfig) {
                super.onConfigurationChanged(newConfig);
                drawerToggle.onConfigurationChanged(newConfig);
            }

            @Override
            protected  void onPostCreate(Bundle savedInstanceState){
                super.onPostCreate(savedInstanceState);
                drawerToggle.syncState();
            }
            @Override
            public void onSaveInstanceState(Bundle outState){
                super.onSaveInstanceState(outState);
                outState.putInt("position",currentPosition);
            }

            @Override
            public boolean onPrepareOptionsMenu(Menu menu){
                boolean drawerOpen=drawerLayout.isDrawerOpen(drawerList);
                menu.findItem(R.id.action_share).setVisible(!drawerOpen);
                return super.onPrepareOptionsMenu(menu);
            }


            private void setActionBarTitle(int position){
                String title;
                if(position==0){
                    title=getResources().getString(R.string.app_name);
                }
                else{
                    title=titles[position];
                }

     /*******************************/
    /**** here its giving error *****/ 
   /*******************************/
                getActionBar().setTitle(title);
            }
            @Override
            public boolean onCreateOptionsMenu(Menu menu){
                getMenuInflater().inflate(R.menu.menu_main, menu);
                MenuItem menuItem=menu.findItem(R.id.action_share);
                shareActionProvider=(ShareActionProvider)menuItem.getActionProvider();
                setIntent("this is some simple text for sharing through shareActionProvider");
                return super.onCreateOptionsMenu(menu);
            }
            @Override
            public boolean onOptionsItemSelected(MenuItem menuitem){
                if(drawerToggle.onOptionsItemSelected(menuitem)){
                    return true;
                }
                switch (menuitem.getItemId()){
                    case R.id.action_settings:
                        return true;
                    default:
                        return super.onOptionsItemSelected(menuitem);
                }
            }
            private void setIntent(String text){
                Intent intent=new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT,text);
                shareActionProvider.setShareIntent(intent);
            }
        }

这是我的 styles.xml

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

这是我的 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    >
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/content_frame"></FrameLayout>
    <ListView
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:id="@+id/drawer"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#ffffff"></ListView>
</android.support.v4.widget.DrawerLayout>
  1. 尝试过手动设置标题,但没有用
  2. 用调试器检查它无法获取 ActionBarObject

一些前提:

  • 检查您是否已声明 import android.support.v7.app.AppCompatActivity 并且您的 activity 已扩展。
  • 检查您是否声明了 WINDOWS_FEATURE: requestWindowFeature(Window.FEATURE_ACTION_BAR); 或者按照你的风格: <item name="android:windowActionBar">true</item>

问候,

是样式的问题sheet 也就是说

"<style name="AppTheme.NoActionBar">"

定义一些主题然后摆脱空指针异常

如果您将 INTENT 与 AppCompatActivity 一起使用,则需要访问相同的相关线程:

YourClass mContext;
mContext.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        mContext.getSupportActionBar().hide();
    }
});

YourClass 是扩展 AppCompActivity 的类:

public class YourClass extends AppCompatActivity {
}