getSupportActionBar()在完美工作数周后返回null

时间:2015-04-03 10:16:37

标签: android android-actionbar navigation-drawer

我正在编写一个小型时间表项目,并在从学校导入到家中后,我收到此错误。请记住,我已经四次检查我在我需要的每个地方都使用了getSupportActionBar()。

  04-03 10:54:02.561: E/AndroidRuntime(24473): FATAL EXCEPTION: main
  04-03 10:54:02.561: E/AndroidRuntime(24473): Process:       com.pipturner.timetable, PID: 24473
  04-03 10:54:02.561: E/AndroidRuntime(24473): java.lang.RuntimeException:       Unable to start activity  ComponentInfo{com.pipturner.timetable/com.pipturner.timetable.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void       android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null objectreference
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.ActivityThread.access$800(ActivityThread.java:148)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.os.Handler.dispatchMessage(Handler.java:102)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.os.Looper.loop(Looper.java:135)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.ActivityThread.main(ActivityThread.java:5312)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at java.lang.reflect.Method.invoke(Native Method)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at java.lang.reflect.Method.invoke(Method.java:372)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
  04-03 10:54:02.561: E/AndroidRuntime(24473): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.support.v7.app.ActionBarImplICS.setDisplayHomeAsUpEnabled(ActionBarImplICS.java:179)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.support.v7.app.ActionBarImplJB.setDisplayHomeAsUpEnabled(ActionBarImplJB.java:20)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at com.pipturner.timetable.NavigationDrawerFragment.setUp(NavigationDrawerFragment.java:146)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at com.pipturner.timetable.MainActivity.onCreate(MainActivity.java:76)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.Activity.performCreate(Activity.java:5953)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
  04-03 10:54:02.561: E/AndroidRuntime(24473):  ... 10 more

这是调用它的MainActivity

package com.pipturner.timetable;

import java.util.List;
import Database.DatabaseHelper;
import Database.MC_shomework;
import Database.MC_slesson;
import Database.MC_sschoolday;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity implements
        NavigationDrawerFragment.NavigationDrawerCallbacks {

    DatabaseHelper db;
    OnClickListener homeworkOnClickListener =
               new OnClickListener(){

                @Override
                public void onClick(View v) {
                    Class<?> homework = Input_shomework.class;
                    StartIntent(homework); //run the add a new homework screen
                }
                };

     OnClickListener lessonOnClickListener =
                           new OnClickListener(){

                            @Override
                            public void onClick(View v) {
                                Class<?> lesson = Input_slesson.class;
                                StartIntent(lesson); //run the add a new homework screen
                            }
                            };      

    /**
     * Fragment managing the behaviors, interactions and presentation of the
     * navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in
     * {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
                .findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        createDataItems(); //adds lessons and days to the database
        getUserSettings(); //gets the settings from the preference screen and stores them into the database
        displayUserSettings(); //gets the settings that were stored in the database and displays them in a text field
        displayUserHomeworks(); //gets and displays the homeworks
        Button button = (Button) findViewById(R.id.homeworkbutton); //sets a button to the homework button

         button.setOnClickListener(homeworkOnClickListener); //if the button is clicked, do the homeworkOnClickListener
        // Button lessonbutton = (Button) findViewById(R.id.lessonbutton);
         //lessonbutton.setOnClickListener(lessonOnClickListener);
        }

    private void createDataItems(){
        db = new DatabaseHelper(getApplicationContext());       

        MC_sschoolday[] sday = new MC_sschoolday[8];
        MC_slesson[] slesson = new MC_slesson[7];


        sday[1] = new MC_sschoolday(1, "Monday",    "n", 0); //creates a schoolday
        sday[2] = new MC_sschoolday(2, "Tuesday",   "n", 0);
        sday[3] = new MC_sschoolday(3, "Wednesday", "n", 0);
        sday[4] = new MC_sschoolday(4, "Thursday",  "n", 0);
        sday[5] = new MC_sschoolday(5, "Friday",    "n", 0);
        sday[6] = new MC_sschoolday(6, "Saturday",  "n", 0);
        sday[7] = new MC_sschoolday(7, "Sunday",    "n", 0);

        slesson[1] = new MC_slesson(1, "Maths", "21", "Mrs Anderson"); //creates a lesson
        slesson[2] = new MC_slesson(2, "Maths", "14", "Mr Dhillow");
        slesson[3] = new MC_slesson(3, "English", "2", "Mr Duck");
        slesson[4] = new MC_slesson(4, "English", "3", "Mrs Brown");
        slesson[5] = new MC_slesson(5, "Computing", "C1", "Mr King");
        slesson[6] = new MC_slesson(6, "Computing", "C3", "Ms Brown");

        if  (db.getAllSSchoolDays().size()<7){

              // Creating schooldays

            // Inserting them in db
            db.createSSchoolDay(sday[1]);
            db.createSSchoolDay(sday[2]); 
            db.createSSchoolDay(sday[3]);
            db.createSSchoolDay(sday[4]);
            db.createSSchoolDay(sday[5]);
            db.createSSchoolDay(sday[6]);
            db.createSSchoolDay(sday[7]);
            Log.v("Main Activity", "Added Schooldays");
        }
        if(db.getAllLessons().size()<6){
            //inserts lessons into database
            db.createSLesson(slesson[1]);
            db.createSLesson(slesson[2]);
            db.createSLesson(slesson[3]);
            db.createSLesson(slesson[4]);
            db.createSLesson(slesson[5]);
            db.createSLesson(slesson[6]);

            }
        }

        private void getUserSettings() {
            boolean[] d = new boolean[7];
            int[] dp = new int[7];
            String[] dps = new String[7];

            MC_sschoolday[] sday = new MC_sschoolday[8];
            sday[1] = new MC_sschoolday(1, "Monday",    "n", 0); //creates a schoolday
            sday[2] = new MC_sschoolday(2, "Tuesday",   "n", 0);
            sday[3] = new MC_sschoolday(3, "Wednesday", "n", 0);
            sday[4] = new MC_sschoolday(4, "Thursday",  "n", 0);
            sday[5] = new MC_sschoolday(5, "Friday",    "n", 0);
            sday[6] = new MC_sschoolday(6, "Saturday",  "n", 0);
            sday[7] = new MC_sschoolday(7, "Sunday",    "n", 0);



        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        d[0] =sharedPrefs.getBoolean("schooldays_monday", false);
            dps[0]=sharedPrefs.getString("schooldays_monday_periods", "0");

        d[1] =sharedPrefs.getBoolean("schooldays_tuesday", false);
            dps[1]=sharedPrefs.getString("schooldays_tuesday_periods", "0");

        d[2] =sharedPrefs.getBoolean("schooldays_wednesday", false);
            dps[2]=sharedPrefs.getString("schooldays_wednesday_periods","0");

        d[3] =sharedPrefs.getBoolean("schooldays_thursday", false);
            dps[3]=sharedPrefs.getString("schooldays_thursday_periods", "0");

        d[4] =sharedPrefs.getBoolean("schooldays_friday", false);
            dps[4]=sharedPrefs.getString("schooldays_friday_periods", "0");

        d[5] =sharedPrefs.getBoolean("schooldays_saturday", false);
            dps[5]=sharedPrefs.getString("schooldays_saturday_periods", "0");

        d[6] =sharedPrefs.getBoolean("schooldays_sunday", false);
            dps[6]=sharedPrefs.getString("schooldays_sunday_periods", "0");

            for(int i=0; i<7;i++){
                dp[i] = Integer.parseInt(dps[i]);
                Log.v("Days", "Parsed String to int " + i + " times(s)");
            }

            for(int i=0; i<7;i++){
                if(d[i]){
                    sday[i+1].setUsed("y");
                    sday[i+1].setNo_of_lessons(dp[i]);
                    db.updatesSchoolDay(sday[i+1]);

                }
            }

            db.closeDB();


    }

    private void displayUserSettings(){
        String[] days = new String[7];

        db = new DatabaseHelper(getApplicationContext());

        MC_sschoolday[] sday = new MC_sschoolday[7];

        List<MC_sschoolday> schoolday = db.getAllSSchoolDays();

        for (int i =0; i< db.getAllSSchoolDays().size(); i++){
                sday[i]=schoolday.get(i);
            }



        for(int i =0;i < 7; i++){
        //  if(sday[i].getUsed()=="y"){
                days[i]=(sday[i].getschool_day()+": \n" +
                        "    Number Of Lessons: "+sday[i].getNo_of_lessons()+"\n");

        //  }
        }

        TextView settingsTextView = (TextView) findViewById(R.id.lessons);
        settingsTextView.setText(
                days[0] +days[1] + days[2] + days[3] +days[4] +days[5] +days[6] 
                                    + "\n NUMBER OF DAYS " +db.getAllSSchoolDays().size() + "\n NUMBER OF HOMEWORKS " + db.getAllHomework().size());


    db.close();
    }

    public void displayUserHomeworks(){
        db = new DatabaseHelper(getApplicationContext());   
        int homeworksize = db.getAllHomework().size();
        MC_shomework[] shomework = new MC_shomework[homeworksize];
        List<MC_shomework> homeworklist = db.getAllHomework();

        String[] homeworkString = new String[homeworksize];

        for (int i =0; i< homeworksize; i++){
            shomework[i]=homeworklist.get(i);
        }

        for(int i =0;i < homeworksize; i++){
            homeworkString[i]=("Lesson ID: " + shomework[i].getSlesson_ID()+": \n" +
                            "    Duedate: "+shomework[i].getShomework_duedate()+"\n"+
                            "    Details: "+shomework[i].getShomework_details()+"\n");
            }

        if(homeworksize>0){
            TextView settingsTextView = (TextView) findViewById(R.id.homeworktext);
            settingsTextView.setText(
                    homeworkString[0]
                    );
            }
            db.close();
    }




    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager
                .beginTransaction()
                .replace(R.id.container,
                        PlaceholderFragment.newInstance(position + 1)).commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
        case 1:
            mTitle = getString(R.string.title_section1);
            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            break;
        case 3:
            mTitle = getString(R.string.title_section3);
            break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Class<?> settings= SettingsActivity.class;
            StartIntent(settings);
        }
        return super.onOptionsItemSelected(item);
    }


//this method starts an intent with the class given to it   
    public void StartIntent(Class<?> intentclass) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, intentclass);            
        startActivity(intent);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(getArguments().getInt(
                    ARG_SECTION_NUMBER));


        }

    }

}

请记住,我对Android编码相对较新,所以错误可能是我忽略的极其简单的事情。

这可能是因为我最近使用了PagerSlidingTabStrip,但是在主要活动中没有使用PagerSlidingTabStrip。 HMM。

谢谢。

EDIT1 :发布styles.xml

值-V14:

<resources>

    <!--
        Base application theme for API 14+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v11/styles.xml on API 14+ devices.
    -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- API 14 theme customizations can go here. -->
    </style>

</resources>

值-V11:

<resources>

    <!--
        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.
    -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        <!-- API 11 theme customizations can go here. -->
    </style>

</resources>

值:     

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

EDIT2 :发布activity_main.xml

<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pipturner.timetable.MainActivity" >

    <!--
         As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions.
    -->
<FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:orientation="vertical" >

            <TextView
                android:id="@+id/lessons"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <Button
                android:id="@+id/homeworkbutton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0"
                android:text="@string/homework" />


            <TextView
                android:id="@+id/homeworktext"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

        </LinearLayout>

    </FrameLayout>
    <!--
         android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead.
    -->
    <!--
         The drawer is given a fixed width in dp and extends the full height of
         the container.
    -->

    <fragment
        android:id="@+id/navigation_drawer"
        android:name="com.pipturner.timetable.NavigationDrawerFragment"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        tools:layout="@layout/fragment_navigation_drawer" />


</android.support.v4.widget.DrawerLayout>

1 个答案:

答案 0 :(得分:0)

我通过创建具有更高API最低要求的新项目来解决此错误,然后将所有代码复制到新项目中。不知道为什么或如何运作但是啊。