MenuInflater NullPointerException (NPE)

I just recently published my first app on Google Play, and after I had published it I was playing with it on my Galaxy S3 and it crashed when I tried to delete a page. I know I had this working correctly on my Nexus 7 prior to publishing it, but I didn’t test it on my phone (shame on me :(). So, I went to work trying to figure out what the problem was, and here’s part of the stack trace:

	at com.actionbarsherlock.view.MenuInflater.inflate(MenuInflater.java:109)
	at com.test.app.SomeFragment.onCreateOptionsMenu(SomeFragment.java:1921)
	at android.support.v4.app.Watson.onCreatePanelMenu(Watson.java:55)
	at com.actionbarsherlock.ActionBarSherlock.callbackCreateOptionsMenu(ActionBarSherlock.java:559)
	at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchCreateOptionsMenu(ActionBarSherlockNative.java:65)
	at com.actionbarsherlock.app.SherlockFragmentActivity.onCreatePanelMenu(SherlockFragmentActivity.java:165)
	at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:446)
	at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:820)
	at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchInvalidateOptionsMenu(ActionBarSherlockNative.java:52)
	at com.actionbarsherlock.app.SherlockFragmentActivity.invalidateOptionsMenu(SherlockFragmentActivity.java:150)
	at com.actionbarsherlock.app.SherlockFragmentActivity.supportInvalidateOptionsMenu(SherlockFragmentActivity.java:156)
	at android.support.v4.app.Fragment.setHasOptionsMenu(Fragment.java:763)
	at com.test.app.SomeFragment.onCreate(SomeFragment.java:190)
	at android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
	at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
	at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
	at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
	at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
	at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
	at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
	at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:548)
	at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:507)
	at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:905)
	at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2772)
	at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
	at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
	at com.test.app.SomeActivity.updateView(SomeActivity.java:624)
	at com.test.app.SomeActivity$LoadInfo.onPostExecute(SomeActivity.java:353)
	at com.test.app.SomeActivity$LoadInfo.onPostExecute(SomeActivity.java:1)
	at android.os.AsyncTask.finish(AsyncTask.java:631)
	at android.os.AsyncTask.access$600(AsyncTask.java:177)
	at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loop(Looper.java:137)
	at android.app.ActivityThread.main(ActivityThread.java:4950)
	at java.lang.reflect.Method.invokeNative(Native Method)
	at java.lang.reflect.Method.invoke(Method.java:511)
	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
	at dalvik.system.NativeStart.main(Native Method)

After checking the stack trace and doing some research, I narrowed it down to an issue with setHasOptionsMenu(true) and I thought it might be a problem with the ActionBarSherlock Library. Well, I stumbled upon this post and found that setHasOptionsMenu(true) was set in onActivityCreated(). I had set it in onCreate(), since when I had looked at how to use it that’s where everyone seemed to put it…at least in the posts I looked at. Well, it was already broken, so I had nothing to lose and the other stuff I had tried didn’t fix it. I moved setHasOptionsMenu(true) from onCreate() to OnActivityCreated() and then ran a test. Bingo! That fixed the problem on my phone! I tested on my other two tablets (Nexus 7 and Motorola Xoom) and it worked like it should on both of those as well.

Anyway, just throwing this out there in case anyone else runs into this problem.

Android Tutorial: Implementing a Drag and Sort ListView with a Database

I’m working on an app and got to the point where I wanted to implement a drag and drop ListView that allows re-ordering, adding and deleting of list items using a database. I didn’t think that it would be all that difficult. However, with my limited experience with Android, it turned out to be a bit of a pain to get working. But, now that I have it working I figured I’d post some example code so that others can take advantage of what I learned and hopefully have an easier time getting this implemented.

My initial searches had me stumble upon DragSortListView (DSLV) by Carl A. Bauer. I was excited to find something that looked so polished, and it appeared pretty easy to implement. After digging into the demo code (available from above link) and playing with the demo app (available as app on Google Play), I thought I had a pretty good idea of what I needed to do to get it working. Unfortunately, I just couldn’t get it to work with a database. I could get the items to display correctly and then I could drag them around to re-arrange the order and swipe to delete them, but I couldn’t figure out how to save any of that in the database.

As part of my trials, I posted what I thought was an issue on the DSLV GitHub site. Turns out that it’s not an issue, just a misunderstanding on my part. But, through the discussion of that issue I figured out how to get it to work. YEAH!

The SimpleDragSortCursor adapter class provides most of the muscle to get things up and running. The difficult part was to get it to correctly update the database. Read on to find out how I got it working.

To get started, I based my test app on the CursorDSLV.java class from the DSLV demo. I already had a database class that I was using (DatabaseAdapter.java), so I modified it a little for this test app (it’s available in the demo code you can download on GitHub). Next, I ended up creating my own method to setup the ListView and configure click and long-click actions. Here’s what I put together:

