为什么getActionBar()在Android的TabHost中获得空值?

时间:2014-05-24 13:47:04

标签: android nullpointerexception android-actionbar android-tabactivity

我正在尝试在Android中编写代码,以在向下滚动事件期间隐藏Actionbar。我有一个10x50的网格。因此,当我向下滚动时,操作栏应该隐藏。我正确地在Log Cat中获得滚动状态结果,所以每当我申请getActionBar()时,我都会收到NullPointerException错误。

我的代码:

package com.example.complexdatepicker;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class MainActivity extends TabActivity 
{

@Override
protected void onCreate(Bundle savedInstanceState) 
{


        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        TabHost tabHost = getTabHost();


        TabSpec tab1 = tabHost.newTabSpec("Home");

        tab1.setIndicator("Home");
        Intent photosIntent = new Intent(this, Home.class);
        tab1.setContent(photosIntent);

        tabHost.addTab(tab1);


}

 }

Home.java

package com.example.complexdatepicker;

import java.util.ArrayList;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.GridView;


public class Home extends ActionBarActivity 
{

ArrayList<String> abc;

TestGrid tg;

GridView gv;

int mLastFirstVisibleItem;

int mLastVisibleItemCount;

@Override
protected void onCreate(Bundle savedInstanceState) 
{


        super.onCreate(savedInstanceState);

        setContentView(R.layout.home);

        gv = (GridView) findViewById(R.id.gridView1);

        abc = new ArrayList<String>();

        for(int i=0;i<500;i++)
        {

            abc.add(String.valueOf(i));

        }


        tg = new TestGrid(Home.this,Home.this,abc);

        gv.setAdapter(tg);

        getSupportActionBar().hide(); /// Getting Error at this point..


     /*         
        gv.setOnScrollListener(new AbsListView.OnScrollListener() {
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (mLastFirstVisibleItem > firstVisibleItem) {
                    Log.e(getClass().toString(), "scrolling up");
                    getActionBar().show();
                } else if (mLastFirstVisibleItem < firstVisibleItem) {
                    Log.e(getClass().toString(), "scrolling down");
                    getActionBar().hide();

                } else if (mLastVisibleItemCount < visibleItemCount) {
                    Log.e(getClass().toString(), "scrolling down");
                    getActionBar().hide();
                } else if (mLastVisibleItemCount > visibleItemCount) {
                    Log.e(getClass().toString(), "scrolling up");
                    getActionBar().show();
                }
                mLastFirstVisibleItem = firstVisibleItem;
                mLastVisibleItemCount = visibleItemCount;
            }

            public void onScrollStateChanged(AbsListView listView, int scrollState) {
            }
        });

     */         

}

 }

TestGrid.java

package com.example.complexdatepicker;
import java.util.ArrayList;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

public class TestGrid extends BaseAdapter
{

    private ArrayList<String> abc;

    private FragmentActivity activity;

    private Context context; 

    String text;

    int c = 0;

    int x = 0;

    SelectDateFragment newFragment;



    public TestGrid(FragmentActivity activity , Context cont,ArrayList<String> abc)
    {

        super();

        this.activity=activity;

        this.context = cont;

        this.abc = abc;

    }

    @Override
    public int getCount() 
    {

        return abc.size();

    }

    @Override
    public Object getItem(int in) 
    {       

        return abc.get(in);

    }

    @Override
    public long getItemId(int arg0) 
    {

        return 0;

    }

    public class ViewHolder
    {

        public TextView txt;

    }


    @Override
    public View getView(final int arg0, View arg1, ViewGroup arg2) 
    {

        final SharedPreferences pref = context.getApplicationContext().getSharedPreferences("TestDate", 0);

        ViewHolder view;

        LayoutInflater inflator = activity.getLayoutInflater();

        if(arg1==null)
        {

            view = new ViewHolder();

            arg1 = inflator.inflate(R.layout.test_grid, null);

            view.txt = (TextView) arg1.findViewById(R.id.txt);

            arg1.setTag(view);

        }
        else
        {

            view = (ViewHolder) arg1.getTag();

        }





         View.OnClickListener alert = new OnClickListener() 
         {


                public void onClick(View v) 
                {


                        Toast.makeText(activity.getApplicationContext(), abc.get(arg0)+" - Clicked ", Toast.LENGTH_SHORT).show();


                    newFragment = new SelectDateFragment();

                    Bundle args = new Bundle();

                    newFragment.setArguments(args);


                    newFragment.setOnDateSetListener(new DatePickerDialog.OnDateSetListener()
                    {

                        @Override
                        public void onDateSet(DatePicker view, int yy, int mm, int dd)
                        {

                            String saved_date = pref.getString("SavedDate", null);

                            Toast.makeText(activity.getApplicationContext(), "SavedDate : "+saved_date,Toast.LENGTH_LONG).show(); 


                        }


                    });



                    newFragment.show(activity.getSupportFragmentManager(), "DatePicker");       

                }


         };



        view.txt.setOnClickListener(alert);






        text = String.valueOf(abc.get(arg0));

        view.txt.setBackgroundResource(R.drawable.txtbk);

        view.txt.setTextSize(18);

        view.txt.setTextColor(Color.BLACK);

        view.txt.setGravity(Gravity.CENTER);    

        view.txt.setText(text);

        return arg1;

    }




