java.lang.ArrayIndexOutOfBoundsException:length = 2;索引= 2

时间:2015-01-22 10:00:07

标签: java

嗨,在下面的代码中我得到了数组索引超出范围的异常。这是朋友数组,它给出了两个值。

对于前: friendinfo [0] = user1,friendinfo 1 = user2,当我选择user1时选中复选框我要将friend.length显示为2,选中的值应为1.

这是示例屏幕,当我点击创建按钮时,如何添加use3和user1。 的 GroupList.java

    public class GroupList extends ListActivity 
{

    boolean[] checkBoxState;

    private IAppManager imService = null;

    private FriendListAdapter friendAdapter;

    public String ownusername = new String();

    private class FriendListAdapter extends BaseAdapter 
    {   
        @SuppressWarnings("unused")

        class ViewHolder {
            TextView text;
            ImageView icon;
            CheckBox check1;



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

        private FriendInfo[] friends = null;




        public FriendListAdapter(Context context) {
            super();            

            mInflater = LayoutInflater.from(context);

            mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
            mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);

        }

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

        }


        public int getCount() {     

            return friends.length;
        }


        public FriendInfo getItem(int position) {           

            return friends[position];
        }

        public long getItemId(int position) {

            return 0;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;


            if (convertView == null) 
            {
                convertView = mInflater.inflate(R.layout.grouplist, null);


                holder = new ViewHolder();

                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.check1 = (CheckBox) convertView.findViewById(R.id.checkBox1);

                convertView.setTag(holder);

            }           

            else {

                holder = (ViewHolder) convertView.getTag();
            }


            holder.text.setText(friends[position].userName);
            holder.icon.setImageBitmap(friends[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
            checkBoxState = new boolean[friends.length];
            holder.check1.setChecked(checkBoxState[position]);
            holder.check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){

                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    checkBoxState[position]=isChecked;

                    String check=friends[position].userName;


                    Toast.makeText(getApplicationContext(),friends[position].userName+"checked", Toast.LENGTH_LONG).show();
                }
            });


            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(IMService.FRIEND_LIST_UPDATED))
                {

                    GroupList.this.updateData(FriendController.getFriendsInfo(), 
                                                FriendController.getUnapprovedFriendsInfo());

                }
            }
        }

    };
    public MessageReceiver messageReceiver = new MessageReceiver();

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

            FriendInfo[] friends = FriendController.getFriendsInfo(); 
            if (friends != null) {              
                GroupList.this.updateData(friends, null); 
            }    
            String groupname = getIntent().getStringExtra("nick");
            setTitle(groupname);
            ownusername = imService.getUsername();
        }
        public void onServiceDisconnected(ComponentName className) {          
            imService = null;
            Toast.makeText(GroupList.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };



    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    protected void onCreate(Bundle savedInstanceState) 
    {       
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        setContentView(R.layout.group_list_screen);
        friendAdapter = new FriendListAdapter(this);
        Button create=(Button)findViewById(R.id.create);
        create.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("unused")
            @Override
            public void onClick(View v) {
                String groupname = getIntent().getStringExtra("nick");


                        try {

                            FriendInfo[] friend=FriendController.getFriendsInfo();
                            //checkBoxState = new CheckBox[friend.length];
                            /*try {
                                for(int i=0;i <=friend.length ;i++){

                                    if(checkBoxState[i].isChecked()){
                                        check[i]="1";
                                    }



                            } 
                            }catch (Exception e) {
                                e.printStackTrace();
                            }*/


                            String result1 = imService.CreateGroup(groupname,imService.getUsername(),friend);
                        } catch (UnsupportedEncodingException e) {

                            e.printStackTrace();
                        }


                Toast.makeText(getApplicationContext(), "Group Created Sucessfully",Toast.LENGTH_LONG).show();

            }
        });







    }

    public void updateData(FriendInfo[] friends, FriendInfo[] 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.stat_sample)
                .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, UnApprovedFriendList.class);
                i.putExtra(FriendInfo.FRIEND_LIST, tmp);                

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

                mBuilder.setContentText("You have new friend request(s)");


                mBuilder.setContentIntent(contentIntent);


                NM.notify(R.string.new_friend_request_exist, mBuilder.build());         
            }
            else
            {

                NM.cancel(R.string.new_friend_request_exist);           
            }
        }

    }





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

    @Override
    protected void onResume() 
    {

        super.onResume();
        bindService(new Intent(GroupList.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);

        IntentFilter i = new IntentFilter();

        i.addAction(IMService.FRIEND_LIST_UPDATED);

        registerReceiver(messageReceiver, i);           


    }


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

        super.onActivityResult(requestCode, resultCode, data);




    }

3 个答案:

答案 0 :(得分:5)

你可能想写:

if(checkBoxState[i]==isChecked)

如果checkBoxStatefriend数组具有相同的长度,checkBoxState[friend.length]超出范围,因为数组的索引从0到长度为-1。

另请注意,您的if条件包含赋值运算符=,而不是比较运算符==

答案 1 :(得分:2)

只需使用for循环中的索引即可。此外,因为isChecked已经是一个布尔值,你可以直接将其分配给checkBoxState

for (int i = 0; i < friend.length; i++) {
    checkBoxState[i] = isChecked;
}

答案 2 :(得分:1)

您正尝试访问长度为2(位置0和1)的数组中的索引第2个位置。

所以请更改以下代码,

if(checkBoxState[i]==isChecked)
相关问题