将标题设置为操作栏时获取Null指针异常

时间:2016-07-04 18:23:31

标签: android android-actionbaractivity

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扩展该类仍然无法解析。

在仿真器和真实设备上执行相同的问题。 在打开应用程序后,它的显示很不幸" 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

3 个答案:

答案 0 :(得分:1)

一些前提:

  • 检查您是否已宣布import android.support.v7.app.AppCompatActivity并且您的活动已延长。
  • 检查您是否声明了WINDOWS_FEATURE: requestWindowFeature(Window.FEATURE_ACTION_BAR); 或者你的风格: <item name="android:windowActionBar">true</item>

的问候,

答案 1 :(得分:0)

它是样式表中的问题 那说

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

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

答案 2 :(得分:0)

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

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

YourClass是扩展AppCompActivity的一种:

public class YourClass extends AppCompatActivity {
}