-3

I have used toolbar for as my title bar for all the activity. Now one of my class need to use getActionBar().setDisplayHomeAsUpEnabled(true); and here comes the error .The question is how to replace getActionBar().setDisplayHomeAsUpEnabled(true); to other option. I have tried getSupportActionBar()but it gives an error. This is the logcat error:

/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.foo.isfoo, PID: 2426
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.foo.isfoo/com.example.foo.isfoo.ListOfFriends}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

This is part of my code, I have shorten my code:

    public class ListOfFriends extends ListActivity{

    private Manager imService = null;
    private FriendListAdapter friendAdapter;

    public String ownusername = new String();

    private class FriendListAdapter extends BaseAdapter {
        class ViewHolder {
            TextView text;
            ImageView icon;
        }

        private LayoutInflater mInflater;
        private Bitmap mOnlineIcon;
        private Bitmap mOfflineIcon;

        private InfoOfFriend[] friends = null;

        public FriendListAdapter(Context context) {
            super();

            mInflater = LayoutInflater.from(context);

            mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.online);
            mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.offline);

        }

        public void setFriendList(InfoOfFriend[] friends) {
            this.friends = friends;
        }

        public int getCount() {

            return friends.length;
        }

        public InfoOfFriend getItem(int position) {

            return friends[position];
        }

        public long getItemId(int position) {

            return 0;
        }

        @SuppressLint("InflateParams")
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid
            // unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is
            // no need
            // to reinflate it. We only inflate a new View when the convertView
            // supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.friend_list_screen, null);

                // Creates a ViewHolder and store references to the two children
                // views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            holder.text.setText(friends[position].userName);
            holder.icon.setImageBitmap(friends[position].status == InfoStatus.ONLINE ? mOnlineIcon : mOfflineIcon);

            return convertView;
        }

    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.i("Broadcast receiver ", "received a message");
            Bundle extra = intent.getExtras();
            if (extra != null) {
                String action = intent.getAction();
                if (action.equals(MessagingService.FRIEND_LIST_UPDATED)) {
                    // taking friend List from broadcast
                    // String rawFriendList =
                    // extra.getString(FriendInfo.FRIEND_LIST);
                    // FriendList.this.parseFriendInfo(rawFriendList);
                    ListOfFriends.this.updateData(ControllerOfFriend.getFriendsInfo(),
                            ControllerOfFriend.getUnapprovedFriendsInfo());

                }
            }
        }

    };

    public MessageReceiver messageReceiver = new MessageReceiver();

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            imService = ((MessagingService.IMBinder) service).getService();

            InfoOfFriend[] friends = ControllerOfFriend.getFriendsInfo(); // imService.getLastRawFriendList();
            if (friends != null) {
                ListOfFriends.this.updateData(friends, null); // parseFriendInfo(friendList);
            }

            setTitle(imService.getUsername() + "'s friend list");
            ownusername = imService.getUsername();
        }

        public void onServiceDisconnected(ComponentName className) {
            imService = null;
            Toast.makeText(ListOfFriends.this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.list_friends);
//error here
        getActionBar().setDisplayHomeAsUpEnabled(true);
        friendAdapter = new FriendListAdapter(this);

    }

    public void updateData(InfoOfFriend[] friends, InfoOfFriend[] unApprovedFriends) {
        if (friends != null) {
            friendAdapter.setFriendList(friends);
            setListAdapter(friendAdapter);
        }

        if (unApprovedFriends != null) {
            NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            if (unApprovedFriends.length > 0) {
                String tmp = new String();
                for (int j = 0; j < unApprovedFriends.length; j++) {
                    tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
                }
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.notification)
                        .setContentTitle(getText(R.string.new_friend_request_exist));
                /*
                 * Notification notification = new
                 * Notification(R.drawable.stat_sample,
                 * getText(R.string.new_friend_request_exist),
                 * System.currentTimeMillis());
                 */

                Intent i = new Intent(this, WaitingListFriends.class);
                i.putExtra(InfoOfFriend.FRIEND_LIST, tmp);

                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);

                mBuilder.setContentText("You have new friend request(s)");
                /*
                 * notification.setLatestEventInfo(this,
                 * getText(R.string.new_friend_request_exist),
                 * "You have new friend request(s)", contentIntent);
                 */

                mBuilder.setContentIntent(contentIntent);

                NM.notify(R.string.new_friend_request_exist, mBuilder.build());
            } else {
                // if any request exists, then cancel it
                NM.cancel(R.string.new_friend_request_exist);
            }
        }

    }

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

        super.onListItemClick(l, v, position, id);

        Intent i = new Intent(this, PerformingMessaging.class);
        InfoOfFriend friend = friendAdapter.getItem(position);
        i.putExtra(InfoOfFriend.USERNAME, friend.userName);
        i.putExtra(InfoOfFriend.PORT, friend.port);
        i.putExtra(InfoOfFriend.IP, friend.ip);
        startActivity(i);
    }

    @Override
    protected void onPause() {
        unregisterReceiver(messageReceiver);
        unbindService(mConnection);
        super.onPause();
    }

    @Override
    protected void onResume() {

        super.onResume();
        bindService(new Intent(ListOfFriends.this, MessagingService.class), mConnection,
                Context.BIND_AUTO_CREATE);

        IntentFilter i = new IntentFilter();
        // i.addAction(IMService.TAKE_MESSAGE);
        i.addAction(MessagingService.FRIEND_LIST_UPDATED);

        registerReceiver(messageReceiver, i);

    }

    @Override
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        // TODO Auto-generated method stub
        getMenuInflater().inflate(R.menu.addfriend_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.add_friend:
                Intent i = new Intent(ListOfFriends.this, FriendAdder.class);
                startActivity(i);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        imService.exit();
        Intent i = new Intent(ListOfFriends.this, stu_homepage.class);
        startActivity(i);
        finish();
    }
}
Kleorence
  • 23
  • 5
  • toolbar is not configured as actionbar in your code. Use following api **setSupportActionBar(toolbar)** for android.support.v7.widget.Toolbar with **AppcompatActivity** or **setActionBar(toolbar)** for android.widget.Toolbar. – John Ruban Singh Oct 06 '17 at 13:21

2 Answers2

1

EDIT: ListActivity do not extend AppCompatActivity So you will have to use getActionBar(), setActionBar() and android.widget.Toolbar. Also you have to use minimum api level 21 using minSdkVersion 21 in the build.gradle file.

OLD Answer:

Before using getActionBar() you should set your Toolbar as the action bar.

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setActionBar(toolbar); 

//now you can use the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);;

Note: If your activity extends AppCompatActivity, you should use the methods setSupportActionBar and getSupportActionBar

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
0

ListActivity is wrong here. You should use AppCompatActivity to access this API. For list of items it's recommended to use RecyclerView.

For this particular code you provided Android Studio gives a hint "Possible NullPointer" so you should check for null before you calling some methods.

Viktor Yakunin
  • 2,927
  • 3
  • 24
  • 39
  • There is still other code in this class. If i changed to AppCompatActivity there is an error with my setListAdapter. – Kleorence Oct 06 '17 at 11:31
  • @Kleorence That is a different issue, to see how whole sample could be done you can visit https://stackoverflow.com/questions/40584424/simple-android-recyclerview-example – Viktor Yakunin Oct 06 '17 at 11:42