2012-03-12 30 views
0

我爲什麼會得到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

回答

0

我會建議你使用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

0

getCount()方法要返回列表msgs.length+16的大小。因此適配器的getView()方法將被稱爲比msgs.length的值和該行

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

更將拋出異常時的位置值是多於或等於msgs.length

0

例外是最有可能就行:

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

及其beczuse你getCount將正在返回是msg.length + 18,但陣列味精是長度msg.length的還是,希望其明確的NW

相關問題