Introduction

Android is one of the most popular operating systems for mobile. You can create the database and manipulate the data in Android apps using SQLite. The database is used to store and retrieve the data. Here, I will show you how to work with SQLite in Android applications using Android Studio.
Requirements

Steps to be followed

Carefully follow the below steps to work with SQLite Android applications using Android Studio, and I have included the source code below.
Step 1
Open Android Studio and start a new project.
Android
Step 2
Put the application name and company domain. If you wish to use C++ for coding the project, mark the "Include C++ support" checkbox and click Next.
Android
Step 3
Select the Android minimum SDK version. After you chose the minimum SDK, it will show the approximate percentage of people using that SDK. Then, click Next.
Android
Step 4
Choose "Basic Activity" and click Next.
Android
Step 5
Put the activity name and layout name. Android Studio basically takes the java class name that you provide as an activity name. Click Finish.
Android
Step 6
Go to activity_main.xml and click the text button. This XML file contains the designing code for the Android app. Into the activity_main.xml, copy and paste the below code.
Activity_main.xml code
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  3. android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  4. android:paddingRight="@dimen/activity_horizontal_margin"
  5. android:paddingTop="@dimen/activity_vertical_margin"
  6. android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
  7. <EditText
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:id="@+id/user_Input"
  11. android:layout_alignParentTop="true"
  12. android:layout_centerHorizontal="true"
  13. android:layout_marginTop="69dp"
  14. android:width="300dp"
  15. android:inputType=""
  16. tools:ignore="LabelFor" />
  17. <Button
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:text="@string/add"
  21. android:id="@+id/add_Button"
  22. android:layout_below="@+id/user_Input"
  23. android:layout_alignStart="@+id/user_Input"
  24. android:layout_marginTop="40dp"
  25. android:onClick="addButtonClicked" />
  26. <Button
  27. android:layout_width="wrap_content"
  28. android:layout_height="wrap_content"
  29. android:text="@string/delete"
  30. android:id="@+id/delete_Button"
  31. android:layout_alignTop="@+id/add_Button"
  32. android:layout_alignEnd="@+id/user_Input"
  33. android:onClick="deleteButtonClicked" />
  34. <TextView
  35. android:layout_width="wrap_content"
  36. android:layout_height="wrap_content"
  37. android:textAppearance="?android:attr/textAppearanceLarge"
  38. android:text="Large Text"
  39. android:id="@+id/records_TextView"
  40. android:layout_centerVertical="true"
  41. android:layout_centerHorizontal="true" />
  42. </RelativeLayout>
Android
Step 7
In the MainActivity.java file, copy and paste the below code. Java programming is the back-end language for Android. Do not replace your package name, otherwise, the app will not run.
MainActivity.java code
  1. package ganeshannt.sqlite;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.widget.EditText;
  6. import android.widget.TextView;
  7. public class MainActivity extends Activity {
  8. // Declare references
  9. EditText userInput;
  10. TextView recordsTextView;
  11. MyDBHandler dbHandler;
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. userInput = (EditText) findViewById(R.id.user_Input);
  17. recordsTextView = (TextView) findViewById(R.id.records_TextView);
  18. dbHandler = new MyDBHandler(this, null, null, 1);
  19. printDatabase();
  20. }
  21. //Print the database
  22. public void printDatabase(){
  23. String dbString = dbHandler.databaseToString();
  24. recordsTextView.setText(dbString);
  25. userInput.setText("");
  26. }
  27. //add your elements onclick methods.
  28. //Add a product to the database
  29. public void addButtonClicked(View view){
  30. // dbHandler.add needs an object parameter.
  31. Products product = new Products(userInput.getText().toString());
  32. dbHandler.addProduct(product);
  33. printDatabase();
  34. }
  35. //Delete items
  36. public void deleteButtonClicked(View view){
  37. // dbHandler delete needs string to find in the db
  38. String inputText = userInput.getText().toString();
  39. dbHandler.deleteProduct(inputText);
  40. printDatabase();
  41. }
  42. }
