【问题标题】:How to fix java lang arrayadapter index out of bound?java - 如何修复java lang arrayadapter索引超出范围?
【发布时间】:2014-02-26 19:08:44
【问题描述】:

我尝试添加一个新的项目块,但出现错误,我删除了新块的整个代码,但我仍然收到此错误。有人可以帮我修复错误并在我的滑动菜单中添加新的项目块吗?

这是我的 MainActivity.java:

package com.orar.cngcnasaud;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener {

    private ListView mDrawerList;
    private DrawerLayout mDrawer;
    private CustomActionBarDrawerToggle mDrawerToggle;
    private String[] menuItems;


    private static final String TAG = "AudioDemo";
    private static final String isPlaying = "Media is Playing"; 
    private static final String notPlaying = "Media has stopped Playing"; 

    MediaPlayer player;
    Button playerButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_drawer);
        player = MediaPlayer.create(this, R.raw.gc);

        player.setLooping(false); // Set looping

        // Get the button from the view
        playerButton = (Button) this.findViewById(R.id.buttonmp);
        playerButton.setText(R.string.play_label);
        playerButton.setTextColor(Color.WHITE);
        playerButton.setOnClickListener((OnClickListener) this);







        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        // set a custom shadow that overlays the main content when the drawer
        // opens
        mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        _initMenu();
        mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
        mDrawer.setDrawerListener(mDrawerToggle);
    }

        public void onClick(View v) {
            Log.d(TAG, "onClick: " + v);
            if (v.getId() == R.id.buttonmp) {
                playPause();
            }

    }




    private void demoPause() {
        // TODO Auto-generated method stub
        player.pause();
        playerButton.setText(R.string.play_label);

        Log.d(TAG, notPlaying);
}

    private void playPause() {
        // TODO Auto-generated method stub
        if(player.isPlaying()) {
          demoPause();
        } else {
          demoPlay();
        }   
    }

    private void demoPlay() {
        // TODO Auto-generated method stub
        player.start();
        playerButton.setText(R.string.stop_label);

        Log.d(TAG, isPlaying);
}




    private void _initMenu() {
        NsMenuAdapter mAdapter = new NsMenuAdapter(this);

        // Add Header
        mAdapter.addHeader(R.string.ns_menu_main_header);

        // Add first block

        menuItems = getResources().getStringArray(
                R.array.ns_menu_items);
        String[] menuItemsIcon = getResources().getStringArray(
                R.array.ns_menu_items_icon);

        int res = 0;
        for (String item : menuItems) {

            int id_title = getResources().getIdentifier(item, "string",
                    this.getPackageName());
            int id_icon = getResources().getIdentifier(menuItemsIcon[res],
                    "drawable", this.getPackageName());

            NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
            if (res==1) mItem.counter=0; //it is just an example...
            if (res==3) mItem.counter=0; //it is just an example...
            mAdapter.addItem(mItem);
            res++;
        }



        mDrawerList = (ListView) findViewById(R.id.drawer);
        if (mDrawerList != null)
            mDrawerList.setAdapter(mAdapter);

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        /*
         * The action bar home/up should open or close the drawer.
         * ActionBarDrawerToggle will take care of this.
         */
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        // Handle your other action bar items...
        return super.onOptionsItemSelected(item);
    }

    private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {

        public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
            super(
                mActivity,
                mDrawerLayout, 
                R.drawable.ic_drawer,
                R.string.ns_menu_open, 
                R.string.ns_menu_close);
        }

        @Override
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(getString(R.string.ns_menu_close));
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(getString(R.string.ns_menu_open));
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mDrawerList.setItemChecked(position, true);         
            mDrawer.closeDrawer(mDrawerList);
            if (position == 1) {
                Intent intent = new Intent(MainActivity.this, Istoric.class);
                startActivity(intent);
                mDrawer.closeDrawers();
            }
            else if (position == 2) {
                Intent intent2 = new Intent(MainActivity.this, Profesori.class);
                startActivity(intent2);
                mDrawer.closeDrawers();
            }
            if (position == 3) {
                Intent intent3 = new Intent(MainActivity.this, Elevi.class);
                startActivity(intent3);
                mDrawer.closeDrawers();
            }
            if (position == 4) {
                Intent intent4 = new Intent(MainActivity.this, ShowImageActivity.class);
                startActivity(intent4);
                mDrawer.closeDrawers();
            }

            if (position == 5) {
                Intent intent5 = new Intent(MainActivity.this, Despre.class);
                startActivity(intent5);
                mDrawer.closeDrawers();
            }
            if (position == 6) {
                Intent intent6 = new Intent(MainActivity.this, Feedback.class);
                startActivity(intent6);
                mDrawer.closeDrawers();
            }

        }



    }
        }

