In this tutorial, we will learn about how to fetch data from SQLite Database. In the last tutorial, we learned how to add data in the SQLite database in this tutorial we will fetch data from the database. we will continue with the same app which we started in the last tutorial. In this tutorial, we will fetch data from and SQLite and will show data in the form of a list in MainActivity. We will start with the layout file of the main activity and add a listview.

MainActivity XML Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"
         />
</LinearLayout>

Before going to java file of MainActivity. We will add a method in DatabaseHelper class to which would help us to fetch data from SQLite database. Check this code:

DatabaseHelper Class Code:

public class DatabaseHelper extends SQLiteOpenHelper {

    //writing database name
    private static final String DATABASE_NAME = "PhoneBook.db";
    //writing table name
    private static final String TABLE_NAME = "Contacts_Table";


    //Constructor here
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }


    //On create and onUpgrade these two are abstract methods in SQLiteOpenHelper class
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        //use this execSQL method to create new table in database
        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT , CONTACT TEXT )");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }


    //Creating this method to insert data in table
    public boolean insertData(String name, String contact) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("NAME", name);
        cv.put("CONTACT", contact);

        long result = db.insert(TABLE_NAME, null, cv);

        if (result == -1) {
            return false;

        } else {
            return true;
        }
    }


    //getMethod defined to get data from SQLite database
    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(query, null);
        return cursor;
    }
}

As you can see we have added getData() method in DatabaseHelper class to fetch data from the SQLite database. Here you can see I have used a new class called Cursor it is same as ResultSet in core java. Now we will create a model class for Contact called ContactModel which would later help us to save data in the form of a list. check this code of model class:

ContactModel Class Code:

public class ContactModel {
    int id;
    String name;
    String number;

    public ContactModel(int id, String name, String number) {
        this.id = id;
        this.name = name;
        this.number = number;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getNumber() {
        return number;
    }
}

After this step is our next step is to call this getData() method call in MainActivity and to show data in our ListView of MainActivity. Check this code here:

MainActivity Java Code:

public class MainActivity extends AppCompatActivity {

    ListView listView;
    DatabaseHelper databaseHelper;
    List<contactmodel> contactList=new ArrayList<contactmodel>();
    String namesArray[];
    int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.listView);

        databaseHelper=new DatabaseHelper(getApplicationContext());

        Cursor cursor=databaseHelper.getData();

        namesArray=new String[cursor.getCount()];

        while (cursor.moveToNext()){
            namesArray[i]=cursor.getString(cursor.getColumnIndex("NAME"));
            contactList.add(new 
ContactModel(cursor.getInt(cursor.getColumnIndex("ID")),cursor.getString(cursor.getColumnIndex("NAME")),cursor.getString(cursor.getColumnIndex("CONTACT"))));
            i++;
        }

        ArrayAdapter<string> arrayAdapter=new ArrayAdapter<>(getApplication(),android.R.layout.simple_list_item_1,namesArray);
        listView.setAdapter(arrayAdapter);

    }
}