4

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:

enter image description here

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.

user3668350
  • 73
  • 1
  • 9

1 Answers1

7

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.

joao2fast4u
  • 6,868
  • 5
  • 28
  • 42
  • Yes brother i am doing everything right in the app manifest but don't find any reason ... why i am getting this exception... – user3668350 May 24 '14 at 15:39
  • Try to clean your project and run it again, then. – joao2fast4u May 24 '14 at 15:44
  • I have edited my post ... why i am getting a red symbol in my project folder after adding the v7 libraries into my app ... so i am not able to run my app now.... – user3668350 May 24 '14 at 15:44
  • I have cleaned my project but nothing changed ... still having red exclamation in my project folder... please let me know... – user3668350 May 24 '14 at 15:47
  • Is your v7-appcompat library project ok, with no errors? Did you check it as library? – joao2fast4u May 24 '14 at 15:48
  • When you go to your Project properties, are you importing the right library? – joao2fast4u May 24 '14 at 15:53
  • i think so ... i got v7 library from my sdk extras->android->support-v7->appcompat-> and i imported this project.. and i add this as library to my project.... – user3668350 May 24 '14 at 15:57
  • In Eclipse, you have a View called Problems. Check that section to see if any message helps you. – joao2fast4u May 24 '14 at 15:57
  • No friend not finding any issue from Problems view ... what's actual issue ? please suggest me.... – user3668350 May 24 '14 at 16:16
  • Try to clean your v7 library, and import it again. – joao2fast4u May 24 '14 at 16:17
  • Ahh now i get it ...in android-support-v7-appcompat folder there is no java file inside the src folder , so what can i do now... where do i get all the source java files.... – user3668350 May 24 '14 at 16:19
  • No, it is supposed not to have any classes in src folder. Check if libs folder has the v4 and v7 jars. And check your project build target correctly. – joao2fast4u May 24 '14 at 16:39
  • Nope i tried a lot but nothing great i found ... please suggest me how can i overcome this problem...? can sherlock could be a good option...? – user3668350 May 25 '14 at 13:32
  • Well, Sherlock is also a library. Eventually, you'll have the same problem. Your problem is importing a library. Does not have to do with the library itself, I think. Did you tried to do the whole process again? Are you importing the library from the right directory? – joao2fast4u May 25 '14 at 13:37
  • Let's try another approach. Create a new Android project, and on the new Project wizard,set minimum sdk to 11, the click Next, then choose master/detail flow. That project will automatically import appcompat v7 library. Then try to import your new v7 library into your own project. – joao2fast4u May 25 '14 at 13:47
  • No friend same result ... i created new project with minimum sdk to 11 and done master/detail flow ... but still getting error in getActionBar().hide.... getting NullPointerException at this point... i didn't add v7 library this time.... – user3668350 May 25 '14 at 14:12
  • Yes, but for it to work, you got to add it as library. And what about the new project? Does it work? Does it have an actionbar? – joao2fast4u May 25 '14 at 14:29
  • One more thing, could you show your styles.xml file. So I can see which Theme you have on your application? – joao2fast4u May 25 '14 at 14:30
  • No friend getting NullPointerException at getActionBar().hide... nothing working at all.... – user3668350 May 25 '14 at 14:32
  • yes sure i have edited my post , please go through my style.xml file – user3668350 May 25 '14 at 14:37
  • You have to change your Manifest.xml, in tag application, to android:theme="@style/Theme.AppCompat". This theme is in v7-appcompat library. You have to import it to your project. Compare with the project you just created and see why is the reason it works and your project not. – joao2fast4u May 25 '14 at 14:57
  • Yes i have added the Theme.AppCompat in the manifest but getting some new exception now... i have edited my post ... please go through my Errors ... – user3668350 May 25 '14 at 15:18
  • You mean you managed to import v7-appcompat in your project without errors? If not, try importing actionbarsherlock – joao2fast4u May 25 '14 at 17:05
  • Yes i managed to import v7 libraries without errors... but having exception still now.... – user3668350 May 25 '14 at 17:24
  • Ok then. Did you try to check if getSupportActionBar() != null before you make the call? – joao2fast4u May 25 '14 at 22:33
  • Also, try to do some research, there are lots of cases like yours. Check this, for a start: http://stackoverflow.com/questions/20147921/actionbaractivity-getsupportactionbar-hide-throws-nullpointerexception. Also, try to change your application theme to android:Theme.Holo.Light instead. – joao2fast4u May 25 '14 at 22:38
  • And what about your Styles.xml file in values-v11 and values v-14? You have to set an AppCompat Theme there also. – joao2fast4u May 25 '14 at 22:43
  • Also check this: http://developer.android.com/guide/topics/ui/actionbar.html#Adding. Hope it helps :D – joao2fast4u May 25 '14 at 22:45
  • Ahh No Friend , i think i need deep breath and will start from the beginning. I think Inside tabhost the loaded Activity not manage to find any Actionbar from the Parent Activity , that's why it's giving NullPointerException ..... – user3668350 May 29 '14 at 10:25
  • The loaded Activity has its own ActionBar. Does not need to get it from the Parent Activity. THe problem must be different. – joao2fast4u May 29 '14 at 10:29
  • So i want to Hide the Parent Activity ActionBar from the Tabhost activity , so how i can do it ? – user3668350 May 29 '14 at 10:31
  • Yes but how can i hide it's ActionBar from Home.java while doing upside scrolling.... – user3668350 May 29 '14 at 10:46
  • For that, you may take a different approach. See this post: http://stackoverflow.com/questions/13559275/hiding-the-actionbar-on-listview-scroll. It is exactly what you want. – joao2fast4u May 29 '14 at 10:57
  • Oh!! Friend that i know properly , if the scrolling code will in a tabhost then how can i hide the ActionBar of Parent Activity? Normally In the scrolling Up or Down the actionbar got hide but while i am doing from TabHost it showing an NullPointerException .... – user3668350 May 29 '14 at 11:01
  • It may be a bug in ActionBarImplICS class. mActionBar value is null. Hiding it or showing it returns null. You may also consider that TabActivity is deprecated. Its use is not recommended. – joao2fast4u May 29 '14 at 12:38