替换getActionBar()。setDisplayHomeAsUpEnabled(true);

时间:2017-10-06 11:16:02

标签: android

我使用工具栏作为所有活动的标题栏。现在我的一个班级需要使用getActionBar().setDisplayHomeAsUpEnabled(true);,这就出现了错误。问题是如何将getActionBar().setDisplayHomeAsUpEnabled(true);替换为其他选项。我试过了getSupportActionBar(),但是它出错了。这是logcat错误:

/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

这是我的代码的一部分,我缩短了我的代码:

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

2 个答案:

答案 0 :(得分:1)

修改 ListActivity不延长AppCompatActivity因此您必须使用getActionBar()setActionBar()android.widget.Toolbar。此外,您必须使用minSdkVersion 21文件中的build.gradle使用最低api级别21。

OLD答案:

在使用getActionBar()之前,您应将工具栏设置为操作栏。

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

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

注意:如果您的活动扩展了AppCompatActivity,您应该使用方法setSupportActionBargetSupportActionBar

答案 1 :(得分:0)

ListActivity在这里是错误的。您应该使用AppCompatActivity来访问此API。对于建议使用RecyclerView的项目列表。

对于您提供的特定代码,Android Studio提供了一个提示&#34;可能的NullPointer&#34;所以你应该在调用某些方法之前检查null。