0

In my first run, I created 3 record and that worked nice!

But when I thought to add a new record and wanted all the 4(3+1) record to be Toasted, it only Toast the 3 past records!

public class MainActivity extends AppCompatActivity {

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

        try {
            SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("Database", MODE_PRIVATE, null);
            sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS database(name VARCHAR,age INT(3))");


            sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('ARGHA',20)");
            sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('CHANDRA',21)");
            sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('DHAR',22)");
            sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('AMIT',26)");


            Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM database", null);
            cursor.moveToFirst();


            int nameIndex = cursor.getColumnIndex("name");
            int ageIndex = cursor.getColumnIndex("age");


            while (cursor != null) {
                Toast.makeText(this, cursor.getString(nameIndex) + ":" + Integer.toString(cursor.getInt(ageIndex)), Toast.LENGTH_SHORT).show();
                cursor.moveToNext();

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

    }
}
Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
Argha
  • 1
  • 1
    I don't have an answer, but I do notice that your loop "while (cursor != null)" doesn't change the value of cursor inside the loop, so it will always be true. I'm guessing your loop only exits because getString() is throwing an exception. Probably "do {...} until (!cursor.moveToNext());" would be better, since moveToNext() returns false if there are no more records. – John Bayko Nov 05 '19 at 04:18
  • https://stackoverflow.com/questions/10723770/whats-the-best-way-to-iterate-an-android-cursor – Malavan Nov 05 '19 at 10:56

0 Answers0