简体   繁体   中英

Getting ArrayIndexOutofBoundsException in android listview

I am using listview to load data from sqlite when i open the app i could see the following error can anyone tell me what i am doing wrong in the adapter.Even when the app gets started it shows the following error

Database:

 public ArrayList<Daybook> getAlldaybookentriesdatewise(int s) {
    ArrayList<Daybook> daybookDetails = new ArrayList<Daybook>();
    String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0) as amountout,daybookusertype FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT " + s + "";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectquery, null);
    if (cursor.moveToFirst()) {
        do {
            Daybook daybookentries = new Daybook();
            daybookentries.setDate(cursor.getString(0));
            daybookentries.setCashin(cursor.getString(1));
            daybookentries.setCashout(cursor.getString(2));
            daybookDetails.add(daybookentries);


        } while (cursor.moveToNext());

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

Activity:

public class NewDaybook_Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ListView listview;
FloatingActionButton fabaddnew;
LinearLayout emptyy;
DatabaseHandler databasehandler;
ArrayList<Daybook> daybookcashentries;
Daybook_adapter dadapter;
LoginSession loginSession;
boolean loadingMore = false;
String totaldaybookcount;
int olimit = 2;
int totalcount;
String s;
private Locale mLocale;
private final String[] language = {"en", "ta"};
LinearLayout li_farmer, li_worker, li_vehicle, li_otherexpense, li_buyer, li_general;
RadioGroup rg_filtering;
RadioButton rbtn_farmertrade, rbtn_farmeradvance, rbtn_work, rbtn_workadvance, rbtn_groupwork, rbtn_groupadvance, rbtn_vehicle, rbtn_otherexpense;
AlertDialog alert;
ImageView img_farm, img_buy, img_work, img_veh, img_expense;
TextView tv_farm, tv_buy, tv_work, tv_veh, tv_expense;
public static final int progress_bar_type = 0;
private ProgressDialog pDialog;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nav_daybooks);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(R.string.daybook);


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View header = navigationView.getHeaderView(0);
    TextView tv_balanceamt = (TextView) header.findViewById(R.id.nav_name);
    TextView tv_timedate = (TextView) header.findViewById(R.id.tv_dateandtime);
    tv_balanceamt.setTextSize(22);
    long date = System.currentTimeMillis();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy ");
    String dateString = sdf.format(date);
    tv_timedate.setText(dateString);
    databasehandler = new DatabaseHandler(getApplicationContext());
    String balanceamount = String.valueOf(databasehandler.getdaybookbalanceamt());
    Log.e("daybookbalanceamt", String.valueOf(balanceamount));
    balanceamount = balanceamount.replaceAll("[\\[\\](){}]", "");
    tv_balanceamt.setText("\u20B9" + balanceamount);
    initalize();
}

