Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ArrayIndex out of Bounds Exception when adding new items to list while scrolling

I have a ListView in which I load data from SQLite by setting a limit of 3 data from SQLite when scrolling the list I have used AsyncTask to load another 3 data from the database, but when the new data is loaded it shows me an error: ArrayIndexOutOfBoundsException.

Adapter:

public class FarmerAdapter extends BaseAdapter implements Filterable{
    Context context;
    ArrayList<Farmer> farmeritems;
    ArrayList<Farmer> mStringFilterList;
    ValueFilter valueFilter;

    public FarmerAdapter(Context context, ArrayList<Farmer> list) {

        this.context = context;
        farmeritems = list;
        mStringFilterList = list;
    }


    @Override
    public int getCount() {

        return farmeritems.size();
    }

    @Override
    public Object getItem(int position) {

        return farmeritems.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public int getViewTypeCount() {

        return getCount();
    }

    @Override
    public int getItemViewType(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        Farmer farmerdetails = farmeritems.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.model_farmer, null);

        }


        final TextView farmname = (TextView) convertView.findViewById(R.id.tv_farmer_name);
        final TextView farmmobno = (TextView) convertView.findViewById(R.id.tv_farmer_mobno);
        final TextView farmlocation = (TextView) convertView.findViewById(R.id.tv_farmer_location);
        final LinearLayout farmtrade = (LinearLayout) convertView.findViewById(R.id.li_farmer_trade);
        final LinearLayout farmadvance = (LinearLayout) convertView.findViewById(R.id.li_farmer_advance);
        final ImageView img_trade = (ImageView)convertView.findViewById(R.id.img_farmertrade);
        final ImageView img_advance = (ImageView)convertView.findViewById(R.id.img_farmeradvance);
        farmname.setText(farmerdetails.getFarmername());
        farmmobno.setText(farmerdetails.getFarmermobno());
        farmlocation.setText(farmerdetails.getFarmerlocation());
        farmtrade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                img_trade.setColorFilter(ContextCompat.getColor(context, R.color.colorAccent));
                img_advance.clearColorFilter();
                Intent b = new Intent(context, Farmer_simpletrade_Activity.class);
                b.putExtra("fname", farmname.getText().toString());
                b.putExtra("fmobno", farmmobno.getText().toString());
                context.startActivity(b);
            }
        });
        farmadvance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                img_advance.setColorFilter(ContextCompat.getColor(context, R.color.colorAccent));
                img_trade.clearColorFilter();
                Intent c = new Intent(context, Farmer_simpleadvance_Activity.class);
                c.putExtra("farmername", farmname.getText().toString());
                c.putExtra("farmermobno", farmmobno.getText().toString());
                context.startActivity(c);
                ((Activity) context).finish();
            }
        });
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //todo disable the comments for farmer individual transaction

                Intent a = new Intent(context, FarmerLedgerView_Activity.class);
                a.putExtra("farmername", farmname.getText().toString());
                a.putExtra("farmermobno", farmmobno.getText().toString());
                context.startActivity(a);
                ((Activity) context).finish();

            }
        });
        return convertView;

    }

    @Override
    public Filter getFilter() {
        if (valueFilter == null) {
            valueFilter = new ValueFilter();
        }
        return valueFilter;
    }

    private class ValueFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                ArrayList<Farmer> filterList = new ArrayList<Farmer>();
                for (int i = 0; i < mStringFilterList.size(); i++) {
                    if ((mStringFilterList.get(i).getFarmername().toUpperCase())
                            .contains(constraint.toString().toUpperCase())) {

                        Farmer farmer = new Farmer(mStringFilterList.get(i)
                                .getFarmername(), mStringFilterList.get(i)
                                .getFarmermobno(), mStringFilterList.get(i)
                                .getFarmerlocation());

                        filterList.add(farmer);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;
            } else {
                results.count = mStringFilterList.size();
                results.values = mStringFilterList;
            }
            return results;

        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            farmeritems = (ArrayList<Farmer>) results.values;
            notifyDataSetChanged();
        }

    }

    public void setTransactionList(ArrayList<Farmer> newList) {
        farmeritems = newList;
        notifyDataSetChanged();
    }
}

