This is the third part of SQLite for Android series tutorials with examples. Here you can find the first part – SQLite for Android Part 2: Insert Data

In this example is explained hot to view insered data in to already created database and table.

NOTE: Dont forget to add ButterKnife binding in onCreate() in MainActivity:

After creating Person.db file and student_table and adding values in it, now we are going to view the inserted data.

Layout

Add a button to the activity_main.xml layout:

Then we add viewAll() method in our DataBaseHelper class:

This method returns Cursor. Cursor is interface that provides random read-write access to the result set returned * by a database query . Raw query is for querying from the data base. In this case we SELECT * (all) FROM table name and null for now, which means get all values from STUDENT_TABLE. This is for storing the data from database to the Cursor object so we can access this data in our MainActivity.

Alert Dialog for showing data

In MainActivity, we are creating Dalog. In this Alert Dialog we set title and a message for showing the results.

Get all data implementation

Cursor is for getting the data that is created in getAllData() method that is previously created. We have check if the data is empty. If is not, we apply adding records and values from the database to the Alert Dialog. The numbers in getString() methods are index of the columns in the database table. Index 0 is ID, Index 1 is NAME etc. The method append(“some string”) is used for adding some text to the string that we are appending to.

While is used for iterating trough out values in the table in the database. This is actually a very long string that is build with the StringBuilder class.  It will add string to the stringBuilder as long as moveToNext() boolean method is true. After there is nothing to move to next, the iteration is stopped and the string is ready for showing in the Alert Dialog.

 

You can get the whole project on GitHub /SQLiteDatabaseAndroid

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *