Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Self-Destructing Message Android App Sending Messages Adding a Send Button

Charles Li
Charles Li
15,557 Points

NullPointerException for RecipientsActivity.onListItemClick! Please help!

Hello guys, I'm working on the Adding a Send Button lecture right now. After I added the onListItemClick method in RecipientsActivity.java, my app stopped running whenever I clicked on a friend to send a picture to (after choosing a picture).

My error message in Logcat is shown below:

01-11 17:34:34.769 31516-31516/com.charlesli.ribbit D/AndroidRuntime﹕ Shutting down VM 01-11 17:34:34.769 31516-31516/com.charlesli.ribbit W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41c452a0) 01-11 17:34:34.779 31516-31516/com.charlesli.ribbit E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException at com.charlesli.ribbit.RecipientsActivity.onListItemClick(RecipientsActivity.java:118) at android.app.ListActivity$2.onItemClick(ListActivity.java:319) at android.widget.AdapterView.performItemClick(AdapterView.java:301) at android.widget.AbsListView.performItemClick(AbsListView.java:1276) at android.widget.AbsListView$PerformClick.run(AbsListView.java:3067) at android.widget.AbsListView$1.run(AbsListView.java:3963) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898) 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:1006) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) at dalvik.system.NativeStart.main(Native Method)

This is my code (shown with *****) that have problems:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_recipients, menu);
    mSendMenuItem = menu.getItem(0);
    return true;
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    mSendMenuItem.setVisible(true);   *****this is line 118 where the problem occurs.****
}

I'm not able to make any other progress until I fix this so any help is much appreciated!! Thank You!

Charles Li
Charles Li
15,557 Points

This is my code in menu_recipients btw. Not sure if it has anything to do with it...

<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.charlesli.ribbit.RecipientsActivity"> <item android:id="@+id/action_send" android:title="@string/menu_send_label" android:orderInCategory="100" app:showAsAction="always" android:visible="false"/> </menu>

Ratul Sarna
Ratul Sarna
Courses Plus Student 11,618 Points

can you please paste the entire RecipientsActivity? and the complete menu_recipients.xml too. Thanks.

Charles Li
Charles Li
15,557 Points

Here is my entire code for RecipientsActivity.

package com.charlesli.ribbit;

import android.app.AlertDialog; import android.app.ListActivity; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.ListView;

import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseQuery; import com.parse.ParseRelation; import com.parse.ParseUser;

import java.util.List;

public class RecipientsActivity extends ListActivity {

public static final String TAG = RecipientsActivity.class.getSimpleName();

protected List<ParseUser> mFriends;
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;

protected MenuItem mSendMenuItem;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_recipients);

    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

@Override
public void onResume() {
    super.onResume();

    mCurrentUser = ParseUser.getCurrentUser();
    mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);

    setProgressBarIndeterminateVisibility(true);

    ParseQuery<ParseUser> query = mFriendsRelation.getQuery();
    query.addAscendingOrder(ParseConstants.KEY_USERNAME);
    query.findInBackground(new FindCallback<ParseUser>() {
        @Override
        public void done(List<ParseUser> friends, ParseException e) {
            setProgressBarIndeterminateVisibility(false);
            if (e == null) {
                mFriends = friends;

                String[] usernames = new String[mFriends.size()];
                int i = 0;
                for (ParseUser user : mFriends) {
                    usernames[i] = user.getUsername();
                    i++;
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                        getListView().getContext(), android.R.layout.simple_list_item_checked, usernames);
                setListAdapter(adapter);
            } else {
                Log.e(TAG, e.getMessage());
                AlertDialog.Builder builder = new AlertDialog.Builder(RecipientsActivity.this);
                builder.setMessage(e.getMessage());
                builder.setTitle(getString(R.string.error_title));
                builder.setPositiveButton(android.R.string.ok, null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_recipients, menu);
    mSendMenuItem = menu.getItem(0);
    return true;
}

@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();

    //noinspection SimplifiableIfStatement
    //if (id == R.id.action_settings) {
    //    return true;
    //}

    //return super.onOptionsItemSelected(item);


    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    // I added this if statement to prevent the app from crashing. It wasn't there before.
    if (mSendMenuItem == null) {
        Log.i(TAG, "mSendMenuItem is null. Fix it please."); 
    }
    else {
        mSendMenuItem.setVisible(true);
    }


}

}

Charles Li
Charles Li
15,557 Points

Here is my code for menu_recipients.xml. Thank you so much for your time Ratul!

<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.charlesli.ribbit.RecipientsActivity"> <item android:id="@+id/action_send" android:title="@string/menu_send_label" android:orderInCategory="100" app:showAsAction="always" android:visible="false" android:icon="@drawable/ic_action_send_now"/> </menu>

Charles Li
Charles Li
15,557 Points

I'm using Android Studio btw.

Ratul Sarna
Ratul Sarna
Courses Plus Student 11,618 Points

A couple more questions? Are you using the latest version of android studio (1.0+)? And if so, does your action bar appear when this activity is launched?

Charles Li
Charles Li
15,557 Points

I'm using Android Studio 1.0.2 and my action bar doesn't appear in the Edit Friends/Recipients Activity section.

1 Answer

Charles Li
Charles Li
15,557 Points

Hi Ratul, Thanks for your help first of all! I went to that thread and tried out Billy Ashmall's method and the Action Bar did appear afterwards. But it still doesn't fix my original problem with regards to the onListItemClick. There wasn't a null exception now, but the Send Icon still doesn't appear. I then tried out your method and I still couldn't see the Action Bar (I'm not too worried about this right now, because I just want to be able to progress through the lectures now). But most importantly the null exception still exists. I still don't know why mSendMenuItem is still null after I set it up in onCreateOptionsMenu like the instructor.

Thanks again tho!!

Charles Li
Charles Li
15,557 Points

Actually now that I tested again on a Nexus 4 Android emulator, it kinda works using Billy Ashmall's method. The send button now appears part of the action bar but it is hidden. I'm not sure what it's called but there's this 3 dots icon which I have to press for the "Send" option to pop up. I set an icon but I'm not sure why it doesn't appear and why this option is not visibly on the action bar right away.

If I test it on my S3 device, it doesn't even appear on the Action Bar. I have to press on an icon on the phone itself for it to appear. It's also in the form of a text, "Send".