尽管初始化数组的大小为

尽管初始化数组的大小为

问题描述:

我为什么会得到ArrayIndexOutOfBoundsException?尽管初始化数组时使用了大小,但我无法找到为什么会得到此异常。当我尝试增加数组的大小时,会发生此异常。这是我的代码。任何人都可以建议我做错了什么?尽管初始化数组的大小为

public class MsgAdapter extends BaseAdapter { 
public String msgs[]=new String[150]; 
public Activity context; 
public LayoutInflater inflater; 
int count=16; 
public MsgAdapter(Activity context,String[] msgs) { 
    super(); 

    this.context = context; 
    this.msgs = msgs; 


    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 
public static class ViewHolder 
{ 

    TextView msgView; 

ImageView b; 
} 
@Override 
public int getCount() { 
    // TODO Auto-generated method stub 
    Log.v("count", ""+msgs.length); 
    return msgs.length+16; 
} 

@Override 
public Object getItem(int position) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public long getItemId(int position) { 
    // TODO Auto-generated method stub 
    return 0; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    // TODO Auto-generated method stub 
     final ViewHolder holder; 

     View v; 

     LayoutInflater inflater = context.getLayoutInflater(); 
     if(convertView==null){ 
      convertView = inflater.inflate(R.layout.msg_list, null); 
       holder = new ViewHolder(); 
       holder.msgView=(TextView)convertView.findViewById(R.id.msgtext); 
      holder.b=(ImageView)convertView.findViewById(R.id.sms); 
       convertView.setTag(holder); 
     } 
     else 
      { 
       holder=(ViewHolder)convertView.getTag(); 

      } 
     holder.b.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       Intent sendIntent = new Intent(Intent.ACTION_VIEW); 
       sendIntent.putExtra("sms_body",  holder.msgView.getText().toString()); 
       sendIntent.setType("vnd.android-dir/mms-sms"); 
      v.getContext().startActivity(sendIntent);  
      } 
     }); 

     holder.msgView.setText(msgs[position]);//the exception occurs here 
return convertView; 
} 
} 
+3

您的程序,要求你,你应该了解ArrayIndexOutOfBoundsException异常,即为什么你得到这个错误。 – RobinHood 2012-03-12 05:19:39

我会建议你使用ArrayList<String> msg而不是使用String []msg,因为ArrayList的大小可以动态增加和减少。

还有另一个bug(可能)。

初始化数组中MsgAdapter这样。

public String msgs[]=new String[150]; 

,现在您设置的其它String阵列msgs再次在这里。

public MsgAdapter(Activity context,String[] msgs) { 
    ... 
    this.msgs = msgs; 
    ... 
} 
+0

谢谢。这解决了我的问题。 ArrayList 比String []效率更高。 – 2012-03-12 05:24:44

getCount()方法要返回列表msgs.length+16的大小。因此适配器的getView()方法将被称为比msgs.length的值和该行

holder.msgView.setText(msgs[position]); 

更将抛出异常时的位置值是多于或等于msgs.length

例外是最有可能就行:

holder.msgView.setText(消息[位置]);

及其beczuse你getCount将正在返回是msg.length + 18,但阵列味精是长度msg.length的还是,希望其明确的NW