Search code examples
androidandroid-edittextcursorandroid-sqliteonclicklistener

How to Retrieve Data from SQLite to EditText screen and scroll through with onClick Event


I am building an app which retrieves data using a cursor object from an SQLite database and populates each row to EditText on the screen. With the Click of the button the next row of data should be pasted to the EditText screen. Basically each button click event scrolls through to the next row of data and paste to Edit text on the screen. My Code does retrieve the data from SQLite and paste the first line of data to screen. However there is no response when I press the button the load the next line of data.

 public void viewStockMaterialDataToScreen(){
        final Cursor cursor = controller.getAllStockMaterialData();
        if (cursor.getCount() == 0) {
            Toast.makeText(DataEntry_DailyStockTake.this, "No data exists in the database", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cursor.moveToFirst()) {
                StockMaterial.setText(cursor.getString(1));
                UnitOM_Str.setText(cursor.getString(2));
                UnitOM_Ava.setText(cursor.getString(3));
                MinimumOQ.setText(cursor.getString(6));
        }
                button_Move_next.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                                           while (cursor.moveToNext()){}

                    }

       });
   }

Solution

  • I believe you have two issues.

    1. You are not setting the text's when you move to the next row, so the data displayed doesn't change.
    2. You are looping through the whole cursor and ending up at the position AfterLastRow when you click rather than just moving to the next row.

    So you appear to want something like :-

                button_Move_next.setOnClickListener(new View.OnClickListener() {
    
                    @Override
                    public void onClick(View v) {
                        if (cursor.moveToNext()) {
                            StockMaterial.setText(cursor.getString(1));
                            UnitOM_Str.setText(cursor.getString(2));
                            UnitOM_Ava.setText(cursor.getString(3));
                            MinimumOQ.setText(cursor.getString(6));
                        }
                    }
                }