Insert data in SQLite database

In this tutorial, we will learn about how to Insert Data in SQLite. Here we will start a new application called Phone Book to save contact number. Our first step would be to create a new SQLite database and table to save our contact details on the device. After that in upcoming tutorials, we will fetch, update and delete data in the SQLite database. Please follow all the steps:

First of all, we need an Activity to add a new contact in our database so I will create a new Activity called AddContact. Check the code of layout file and java file here.

AddContact Activity 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"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".AddContact">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/nameET"
        android:hint="Please Enter Name"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/contactET"
        android:hint="Please Enter Contact Number"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/addContactB"
        android:text="ADD CONTACT"/>

</LinearLayout>

Our next step is to write code in Java file of this activity but before writing code in Java file of AddContact Activity. I will make another class to handle SQLite database operations(table creation, insertion, deletion, updating etc). Create a new class called DatabaseHelper.

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 a 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;
        }
    }
}

Here you can see we have written several lines in our DatabaseHelper class. First of all, inherit class called SQLiteOpenHelper in our class and then we have created a constructor and after that, we implemented two abstract methods of SQLiteOpenHelper class. Apart from this, we have created our own method to insert data in the database.

After writing code in DatabaseHelper class we will go back to AddContact activity and now we will write code in Activity Java file. Check this code:

AddContact Activity code:

public class AddContact extends AppCompatActivity {

    EditText nameET, contactET;
    Button addContactB;
    DatabaseHelper databaseHelper;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contact);
        nameET=(EditText)findViewById(R.id.nameET);
        contactET=(EditText)findViewById(R.id.contactET);
        addContactB=(Button)findViewById(R.id.addContactB);
        
        databaseHelper=new DatabaseHelper(getApplicationContext());
        
        addContactB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nameS=nameET.getText().toString();
                String contactS=contactET.getText().toString();
                
                boolean result=databaseHelper.insertData(nameS,contactS);
                
                if(result)
                    Toast.makeText(getApplicationContext(),"Done",Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Here you can see we have called a function insertData of which we created in DatabaseHelper class to insert data in the database. After that, we showed the result Done if data will enter successfully and Error in the case of any problem. In the next tutorial, we will fetch data from the database and will show data in another activity.

Spread the love