Why getActionBar() getting null value in TabHost from Android?

為{幸葍}努か 提交于 2019-12-05 01:18:17

问题


I am trying to write a code in Android , to hide the Actionbar during scroll down event. I have a grid 10x50. So when i am scrolling down the action bar should hide. I am getting scroll state result in the Log Cat correctly so , whenever i am applying for getActionBar().hide , i am getting NullPointerException error.

My Code :

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>

Error Image:

Error :

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

These are all above codes and error details , please let me know how can i use getActionBar() in TabWidget.

Please suggest me some good solution.


回答1:


Your Home Activity must extend ActionBarActivity instead of FragmentActivity so you can call getActionBar() method.

ActionBarActivity extends FragmentActivity. Also, you should use getSupportActionBar() instead of getActionBar() because the latest requires API level 11.

Also note that you need to import v4 support library to be able to call getSupportActionBar() and support v7 library to use ActionBarActivity.



来源:https://stackoverflow.com/questions/23845738/why-getactionbar-getting-null-value-in-tabhost-from-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!