private void initalize() {
    loginSession = new LoginSession(getApplicationContext());
    loginSession.checkLogin();
    databasehandler = new DatabaseHandler(getApplicationContext());
    listview = (ListView) findViewById(R.id.list_daybook);
    li_general = (LinearLayout) findViewById(R.id.linearLayout2);
    li_farmer = (LinearLayout) findViewById(R.id.linear_farmer);
    li_worker = (LinearLayout) findViewById(R.id.linear_worker);
    li_vehicle = (LinearLayout) findViewById(R.id.linear_vehicle);
    li_otherexpense = (LinearLayout) findViewById(R.id.linear_otherexpense);
    li_buyer = (LinearLayout) findViewById(R.id.linear_buyers);
    fabaddnew = (FloatingActionButton) findViewById(R.id.addnewtransaction);
    emptyy = (LinearLayout) findViewById(R.id.empty);
    rg_filtering = (RadioGroup) findViewById(R.id.rg_sortdata);
    rbtn_farmertrade = (RadioButton) findViewById(R.id.rbtn_farmers);
    rbtn_farmeradvance = (RadioButton) findViewById(R.id.rbtn_fadvance);
    rbtn_work = (RadioButton) findViewById(R.id.rbtn_work);
    rbtn_workadvance = (RadioButton) findViewById(R.id.rbtn_workadvance);
    rbtn_groupwork = (RadioButton) findViewById(R.id.rbtn_groupwork);
    rbtn_groupadvance = (RadioButton) findViewById(R.id.rbtn_groupadvance);
    rbtn_vehicle = (RadioButton) findViewById(R.id.rbtn_vehicle);
    rbtn_otherexpense = (RadioButton) findViewById(R.id.rbtn_otherexpense);

    img_farm = (ImageView) findViewById(R.id.img_farmer);
    img_buy = (ImageView) findViewById(R.id.img_buyer);
    img_work = (ImageView) findViewById(R.id.img_worker);
    img_veh = (ImageView) findViewById(R.id.img_vehicle);
    img_expense = (ImageView) findViewById(R.id.img_otherexpense);
    tv_farm = (TextView) findViewById(R.id.tv_farmer);
    tv_buy = (TextView) findViewById(R.id.tv_buyer);
    tv_work = (TextView) findViewById(R.id.tv_worker);
    tv_veh = (TextView) findViewById(R.id.tv_vehicle);

    tv_expense = (TextView) findViewById(R.id.tv_otherexpense);
    listview.setFastScrollEnabled(true);
    new Daybooklistloader().execute();


    li_buyer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    // When you Touch Down
                    // U can change Text and Image As per your Functionality
                    li_buyer.setBackgroundColor(Color.parseColor("#FF4081"));
                    tv_buy.setTextColor(Color.parseColor("#FFFFFF"));
                    img_buy.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
                    break;
                case MotionEvent.ACTION_UP:

                    //When you Release the touch
                    // U can change Text and Image As per your Functionality
                    startActivity(new Intent(NewDaybook_Activity.this, Activity_BuyerTransaction.class));
                    NewDaybook_Activity.this.finish();
                    break;
            }

            return true;
        }
    });


    li_farmer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    // When you Touch Down
                    // U can change Text and Image As per your Functionality
                    li_farmer.setBackgroundColor(Color.parseColor("#FF4081"));
                    tv_farm.setTextColor(Color.parseColor("#FFFFFF"));
                    img_farm.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
                    startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
                    NewDaybook_Activity.this.finish();
                    break;
                case MotionEvent.ACTION_UP:

                    //When you Release the touch
                    // U can change Text and Image As per your Functionality
                    startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
                    NewDaybook_Activity.this.finish();
                    break;
            }

            return true;
        }
    });


    fabaddnew.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            fabaddnew.setRippleColor(R.drawable.ripple_effect);
            startActivity(new Intent(NewDaybook_Activity.this, Activity_AddFastEntryDaybook.class));
            NewDaybook_Activity.this.finish();
            return true;
        }
    });
}




@SuppressWarnings("StatementWithEmptyBody")