这是我的日志:

02-26 19:00:15.198: E/AndroidRuntime(1308): FATAL EXCEPTION: main
02-26 19:00:15.198: E/AndroidRuntime(1308): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.orar.cngcnasaud/com.orar.cngcnasaud.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.os.Looper.loop(Looper.java:137)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.ActivityThread.main(ActivityThread.java:5041)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at java.lang.reflect.Method.invokeNative(Native Method)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at java.lang.reflect.Method.invoke(Method.java:511)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at dalvik.system.NativeStart.main(Native Method)
02-26 19:00:15.198: E/AndroidRuntime(1308): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
02-26 19:00:15.198: E/AndroidRuntime(1308):     at com.orar.cngcnasaud.MainActivity._initMenu(MainActivity.java:126)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at com.orar.cngcnasaud.MainActivity.onCreate(MainActivity.java:64)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.Activity.performCreate(Activity.java:5104)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-26 19:00:15.198: E/AndroidRuntime(1308):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-26 19:00:15.198: E/AndroidRuntime(1308):     ... 11 more

非常感谢!

【问题讨论】:

  • menuItems 大于menuItemsIcon
  • 是的,我在这里没有发现任何问题,因此只需确保在您的资源数组中 menuItemsIcon 的元素数至少与 menuItems 一样多。

标签: android arrays compiler-errors


【解决方案1】:

在第 126 行(在 _initMenu() 内),您的循环正在调用数组外部的索引。长度为 4 的数组应包含 0,1,2,3 的索引。

02-26 19:00:15.198: E/AndroidRuntime(1308): 由: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4 02-26 19:00:15.198:E/AndroidRuntime(1308):在 com.orar.cngcnasaud .MainActivity._initMenu(MainActivity.java:126)

【讨论】:

  • 我已经解决了.. 但是现在,我怎样才能添加第二块项目..?非常感谢!!!
【解决方案2】:

我认为你的代码可以这样修复:

  int res = 0;
    for (String item : menuItems) {

        int id_title = getResources().getIdentifier(item, "string",
                this.getPackageName());
        if (res < menuItemsIcon.length) { //only if the array is big enough..
               int id_icon = getResources().getIdentifier(menuItemsIcon[res],
                "drawable", this.getPackageName());
        }

        NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
        if (res==1) mItem.counter=0; //it is just an example...
        if (res==3) mItem.counter=0; //it is just an example...
        mAdapter.addItem(mItem);
        res++;
    }

编辑:更正了 res-1 的东西,改为添加对数组长度的检查...

【讨论】:

  • 这有什么不同?
  • 这有什么不同? (因为,你知道,1 - 1 = 0
  • @Tenfour04 确实 ;-) 会改善答案
  • 我已经解决了.. 但是现在,我怎样才能添加第二块项目..?非常感谢!!!
【解决方案3】:

ArrayIndexOutOfBoundsException 被抛出,因为您正在访问索引 4 处的数组项,但您的数组 (menuItemsIcon) 仅包含 4 个元素。

您有 2 个数组:menuItemsmenuItemsIcon,在您的 for loop 中,您正在使用它的增强版本来遍历 menuItems,同时,您正在使用 res 访问 menuItemsIcon 元素,您在 for loop 中递增。现在,in menuItemsIcon 数组中的元素更少了(它的长度为 4),因此当尝试访问索引为 4 的元素时,您会遇到异常。

你有几个选项来解决这个问题:

  • 确保两个数组包含相同数量的元素,或者
  • 在增加 res 之前,检查 res 是否已经等于一个数组的 length-1,它用于从(在您的情况下为 menuItemsIcon)访问元素,或者不增加,或者重置为 0,或者任何适合您的,或者
  • 遍历 for loop 正文中的较短数组,并使用索引来访问较长的数组 - 当然,这并不理想,因为您不会使用较长数组的所有元素

【讨论】:

  • 我已经解决了.. 但是现在,我怎样才能添加第二块项目..?非常感谢!!!
  • 请更具体一些,然后再问一个关于 SO 的问题。
  • 我想在下面添加一个新标题和新项目。现在我只有一个标题和 6 个项目,但我想要第一个标题和第二个标题 2 个标题和 2 个项目。
猜你喜欢
  • 2019-08-17
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 2021-11-13
  • 1970-01-01
  • 2013-06-16
  • 1970-01-01
相关资源
最近更新 更多