Breaking News

How to create a Sqlite Database in Android



In this post, I will show you how to create an SQLite Database in an Android app.

SQLite Database is used in the Android app to store heavy lists like student records, Bookmarks and History data when we creating an Web Browser app.


For that, First of all we will create a Java Class file called Database Helper and in that java file, we extend a class called SQLite Open Helper to use Database.


DatabaseHelper.java

 package harpreet.studio.mysqlitedatabase;  
 import android.app.ActionBar;  
 import android.content.ContentValues;  
 import android.content.Context;  
 import android.database.Cursor;  
 import android.database.sqlite.SQLiteDatabase;  
 import android.database.sqlite.SQLiteOpenHelper;  
 import android.provider.ContactsContract;  
 import androidx.annotation.Nullable;  
 public class DatabaseHelper extends SQLiteOpenHelper {  
   public static final String Database_name = "Students.db";  
   public static final String Table_name = "Student_table";  
   public static final String col_id = "Id";  
   public static final String col_name = "name";  
   public static final String col_marks = "marks";  
   public DatabaseHelper(@Nullable Context context) {  
     super(context, Database_name, null, 1);  
   }  
   @Override  
   public void onCreate(SQLiteDatabase db) {  
       db.execSQL("create table " + Table_name +" (Id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT , marks INTEGER)");  
   }  
   @Override  
   public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {  
       sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+Table_name);  
       onCreate(sqLiteDatabase);  
   }  
 }  

In this, we extend the SQliteopenhelper class and implement its methods and create a constructor also.

Now in our Students.db file, We have a Table named Student_table. and Their three columns Id, name and marks.

When we call this java file constructor our database will be created.

For Inserting in SQLite Database Click Here
For Displaying from SQLite Database Click Here
For Updating in SQLite Database Click Here
For Deleting from SQLite Database Click Here


Follow us for more posts like this,
Subscribe Harpreet studio on Youtube
Like Harpreet Studio on Facebook


No comments