private void displayItemList() {
	// The desired columns to be bound
	String[] columns = new String[] { DatabaseAdapter.ITEM_NAME,
			DatabaseAdapter.ITEM_POSITION };

	// the XML defined views which the data will be bound to
	int[] ids = new int[] { R.id.item_name, R.id.item_position_list };

	// pull all items from database
	Cursor cursor = mDbHelper.getAllItemRecords();

	mMAdapter = new MAdapter(this, R.layout.list_items, null, columns, ids,

	mDslv = (DragSortListView) findViewById(R.id.item_list);

	// set dslv profile for faster scroll speeds


	mDslv.setOnItemClickListener(new OnItemClickListener() {
		public void onItemClick(AdapterView<?> listView, View view,
				int position, long id) {
			// Get the cursor, positioned to the corresponding row in the
			// result set
			Cursor cursor = (Cursor) listView.getItemAtPosition(position);

			// Get the item name and details from this row in the database.
			String itemName = cursor.getString(cursor
			String itemDetails = cursor.getString(cursor
					itemName + ": " + itemDetails, Toast.LENGTH_SHORT)

	mDslv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
		public boolean onItemLongClick(AdapterView<?> listView, View view,
				int position, long id) {
			// Get the cursor, positioned to the corresponding row in the
			// result set
			Cursor cursor = (Cursor) listView.getItemAtPosition(position);

			// Get the item name and details from this row in the database.
			long rowId = cursor.getLong(cursor.getColumnIndex("_id"));
			return true;

Replacing the similar lines in the CursorDSLV.java class with this method allowed me to display the list of items from the database and drag them around and click the red X to delete them. However, I wanted to be able to swipe to delete, put the drag handle on the right and get rid of the red X. I ended up doing a straight swap for some of the layout files (in CursorDSLV.java):

  • Used warp_main.xml instead of cursor_main.xml in order to get swipe to remove working:
  • Changed the layout file for the actual details view from list_item_click_remove.xml to list_item_handle_right.xml in order to move the drag handle to the right of the screen:
adapter = new MAdapter(this,
        R.layout.list_item_handle_right, null, cols, ids, 0);

After those changes, I had the desired look and actions setup. Now all I needed to do was get the changes to actually save in the database. In order to do that I first came up with my own way, but then Carl set me straight and I used the built-in DragSortCursorAdapter methods. I added the following persistChanges method to the MAdapter class in order to create a method that I could use to save the changes (here’s a snippet):

private class MAdapter extends SimpleDragSortListAdapter {
    // ...

    public void persistChanges() {
        Cursor c = getCursor();
        while (c.moveToNext()) {
            int listPos = getListPosition(c.getPosition());
            if (listPos == DragSortListAdapter.REMOVED) {
            } else if (listPos != c.getPosition()) {
                dbAdapter.updateItemPosition(c.getInt(c.getColumnIndex("_id")), listPos);

I thought I was doing really well, but I wasn’t sure where I should call the above method to get it to actually save the data correctly. Carl said that I should call it at the activity level and suggested that I put it in the onPause() method. DUH! Made sense to me. Here’s what Carl suggested:

protected void onPause() {

Yeah! Now I had a working example that would successfully save the changes whenever the back button was pressed. Saving the changes in the onPause() method might not be ideal, so feel free to play around with where you call it so it works best for your application.

The above code is just to illustrate the basic steps to wire up DSLV to work with a database. I put together a more comprehensive demo app that implements what’s talked about above using a SQLite database. The app allows you to add/edit/remove/sor items to experiment with DragSortListView. You can download it from GitHub and play around with it. The app uses ActionBarSherlock, so you’ll have to download it as well as the DragSortListView library and make sure your project is configured correctly to use these libraries.

Hopefully this helps make implementing Drag and Sort ListViews easier for you.

Android Tutorial: Implement A Shake Listener

So I’ve been playing around with Android and have a little app that I wanted the user to be able to shake the phone and have something happen. I did some digging and the following is a tutorial on how to setup a shake listener to capture a shake and then do whatever you want.

This is by no means something that I’ve created, I just used examples that I found on stackoverflow.com. Also, this uses G-force to calculate the shake threshold. Many thanks to Peterdk and Akos Cz for their input and answer for this solution. Peterdk recommended using the G-Force app by Blake La Pierre on Google Play Store if you want to get the actual G-force value on your phone and tweak it in the code below.

Long story short, there are 5 things that need to happen to get this to work:

  1. Create a new class named ShakeDetector
  2. Define variables for sensor manager, shake detector and accelerometer
  3. Add/register the sensor manager and listener in the onCreate() method in your activity
  4. Configure onResume and onPause to activate/deactivate the accelerometer
  5. Edit the AndroidManifest.xml file to require the device to have an accelerometer

Continue reading

HTC “Droid” Incredible Review

My First Impressions

I’ve got my first Android phone and, long story short: I’m loving it.

Why make the switch to Android now? Read on…

I’ve owned WinMo phones forever because I wasn’t willing to switch to another carrier and Verizon hasn’t had a compelling phone to offer until now. Yes, the Moto Droid was a contender but I think it’s ugly and after demoing it in the store a couple times I just didn’t like it. I was waiting for the Nexus One, but the Incredible came out first, has a better camera and a better screen (no multi-touch issues like the N1). So, April 29th arrived and I called the Verizon store where I live and asked that they reserve one for me. I didn’t care that I still had about 6 months until my “New every two”. Shelling out a little extra to get rid of my Samsung Omnia i910 was well worth it. That phone was driving me nuts!

OK, so on to the Incredible. I really liked the responsiveness of the touch screen. Swiping through the home screens and using the “Leap” view made me a little giddy. Getting email setup was easy. Customizing the home screens was also easy and there are plenty of widgets to keep anyone busy. It’s nice that there are several customized Scenes that you can choose from. And, once you get a layout setup that you like you can save it. With so much to customize, I still haven’t figured out what I like best.

Below is my two cents on the HTC Incredible based on a few weeks of use. I won’t go over FriendStream or how the HTC Sense UI tries to integrate all of your contact info, because that’s discussed all over the Internet. I actually like it, others don’t. Although, there’s no way to turn it off on the HTC Droid Incredible.

Continue reading

© 2020 Jason McReynolds

Theme by Anders NorénUp ↑