数组索引超出界限 - Android

时间:2012-01-11 03:25:18

标签: android arrays

我收到一个数组越界错误。我在try / catch块中设置数组值,所以我不确定为什么我得到一个数组越界错误。

private static String profileName;
private String identity = null;
private String address = null;
private boolean valid = false;
private int profileId;

public String fullName="";


private LinkedHashMap<String, String> nameValues = new 
LinkedHashMap<String, String>(0);

public Profile(){
    try {
        String[] subNames = fullName.split("@");
        this.profileName = subNames[0];
        this.identity = subNames[1];
        this.address = subNames[2];
        this.valid = true;
    } catch (Exception ex) {
        Log.w(LOG_TAG, "Invalid profile, " + ex);
        this.valid = false;
    }
}

放置价值代码:

public String getAttributeValue(String key){
    return nameValues.get(key);
}

public void addAttribute(String key, String value){
    nameValues.put(key, value);
}

以下是我从这个问题中得到的堆栈跟踪:

01-11     01:37:20.721: I/ActivityThread(1759): Pub com.whooznear.android: com.whooznear.android.ProfileProvider
01-11     01:37:21.142: D/dalvikvm(1759): GC_FOR_ALLOC freed 42K, 4% free 6337K/6595K, paused 139ms
01-11     01:37:21.174: I/dalvikvm-heap(1759): Grow heap (frag case) to 6.805MB for 588816-byte allocation
01-11     01:37:21.472: D/dalvikvm(1759): GC_CONCURRENT freed 8K, 4% free 6903K/7175K, paused 20ms+14ms
01-11     01:37:24.974: D/dalvikvm(1759): GC_FOR_ALLOC freed 603K, 11% free 6666K/7431K, paused 81ms
01-11     01:37:25.142: D/dalvikvm(1759): GC_CONCURRENT freed <1K, 4% free 7167K/7431K, paused 6ms+14ms
01-11     01:37:25.642: W/Profile(1759): Invalid profile, java.lang.ArrayIndexOutOfBoundsException: index=1 length=1
01-11     01:46:21.692: W/IInputConnectionWrapper(1759): showStatusIcon on inactive InputConnection
01-11     01:46:25.836: D/dalvikvm(1759): GC_EXPLICIT freed 384K, 6% free 7110K/7559K, paused 9ms+5ms

2 个答案:

答案 0 :(得分:4)

我确定Profile是构造函数,不确定如何以及何时分配fullName字符串?但是,在使用数组之前,必须检查数组的边界/长度。

尝试,

String[] subNames = fullName.split("@");
if(subNames.length==3) {
  this.profileName = subNames[0];
  this.identity = subNames[1];
  this.address = subNames[2];
  this.valid = true;
}

答案 1 :(得分:0)

尝试ex.printStackTrace();并且您可以识别出数组越界错误的位置。

相关问题