AsyncTask to load data from background:

  private class LoadDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Void doInBackground(Void... params) {

        if (isCancelled()) {
            return null;
        }

        // Simulates a background task
        try {
            Thread.sleep(1000);
            offSet=offSet+3;
            if (offSet > totalcount) {
               loadingMore=false;
            } else {
                Log.e("OffsetNo", String.valueOf(offSet));
                databasehandler = new DatabaseHandler(getApplicationContext());

                farmerlabels = new ArrayList<Farmer>();
                String selectQuery = "SELECT * FROM farmercontactlabel ORDER BY farmername COLLATE NOCASE LIMIT " + offSet + "";
                SQLiteDatabase db = databasehandler.getReadableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                if (cursor.moveToFirst()) {
                    do {
                        Farmer farmerdetails = new Farmer();
                        farmerdetails.setFarmername(cursor.getString(1));
                        farmerdetails.setFarmermobno(cursor.getString(2));
                        farmerdetails.setFarmerlocation(cursor.getString(3));
                        list.add(farmerdetails);

                    } while (cursor.moveToNext());

                }
                cursor.close();
                db.close();

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }



        return null;

    }

    @Override
    protected void onPostExecute(Void result) {

        fadapter.setTransactionList(list);
        list_farmer.onLoadMoreComplete();

       // fadapter.notifyDataSetChanged();

        super.onPostExecute(result);
    }

    @Override
    protected void onCancelled() {
        // Notify the loading more operation has finished
        list_farmer.onLoadMoreComplete();
    }
}

Database Structure:

 String CREATE_FARMERS_TABLE = "CREATE TABLE " + FARMERCONTACT_LABELS + "("
            + FARMER_ID + " INTEGER,"
            + FARMER_NAME + " TEXT,"
            + FARMER_MOBNO + " NUMERIC PRIMARY KEY,"
            + FARMER_LOCATION + " TEXT" + ");";
    db.execSQL(CREATE_FARMERS_TABLE);

Database:

 public ArrayList<Farmer> getAllfarmers(int offset) {
    ArrayList<Farmer> farmerlabels = new ArrayList<Farmer>();
    String selectQuery = "SELECT * FROM " + FARMERCONTACT_LABELS + " ORDER BY farmername COLLATE NOCASE LIMIT " + offset + "";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            Farmer farmerdetails = new Farmer();
            farmerdetails.setFarmername(cursor.getString(1));
            farmerdetails.setFarmermobno(cursor.getString(2));
            farmerdetails.setFarmerlocation(cursor.getString(3));
            farmerlabels.add(farmerdetails);
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return farmerlabels;
}

Error:

java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:7103)
at android.widget.ListView.layoutChildren(ListView.java:1653)
at android.widget.AbsListView.onLayout(AbsListView.java:2230)
at android.view.View.layout(View.java:16001)
at android.view.ViewGroup.layout(ViewGroup.java:5181)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1195)
at android.view.View.layout(View.java:16001)
like image 626
Ramesh R Avatar asked Jan 17 '17 11:01

Ramesh R


People also ask

How do you avoid array index out of bound exception?

To avoid the ArrayIndexOutOfBoundsException , the following should be kept in mind: The bounds of an array should be checked before accessing its elements. An array in Java starts at index 0 and ends at index length - 1 , so accessing elements that fall outside this range will throw an ArrayIndexOutOfBoundsException .

How do you solve an index outside the bounds of the array?

U are accessing an empty array with some index greater than zero, it returns this error. Solution : Check the array count before you access it through index !

Why do we get array index out of bound exception?

The ArrayIndexOutOfBounds exception is thrown if a program tries to access an array index that is negative, greater than, or equal to the length of the array. The ArrayIndexOutOfBounds exception is a run-time exception. Java's compiler does not check for this error during compilation.


1 Answers

If you're limiting the number of rows to 3, the last index will be 2. So If you try to get by the index 3, you'll get NullPointerException.

like image 68
Wilder Pereira Avatar answered Oct 19 '22 04:10

Wilder Pereira