由以下原因引起:java.lang.ArrayIndexOutOfBoundsException:length = 1;索引= 1

时间:2020-05-28 21:01:40

标签: java android indexoutofrangeexception

我写了一个自定义列表视图以及搜索功能。代码如下:

public class FaqActivity extends AppCompatActivity {
    ListView listView;
    ListViewAdapter adapter;
    String[] title;
    int[] icon;
    ArrayList<faqmodellist> arrayList = new ArrayList<>();

    private final String TAG =  FaqActivity.class.getCanonicalName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.faq_layout);

        listView = findViewById(R.id.list_item);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_n_back);
        setSupportActionBar(toolbar);

        title = new String[]{
                "Battery",
                "Cpu",
                "Display",
                "Memory",
                "Sensor"
        };
        icon = new int[]{R.drawable.ic_n_help};

        listView = findViewById(R.id.listView);

        for (int i = 0; i < title.length; i++) {
            faqmodellist model = new faqmodellist(title[i], icon[i]);
            Log.i(TAG, "onCreate: array is" + Arrays.toString(icon));
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass results to listViewAdapter class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview
        listView.setAdapter(adapter);

    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.appSearchBar);
        final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)) {
                    adapter.filter("");
                    listView.clearTextFilter();
                } else {
                    adapter.filter(s);
                }
                return true;
            }
        });
        return true;
    }

}  

Custom listview adapter:

public class ListViewAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater inflater;
    private List<faqmodellist> modellist;
    private ArrayList<faqmodellist> arrayList;

    public ListViewAdapter(Context context, List<faqmodellist> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<>();
        this.arrayList.addAll(modellist);
    }

    public static class ViewHolder{
        TextView mTitleTv;
        ImageView mIconIv;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view==null){
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.item_listview, parent);

            //locate the views in row.xml
            holder.mTitleTv = view.findViewById(R.id.mainTitle);
            holder.mIconIv = view.findViewById(R.id.mainIcon);

            view.setTag(holder);

        }
        else {
            holder = (ViewHolder)view.getTag();
        }
        //set the results into textviews
        holder.mTitleTv.setText(modellist.get(position).getTitle());
        //set the result in imageview
        holder.mIconIv.setImageResource(modellist.get(position).getIcon());

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (modellist.get(position).getTitle().equals("Battery")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Battery");
                    intent.putExtra("contentTv", "This is Battery detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Cpu")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Cpu");
                    intent.putExtra("contentTv", "This is Cpu detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Display")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Display");
                    intent.putExtra("contentTv", "This is Display detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Memory")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Memory");
                    intent.putExtra("contentTv", "This is Memory detail...");
                    mContext.startActivity(intent);
                }
                if (modellist.get(position).getTitle().equals("Sensor")){
                    //start FaqAnswersActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, FaqAnswersActivity.class);
                    intent.putExtra("actionBarTitle", "Sensor");
                    intent.putExtra("contentTv", "This is Sensor detail...");
                    mContext.startActivity(intent);
                }
            }
        });


        return view;
    }

    //filter
    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0){
            modellist.addAll(arrayList);
        }
        else {
            for (faqmodellist model : arrayList){
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }

}  

运行该代码时,出现此错误:

原因:java.lang.ArrayIndexOutOfBoundsException:length = 1;索引= 1
在com.dell.helpmodule.screen.ui.activity.FaqActivity.onCreate(FaqActivity.java:52)
在android.app.Activity.performCreate(Activity.java:7893)
在android.app.Activity.performCreate(Activity.java:7880)
在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3279)
在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)上
在android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)上
在android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)上
在android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)中
在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2040)中
在android.os.Handler.dispatchMessage(Handler.java:107)上
在android.os.Looper.loop(Looper.java:224)上
在android.app.ActivityThread.main(ActivityThread.java:7520)上
在java.lang.reflect.Method.invoke(本机方法)
在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:539)中
在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

图像数组中只有一个元素,并且数组从位置0开始。如何解决错误?

1 个答案:

答案 0 :(得分:1)

图标数组中只有1个项目。 如果要向所有faqModelList项目添加相同的图标,则应在for循环中替换模型初始化为:

faqmodellist model = new faqmodellist(title[i], R.drawable.ic_n_help);