【问题标题】:Android java.lang.ArrayIndexOutOfBoundsExceptionAndroid java.lang.ArrayIndexOutOfBoundsException
【发布时间】:2012-05-07 12:32:24
【问题描述】:

我正在制作一个梦想字典,我正在读取一个 txt 文件并保存到数组以将其显示到列表视图中。但是日志猫有一些错误,谁能告诉我是什么问题。

    05-07 14:29:06.750: E/AndroidRuntime(29135): FATAL EXCEPTION: main
05-07 14:29:06.750: E/AndroidRuntime(29135): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sonovnik.petkovski/com.sonovnik.petkovski.Main}: java.lang.ArrayIndexOutOfBoundsException
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.app.ActivityThread.access$1500(ActivityThread.java:123)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.os.Looper.loop(Looper.java:130)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.app.ActivityThread.main(ActivityThread.java:3835)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at java.lang.reflect.Method.invokeNative(Native Method)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at java.lang.reflect.Method.invoke(Method.java:507)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at dalvik.system.NativeStart.main(Native Method)
05-07 14:29:06.750: E/AndroidRuntime(29135): Caused by: java.lang.ArrayIndexOutOfBoundsException
05-07 14:29:06.750: E/AndroidRuntime(29135):    at com.sonovnik.petkovski.Main.readTxt(Main.java:115)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at com.sonovnik.petkovski.Main.initStuff(Main.java:131)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at com.sonovnik.petkovski.Main.onCreate(Main.java:39)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-07 14:29:06.750: E/AndroidRuntime(29135):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
05-07 14:29:06.750: E/AndroidRuntime(29135):    ... 11 more

代码如下:

    public class Main extends ListActivity {
    private ArrayList<Son> sonovi;
    private EditText filterText = null;
    private SonovnikAdapter adapter;
    private ListView list;
    Translator t = new Translator();
    private Intent intent;
    private ArrayList<Son> temp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initStuff();

        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                intent.putExtra("opis", sonovi.get(position).getOpis());
                intent.putExtra("naslov", sonovi.get(position).getNaslov());
                startActivity(intent);

            }
        });
        filterText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                String test = filterText.getText().toString().toUpperCase();
                int dolzina = filterText.length();
                temp = new ArrayList<Son>();
                for (int i = 0; i < sonovi.size(); i++) {
                    if (filterText.getText().toString().toLowerCase().equals(
                                    (String) sonovi.get(i).getLatinicno().toLowerCase()
                                            .subSequence(0, dolzina))) {
                        temp.add(sonovi.get(i));
                    }

                }

                SonovnikAdapter testc = new SonovnikAdapter(Main.this,
                        R.layout.item, temp);
                list.setAdapter(testc);
                testc.notifyDataSetChanged();
                list.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        intent.putExtra("opis", temp.get(position).getOpis());
                        intent.putExtra("naslov", temp.get(position)
                                .getNaslov());
                        startActivity(intent);
                    }
                });

            }
        });

    }

    private ArrayList<Son> readTxt() {
        ArrayList<Son> s = new ArrayList<Son>();
        InputStream is = this.getResources().openRawResource(R.raw.sonovnik);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str = null;
        String naslov, opis, latinica;
        String[] tmp;
        try {
            while ((str = br.readLine()) != null) {
                tmp = str.split("-");
                naslov = tmp[0].toString();
                opis = tmp[1].toString();

                latinica = tmp[2].toString(); //line 115
                 Log.v("test", latinica);
                s.add(new Son(naslov, opis, latinica));
            }
            is.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    private void initStuff() {
        list = getListView();
        list.setTextFilterEnabled(true);
        sonovi = new ArrayList<Son>();
        sonovi = readTxt(); //line 131
        intent = new Intent(this, Details.class);
        adapter = new SonovnikAdapter(this, R.layout.item, sonovi);
        setListAdapter(this.adapter);
        filterText = (EditText) findViewById(R.id.search_box);
    }

    private class SonovnikAdapter extends ArrayAdapter<Son> {

        private ArrayList<Son> items;

        public SonovnikAdapter(Context context, int textViewResourceId,
                ArrayList<Son> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.list_item, null);
            }
            Son o = items.get(position);
            if (o != null) {
                TextView naslov = (TextView) v.findViewById(R.id.textView1);
                if (naslov != null) {
                    naslov.setText(o.getNaslov().toString());
                }
            }
            return v;

        }
    }
}

【问题讨论】:

    标签: android indexoutofboundsexception


    【解决方案1】:

    readText,你有:

    tmp = str.split("-");
    

    然后你使用tmp[0]tmp[1]tmp[2]。我的猜测是tmp.length &lt; 2

    是什么让您认为 tmp 至少有 3 个项目?即使您认为应该如此,您也应该对其进行测试:if (tmp.length &gt;=3) { 等。

    旁注:tmp[i] 已经是 String 所以不用写xxx = tmp[i].toString();xxx = tmp[i]; 就够了。

    【讨论】:

      【解决方案2】:

      这是你的问题:

                  tmp = str.split("-");
                  naslov = tmp[0].toString();
                  opis = tmp[1].toString();
      
                  latinica = tmp[2].toString(); //line 115
      

      您使用“-”作为分隔符拆分字符串,但您从未检查它实际拆分了多少块。显然,您的输入文本文件包含一些只有一个“-”的行,因此它被分成两部分,并且 tmp[2] 超出范围。

      另外,不需要调用 .toString(),因为 tmp 已经是一个字符串数组。

      【讨论】:

      • 啊,阿西利亚斯比我快。 :-)
      • 大声笑我也一样,但这一切都很好,我们都给出了相似的答案,没关系,其他人会看到它有用。总有一天……
      【解决方案3】:

      你确定 str = br.readLine() 总是有一个“-”吗?我在这里看到的是,如果您的 str (str = br.readLine() ) 之一不包含“-”,您将不会有 tmp[0] 和或 tmp[1] 这可能导致java.lang.ArrayIndexOutOfBoundsException 您可能需要检查 if(str.contains("-"))

        String[] tmp;
      try {
          while ((str = br.readLine()) != null) {
             //before split, check that delimeter exists                      
              if (str.contains("-")) {
                  tmp = str.split("-");
                  naslov = tmp[0].toString();
                  opis = tmp[1].toString();
               .......            
               }                          
          }
          is.close();
          br.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
      

      【讨论】:

        猜你喜欢
        • 2013-06-07
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 2014-01-30
        • 2016-04-11
        相关资源
        最近更新 更多