Step 8
Create a new MyDBHelper.java file (File ⇒ New ⇒Java class).
In MyDBHelper.java, copy and paste the below code. Java programming contains SQLite query. Do not replace your package name, otherwise, the app will not run.
MyDBHelper.java code
  1. package ganeshannt.sqlite;
  2. // This class handles all the database activities
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteOpenHelper;
  5. import android.database.Cursor;
  6. import android.content.Context;
  7. import android.content.ContentValues;
  8. public class MyDBHandler extends SQLiteOpenHelper{
  9. private static final int DATABASE_VERSION = 1;
  10. private static final String DATABASE_NAME = "productDB.db";
  11. public static final String TABLE_PRODUCTS = "products";
  12. public static final String COLUMN_ID = "_id";
  13. public static final String COLUMN_PRODUCTNAME = "productname";
  14. //We need to pass database information along to superclass
  15. public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
  16. super(context, DATABASE_NAME, factory, DATABASE_VERSION);
  17. }
  18. @Override
  19. public void onCreate(SQLiteDatabase db) {
  20. String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
  21. COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
  22. COLUMN_PRODUCTNAME + " TEXT " +
  23. ");";
  24. db.execSQL(query);
  25. }
  26. //Lesson 51
  27. @Override
  28. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  29. db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
  30. onCreate(db);
  31. }
  32. //Add a new row to the database
  33. public void addProduct(Products product){
  34. ContentValues values = new ContentValues();
  35. values.put(COLUMN_PRODUCTNAME, product.get_productname());
  36. SQLiteDatabase db = getWritableDatabase();
  37. db.insert(TABLE_PRODUCTS, null, values);
  38. db.close();
  39. }
  40. //Delete a product from the database
  41. public void deleteProduct(String productName){
  42. SQLiteDatabase db = getWritableDatabase();
  43. db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";");
  44. }
  45. // this is goint in record_TextView in the Main activity.
  46. public String databaseToString(){
  47. String dbString = "";
  48. SQLiteDatabase db = getWritableDatabase();
  49. String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";// why not leave out the WHERE clause?
  50. //Cursor points to a location in your results
  51. Cursor recordSet = db.rawQuery(query, null);
  52. //Move to the first row in your results
  53. recordSet.moveToFirst();
  54. //Position after the last row means the end of the results
  55. while (!recordSet.isAfterLast()) {
  56. // null could happen if we used our empty constructor
  57. if (recordSet.getString(recordSet.getColumnIndex("productname")) != null) {
  58. dbString += recordSet.getString(recordSet.getColumnIndex("productname"));
  59. dbString += "\n";
  60. }
  61. recordSet.moveToNext();
  62. }
  63. db.close();
  64. return dbString;
  65. }
  66. }
Step 9
Create a new Products.java file (File ⇒ New ⇒Java class).
In the Products.java file, copy and paste the below code. Do not replace your package name otherwise, the app will not run.
Products.java code
  1. package ganeshannt.sqlite;
  2. public class Products {
  3. private int _id;
  4. private String _productname;
  5. //Added this empty constructor in lesson 50 in case we ever want to create the object and assign it later.
  6. public Products(){
  7. }
  8. public Products(String productName) {
  9. this._productname = productName;
  10. }
  11. public int get_id() {
  12. return _id;
  13. }
  14. public void set_id(int _id) {
  15. this._id = _id;
  16. }
  17. public String get_productname() {
  18. return _productname;
  19. }
  20. public void set_productname(String _productname) {
  21. this._productname = _productname;
  22. }
  23. }
Step 10
Click the "Make Project" option and run the project.
Android
Deliverables
Here, we have successfully created a Text entry application.
Android
Add data
Android
Android
Delete data
Android
Deleted
Android
Don’t forget to like and follow me. If you have any doubt, just comment below.
Source code
https://github.com/GaneshanNT/sqlite