    @SuppressLint({ "ValidFragment", "NewApi" })
    public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener 
    {


        private DatePickerDialog.OnDateSetListener externalListener;

        public void setOnDateSetListener(DatePickerDialog.OnDateSetListener listener)
        {
            this.externalListener = listener;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) 
        {


                final Calendar calendar = Calendar.getInstance();

                int yy = calendar.get(Calendar.YEAR);

                int mm = calendar.get(Calendar.MONTH);

                int dd = calendar.get(Calendar.DAY_OF_MONTH);

                return new DatePickerDialog(getActivity(), this, yy, mm, dd);


        }


        public void onDateSet(DatePicker view, int yy, int mm, int dd)
        {

            SharedPreferences pref = context.getApplicationContext().getSharedPreferences("TestDate", 0);

            Editor et = pref.edit();

            et.putString("SavedDate", String.valueOf(dd+"/"+mm+"/"+yy));

            et.commit();

            Log.d("SavedDate : ", String.valueOf(dd+"/"+mm+"/"+yy));

            if(externalListener != null)


                externalListener.onDateSet(view, yy, mm, dd);




        }


        public void onFinishEditDialog(String inputText) 
        {



        }


    }


}

的AndroidManifest.xml

   <manifest 
     xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.complexdatepicker"
     android:versionCode="1"
     android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="14"
      android:targetSdkVersion="17" />

  <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/Theme.AppCompat" >

 <activity

        android:name="com.example.complexdatepicker.MainActivity"
        android:label="@string/app_name" >

     <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="com.example.complexdatepicker.Home"
        android:label="@string/app_name" ></activity>

 </application>

Style.xml

<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="android:Theme.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>

错误图片:

enter image description here

错误:

05-25 11:10:37.374: E/AndroidRuntime(872): FATAL EXCEPTION: main
05-25 11:10:37.374: E/AndroidRuntime(872): java.lang.RuntimeException: Unable to start  activity ComponentInfo{com.example.complexdatepicker/com.example.complexdatepicker.MainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.complexdatepicker/com.example.complexdatepicker.Home}: java.lang.NullPointerException
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.os.Looper.loop(Looper.java:137)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.main(ActivityThread.java:5103)
05-25 11:10:37.374: E/AndroidRuntime(872):  at java.lang.reflect.Method.invokeNative(Native Method)
05-25 11:10:37.374: E/AndroidRuntime(872):  at java.lang.reflect.Method.invoke(Method.java:525)
05-25 11:10:37.374: E/AndroidRuntime(872):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-25 11:10:37.374: E/AndroidRuntime(872):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-25 11:10:37.374: E/AndroidRuntime(872):  at dalvik.system.NativeStart.main(Native Method)
05-25 11:10:37.374: E/AndroidRuntime(872): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.complexdatepicker/com.example.complexdatepicker.Home}: java.lang.NullPointerException
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.startActivityNow(ActivityThread.java:2054)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.widget.TabHost.setCurrentTab(TabHost.java:413)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.widget.TabHost.addTab(TabHost.java:240)
05-25 11:10:37.374: E/AndroidRuntime(872):  at com.example.complexdatepicker.MainActivity.onCreate(MainActivity.java:42)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.Activity.performCreate(Activity.java:5133)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
05-25 11:10:37.374: E/AndroidRuntime(872):  ... 11 more  
05-25 11:10:37.374: E/AndroidRuntime(872): Caused by: java.lang.NullPointerException
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.support.v7.app.ActionBarImplICS.hide(ActionBarImplICS.java:289)
05-25 11:10:37.374: E/AndroidRuntime(872):  at com.example.complexdatepicker.Home.onCreate(Home.java:50)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.Activity.performCreate(Activity.java:5133)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-25 11:10:37.374: E/AndroidRuntime(872):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
05-25 11:10:37.374: E/AndroidRuntime(872):  ... 21 more

这些都是上面的代码和错误详情,请告诉我如何在 TabWidget 中使用 getActionBar()

请建议我一些好的解决方案。

1 个答案:

答案 0 :(得分:7)

您的主页Activity必须延长ActionBarActivity而不是FragmentActivity,以便您可以调用getActionBar()方法。

ActionBarActivity延伸FragmentActivity。此外,您应该使用getSupportActionBar()而不是getActionBar(),因为最新版本需要API级别11。

另请注意,您需要导入v4支持库才能调用getSupportActionBar()并支持v7库以使用ActionBarActivity