@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();


    if (id == R.id.nav_home) {
        startActivity(new Intent(NewDaybook_Activity.this, NewDaybook_Activity.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_dashboard) {
        startActivity(new Intent(NewDaybook_Activity.this, DashboardActivity.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_buyer) {
        startActivity(new Intent(NewDaybook_Activity.this, BuyerListActivity.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_farmer) {
        startActivity(new Intent(NewDaybook_Activity.this, FarmerlistActivity.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_workers) {
        startActivity(new Intent(NewDaybook_Activity.this, WorkerListActivity.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_vehicles) {
        startActivity(new Intent(NewDaybook_Activity.this, VehicleList_activity.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_otherexpense) {
        startActivity(new Intent(NewDaybook_Activity.this, OtherExpenseList.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_report) {
        startActivity(new Intent(NewDaybook_Activity.this, BillBookActivity.class));
        NewDaybook_Activity.this.finish();
    } else if (id == R.id.nav_settings) {
        // startActivity(new Intent(NewDaybook_Activity.this, SettingsActivity.class));
        // NewDaybook_Activity.this.finish();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.language)
                .setItems(R.array.language, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        setLocale(language[i]);
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    } else if (id == R.id.nav_logout) {
        loginSession.logoutUser();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

private void setLocale(String lang) {
    Log.d("Selected Language is ", lang);
    SharedPreferences preferences = getSharedPreferences(MyApplication.PREF_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(MyApplication.PREF_USER_LANGUAGE_KEY, lang).apply();
    mLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        conf.setLocale(mLocale);
    }
    res.updateConfiguration(conf, dm);
    recreate();
}


@Override
protected Dialog onCreateDialog(int id) {

    switch (id) {

        case progress_bar_type:
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Processing...");
            pDialog.setIndeterminate(true);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setProgressNumberFormat(null);
            pDialog.setProgressPercentFormat(null);
            pDialog.setCancelable(false);
            pDialog.show();
            return pDialog;
        default:
            return null;
    }
}

private class Daybooklistloader extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    @Override
    protected String doInBackground(String... strings) {
        daybookcashentries = new ArrayList<Daybook>();
        daybookcashentries = databasehandler.getAlldaybookentriesdatewise(olimit);

        return null;
    }

    @Override
    protected void onPostExecute(String j) {
        dismissDialog(progress_bar_type);
        View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_footer, null, false);
        listview.addFooterView(footerView);
        dadapter = new Daybook_adapter(NewDaybook_Activity.this, daybookcashentries);
        if (dadapter != null) {
            if (dadapter.getCount() > 0) {
                emptyy.setVisibility(View.INVISIBLE);
                listview.setAdapter(dadapter);
            }
        } else {
            emptyy.setVisibility(View.VISIBLE);
        }

        final List<String> labels = databasehandler.getTotaldaybookrecord();
        for (String s : labels) {
            totaldaybookcount = s;
        }
        totalcount = Integer.parseInt(totaldaybookcount);

        listview.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int btn_initPosY = fabaddnew.getScrollY();
                int li_initPosY = li_general.getScrollY();
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {

                    dadapter.isScrolling(true);

                    fabaddnew.animate().cancel();
                    li_general.animate().cancel();
                    fabaddnew.animate().translationYBy(150);
                    li_general.animate().translationYBy(150);
                } else {

                    dadapter.isScrolling(false);
                    fabaddnew.animate().cancel();
                    li_general.animate().cancel();
                    fabaddnew.animate().translationY(btn_initPosY);
                    li_general.animate().translationY(li_initPosY);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                dadapter.isScrolling(true);

                //what is the bottom item that is visible
                int lastInScreen = firstVisibleItem + visibleItemCount;

                //is the bottom item visible & not loading more already? Load more!
                if ((lastInScreen == totalItemCount) && !(loadingMore)) {

                    new LoadDataTask().execute();
                }

            }
        });


    }
}

private class LoadDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loadingMore = true;
        // showDialog(progress_bar_type);
    }

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

        if (isCancelled()) {
            return null;
        }
        Log.e("test2", "reached");
        // Simulates a background task
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }


        Log.e("test3", "starting");
        databasehandler = new DatabaseHandler(getApplicationContext());
        if (olimit > totalcount) {
            // olimit = 1;
            // olimit = 2;
        } else {
            olimit = olimit + 1;


        }
        daybookcashentries = new ArrayList<Daybook>();
        databasehandler = new DatabaseHandler(getApplicationContext());

        daybookcashentries = new ArrayList<Daybook>();
        String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0),daybookusertype as amountout FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT '" + olimit + "'";
        SQLiteDatabase db = databasehandler.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectquery, null);
        if (cursor.moveToFirst()) {
            do {
                Daybook daybookentries = new Daybook();
                daybookentries.setDate(cursor.getString(0));
                daybookentries.setCashin(cursor.getString(1));
                daybookentries.setCashout(cursor.getString(2));
                daybookcashentries.add(daybookentries);

            } while (cursor.moveToNext());

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


        return null;

    }

    @Override
    protected void onPostExecute(Void result) {

        dadapter.setTransactionList(daybookcashentries);
        loadingMore = false;
        //  dismissDialog(progress_bar_type);

        super.onPostExecute(result);
    }

    @Override
    protected void onCancelled() {
        // Notify the loading more operation has finished
        loadingMore = false;
    }
}

}

Adapter:

public class Daybook_adapter extends BaseAdapter {
Context context;
private ArrayList<Daybook> entriesdaybook;
private ArrayList<Daybooklist> daybooklists = new ArrayList<Daybooklist>();
private boolean isListScrolling;
private LayoutInflater inflater;

public Daybook_adapter(Context context, ArrayList<Daybook> entriesdaybook) {
    this.context = context;
    this.entriesdaybook = entriesdaybook;
}

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

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

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



@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.model_daybook, null);

    final TextView tv_date = (TextView) convertView.findViewById(R.id.tv_daybook_date);
    final TextView tv_cashin = (TextView) convertView.findViewById(R.id.tv_daybook_cashin);
    final TextView tv_cashout = (TextView) convertView.findViewById(R.id.tv_daybook_cashout);
    final TextView tv_totalamt = (TextView) convertView.findViewById(R.id.daybook_total_amt);
    final ImageView img_pdf = (ImageView) convertView.findViewById(R.id.img_printpdf);
    LinearLayout emptyy = (LinearLayout) convertView.findViewById(R.id.empty);
    ExpandableHeightListView daybookdetailviewlist = (ExpandableHeightListView) convertView.findViewById(R.id.detaillist_daybook);


    final Daybook m = entriesdaybook.get(position);

    String s = m.getDate();
    String[] spiliter = s.split("-");
    String year = spiliter[0];
    String month = spiliter[1];
    String date = spiliter[2];
    if (month.startsWith("01")) {
        tv_date.setText(date + "Jan" + year);
    } else if (month.startsWith("02")) {
        tv_date.setText(date + "Feb" + year);
    } else if (month.startsWith("03")) {
        tv_date.setText(date + "Mar" + year);
    } else if (month.startsWith("04")) {
        tv_date.setText(date + "Apr" + year);
    } else if (month.startsWith("05")) {
        tv_date.setText(date + "May" + year);
    } else if (month.startsWith("06")) {
        tv_date.setText(date + "Jun" + year);
    } else if (month.startsWith("07")) {
        tv_date.setText(date + "Jul" + year);
    } else if (month.startsWith("08")) {
        tv_date.setText(date + "Aug" + year);
    } else if (month.startsWith("09")) {
        tv_date.setText(date + "Sep" + year);
    } else if (month.startsWith("10")) {
        tv_date.setText(date + "Oct" + year);
    } else if (month.startsWith("11")) {
        tv_date.setText(date + "Nov" + year);
    } else if (month.startsWith("12")) {
        tv_date.setText(date + "Dec" + year);
    }
    tv_cashin.setText("\u20B9" + m.getCashin());
    tv_cashout.setText("\u20B9" + m.getCashout());
    double one = Double.parseDouble(m.getCashin());
    double two = Double.parseDouble(m.getCashout());
    double three = one + two;
    tv_totalamt.setText("\u20B9" + String.valueOf(three));
   /* DatabaseHandler databaseHandler = new DatabaseHandler(context);
    daybooklists = databaseHandler.getAllDaywisedaybookdetails(s);
    for (int i = 0; i < daybooklists.size(); i++) {
        try {
            Daybooklist_adapter adapter = new Daybooklist_adapter(context, daybooklists);
            if (adapter != null) {
                if (adapter.getCount() > 0) {
                    emptyy.setVisibility(View.GONE);
                    daybookdetailviewlist.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                }
            } else {
                daybookdetailviewlist.setEmptyView(emptyy);
            }
            daybookdetailviewlist.setExpanded(true);
            daybookdetailviewlist.setFastScrollEnabled(true);
            if (!isListScrolling) {
                img_pdf.setEnabled(false);
                adapter.isScrolling(true);
            } else {
                img_pdf.setEnabled(true);
                adapter.isScrolling(false);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


    img_pdf.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);

            // set title
            alertDialogBuilder.setTitle(R.string.app_name);

            // set dialog message
            alertDialogBuilder
                    .setMessage("Click yes to Print Report for : " + m.getDate())
                    .setCancelable(true)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, close
                            // current activity
                            Intent pdfreport = new Intent(context, Activity_Daybookpdf.class);
                            pdfreport.putExtra("date", m.getDate());
                            context.startActivity(pdfreport);
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
            Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
            nbutton.setTextColor(context.getResources().getColor(R.color.colorAccent));
            Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
            pbutton.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
            pbutton.setPadding(0, 10, 10, 0);
            pbutton.setTextColor(Color.WHITE);
            return false;

        }
    });

    return convertView;
}

public void setTransactionList(ArrayList<Daybook> newList) {
    entriesdaybook = newList;
    notifyDataSetChanged();
}

public void isScrolling(boolean isScroll) {
    isListScrolling = isScroll;
    Log.e("scrollcheck", String.valueOf(isListScrolling));
}

Error:

 *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
                                        java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
                                            at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
                                            at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
                                            at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
                                            at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
                                            at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
                                            at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
                                            at android.os.Binder.execTransact(Binder.java:451)

The crash logs doesn't seems to be the reason for the crash.

Try cleaning the project and run. If the issue still exists do disable instant run from the settings and run.

Hope this should get fixes and start running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM