Android SQLite Tutorial | CRUD Operation Example

crud operations in sqlite in android

Hello, developers. Welcome to Android SQLite Tutorial with Example.

This Android SQLite tutorial will cover two examples. The first example is simple and is for beginners.

The second one is regarding Android CRUD (create, read, update, and delete) operations in the SQLite Database.

1. Android Simple SQLite Example Step by Step For Beginners (Insert and Retrieve Data)

2. Android SQLite CRUD Operation Example

3. View Or Display SQLite Database Table In Android Studio

1. Android Simple SQLite Example Step by Step For Beginners (Insert and Retrieve Data)

SQLite is an in build database for every android device. In build means that you do not need to have any hosted server to store the database like MySQL. SQLite database is stored in android device(mobile and tablet) itself.

Because, it occupies very less memory space, SQLite works faster than other databases.

SQLite follows all the SQL standards and syntaxes. You need to write queries as per the SQL rules to insert, fetch, update or delete the data in SQLite.

Sometimes you want to give user an offline features, hence you need to store information in the SQLite Database.

You will learn how to store and fetch data in sqlite database in android example.

Generally, data is stored in the text format in sqlite especially when the data is about user information.

You need to create tables and columns as per the general structure of any database.

After that, you can insert the data in terms of the rows.

Output

First, check the output of SQLite In Android Studio example, then we will develop it.

Follow all the below steps to create a simple sqlite database example.

Step 1: Create a new project in Android Studio.

Create a new standalone and fresh new android studio project. Make sure you have select empty activity while creating new project.

Step 2: Creating DatabaseHelper class

Create a new class named “DatabaseHelper” and all below source code

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;

/**
 * Created by Parsania Hardik on 11/01/2016.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "student_database";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_STUDENTS = "students";
    private static final String KEY_ID = "id";
    private static final String KEY_FIRSTNAME = "name";

    /*CREATE TABLE students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone_number TEXT......);*/
   
    private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE "
            + TABLE_STUDENTS + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT );";
   
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        Log.d("table", CREATE_TABLE_STUDENTS);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       db.execSQL(CREATE_TABLE_STUDENTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS '" + TABLE_STUDENTS + "'");
        onCreate(db);
    }

    public long addStudentDetail(String student) {
        SQLiteDatabase db = this.getWritableDatabase();
        // Creating content values
        ContentValues values = new ContentValues();
        values.put(KEY_FIRSTNAME, student);
       // insert row in students table
        long insert = db.insert(TABLE_STUDENTS, null, values);

        return insert;
    }

    public ArrayList<String> getAllStudentsList() {
        ArrayList<String> studentsArrayList = new ArrayList<String>();
        String name="";
        String selectQuery = "SELECT  * FROM " + TABLE_STUDENTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                name = c.getString(c.getColumnIndex(KEY_FIRSTNAME));
               // adding to Students list
                studentsArrayList.add(name);
            } while (c.moveToNext());
            Log.d("array", studentsArrayList.toString());
        }
        return studentsArrayList;
    }
}

Step 3: Description of DatabaseHelper

Database name, Database version, table name and column names of tables are written as below.

    public static String DATABASE_NAME = "student_database";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_STUDENTS = "students";
    private static final String KEY_ID = "id";
    private static final String KEY_FIRSTNAME = "name";

The value of the DATABASE_VERSION variable describes the version of the database. It’s value is 1 at the first time when you create an app.

Understanding the most important part of the SQLite Database

See the below source code

 private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE "
            + TABLE_STUDENTS + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT );";

Above is the query to create a new table named “students”.

We need to write this type of query for each table we want to create.

In onCreate() method, we have written create statement for the table.

@Override
    public void onCreate(SQLiteDatabase db) {
       db.execSQL(CREATE_TABLE_STUDENTS);
}

If you want to make more than one table, then put above type of coding line for each table.

  • In onUpgrade() method, sqlite will deop already exist tables and then it will recreate all the tables.
  • onCreate() method is called within onUpgrade() method to create tables.
 @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS '" + TABLE_STUDENTS + "'");
        onCreate(db);
}

In following scenarios, you need to upgrade DATABASE_VERSION number in increment order.

  1. When you add, update or delete any column of any table in the whole database.
  2. If you update any column name of any table.
  3. After you add, update or delete any table.
  4. Update the table name and increase DATABASE_VERSION.
  • onUpgrade() method is called every time When you update the DATABASE_VERSION in the increment order.
  • addStudentDetail() method will add the name to the database.
  • getAllStudentsList() method will fetch all the values of names from database.

Step 5: Updating activity_main.xml

Put following code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorAccent"
    tools:context="com.exampledemo.parsaniahardik.simplesqlitedemonuts.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#fff"
        android:textSize="20sp"
        android:layout_marginTop="10dp"
        android:text="Enter Name to store in SQLite" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etname"
        android:background="#fff"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:hint="Enter Name"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnstore"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:text="Store"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnget"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:text="Get All Names from SQLite"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvnames"
        android:layout_marginLeft="10dp"
        android:textColor="#fff"
        android:textSize="20sp"
        android:layout_marginTop="10dp"
        android:text="Enter Name to store in SQLite" />

</LinearLayout>

One edittext, one textview and two buttons are defined in above code.

User will use edittext to enter the name of the student.

Step 6: Updating MainActivity.java

Add following  in MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private Button btnStore, btnGetall;
    private EditText etname;
    private DatabaseHelper databaseHelper;
    private TextView tvnames;
    private ArrayList<String> arrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseHelper = new DatabaseHelper(this);
        tvnames = (TextView) findViewById(R.id.tvnames);

        btnStore = (Button) findViewById(R.id.btnstore);
        btnGetall = (Button) findViewById(R.id.btnget);
        etname = (EditText) findViewById(R.id.etname);

        btnStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                databaseHelper.addStudentDetail(etname.getText().toString());
                etname.setText("");
                Toast.makeText(MainActivity.this, "Stored Successfully!", Toast.LENGTH_SHORT).show();
            }
        });
        btnGetall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                arrayList = databaseHelper.getAllStudentsList();
                tvnames.setText("");
                for (int i = 0; i < arrayList.size(); i++){
                     tvnames.setText(tvnames.getText().toString()+", "+arrayList.get(i));
                }
            }
        });
    }
}

When the user clicks on store button, the entered text is stored in the database as below.

 btnStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                databaseHelper.addStudentDetail(etname.getText().toString());
                etname.setText("");
                Toast.makeText(MainActivity.this, "Stored Successfully!", Toast.LENGTH_SHORT).show();
            }
 });

addStudentDeatils method is called here, which is present in the DatabaseHelper class.

This method defines the sql query to add the name in the sqlite database under the column “name”.

When the user clicks on the getall button, all the names are fetched from the database.

 btnGetall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                arrayList = databaseHelper.getAllStudentsList();
                tvnames.setText("");
                for (int i = 0; i < arrayList.size(); i++){
                     tvnames.setText(tvnames.getText().toString()+", "+arrayList.get(i));
                }
            }
});

getAllStudentsList method gives us all the names of the students in the arraylist.

Above method is also present in the DatabaseHelper class.

So that is all for SQLite in Android example.

Feel free to comment your queries and reviews in the comment section. Thank you šŸ™‚





2. Android SQLite CRUD Operation Example

Hello, learners. Welcome to Crud Operations In SQLite in Android Studio example.

In Crud Operations In SQLite in Android tutorial, you will learn to insert, update/edit and delete records of SQLite database.

First, check the output of Crud Operations In SQLite in Android example, then we will develop it.

Step 2: Creating UserModel class

Create a new Java class named “UserModel” and add below source code

import java.io.Serializable;

/**
 * Created by Parsania Hardik on 26-Apr-17.
 */
public class UserModel implements Serializable{

    private String name, hobby;
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
}

Step 3: Creating DatabaseHelper class

Create a new class named ā€œDatabaseHelperā€ and all below source code

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;

/**
 * Created by Parsania Hardik on 11/01/2016.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "user_database";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_USER = "users";
    private static final String KEY_ID = "id";
    private static final String KEY_FIRSTNAME = "name";
    private static final String KEY_HOBBY = "hobby";


    /*CREATE TABLE students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone_number TEXT......);*/

    private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE "
            + TABLE_USER + "(" + KEY_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT, "+ KEY_HOBBY + " TEXT );";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        Log.d("table", CREATE_TABLE_STUDENTS);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       db.execSQL(CREATE_TABLE_STUDENTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS '" + TABLE_USER + "'");
        onCreate(db);
    }

    public long addUserDetail(String name, String hobby) {
        SQLiteDatabase db = this.getWritableDatabase();
        // Creating content values
        ContentValues values = new ContentValues();
        values.put(KEY_FIRSTNAME, name);
        values.put(KEY_HOBBY, hobby);
       // insert row in students table
        long insert = db.insert(TABLE_USER, null, values);

        return insert;
    }

    public ArrayList<UserModel> getAllUsers() {
        ArrayList<UserModel> userModelArrayList = new ArrayList<UserModel>();

        String selectQuery = "SELECT  * FROM " + TABLE_USER;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                UserModel userModel = new UserModel();
                userModel.setId(c.getInt(c.getColumnIndex(KEY_ID)));
                userModel.setName(c.getString(c.getColumnIndex(KEY_FIRSTNAME)));
                userModel.setHobby(c.getString(c.getColumnIndex(KEY_HOBBY)));
               // adding to Students list
                userModelArrayList.add(userModel);
            } while (c.moveToNext());
         }
        return userModelArrayList;
    }

    public int updateUser(int id, String name, String hobby) {
        SQLiteDatabase db = this.getWritableDatabase();

        // Creating content values
        ContentValues values = new ContentValues();
        values.put(KEY_FIRSTNAME, name);
        values.put(KEY_HOBBY, hobby);
       // update row in students table base on students.is value
        return db.update(TABLE_USER, values, KEY_ID + " = ?",
                new String[]{String.valueOf(id)});
    }

    public void deleteUSer(int id) {

        // delete row in students table based on id
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_USER, KEY_ID + " = ?",
                new String[]{String.valueOf(id)});
    }

}

Step 4: Description of DatabaseHelper

Database name, Database version, table name and column names of tables are written as below.

    public static String DATABASE_NAME = "user_database";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_USER = "users";
    private static final String KEY_ID = "id";
    private static final String KEY_FIRSTNAME = "name";
    private static final String KEY_HOBBY = "hobby";

Understanding most important part of SQLite Database

In onCreate() method, create statement for the table is written.

@Override
    public void onCreate(SQLiteDatabase db) {
       db.execSQL(CREATE_TABLE_STUDENTS);
    }

In onUpgrade() method, already exist tables are dropped and then all tables are recreated.

onCreate() method is called within onUpgrade() method to create tables.

 @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS '" + TABLE_USER + "'");
        onCreate(db);
    }

In following scenarios, you need to upgrade DATABASE_VERSION number in increment order.

  1. When you add, update or delete any column of any table in the whole database.
  2. When you update any column name of any table.
  3. When you add, update or delete any table.
  4. When you update table name.

When DATABASE_VERSION is updatedin increment order, onUpgrade() method is called.

addUserDetail() method will add the user to SQLite Database.

getAllUsers() method will fetch all the users from SQLite Database.

updateUser() method will update the user’s information.

deleteUser() method will delete the user from SQLite.

Step 5: Creating lv_item.xml file

Create a new layout resource file named “lv_item.xml” and add below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000"
        android:orientation="vertical">

         <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:textColor="#fff"
             android:layout_marginTop="10dp"
            android:gravity="center_vertical"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:paddingLeft="10dp"
            android:text="Name" />
        <TextView
            android:id="@+id/hobby"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#fff"
            android:gravity="center_vertical"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:paddingLeft="10dp"
            android:text="Hobby" />


    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@color/colorAccent"/>

</LinearLayout>

Step 6: Preparing CustomAdapter class

Make a new Java class named “CustomAdapter” and paste following

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Parsania Hardik on 26-Apr-17.
 */
public class CustomAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<UserModel> userModelArrayList;

    public CustomAdapter(Context context, ArrayList<UserModel> userModelArrayList) {

        this.context = context;
        this.userModelArrayList = userModelArrayList;
    }


    @Override
    public int getCount() {
        return userModelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return userModelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.tvname = (TextView) convertView.findViewById(R.id.name);
            holder.tvcountry = (TextView) convertView.findViewById(R.id.hobby);


            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }

        holder.tvname.setText("Name: "+userModelArrayList.get(position).getName());
        holder.tvcountry.setText("Hobby: "+userModelArrayList.get(position).getHobby());

        return convertView;
    }

    private class ViewHolder {

        protected TextView tvname, tvcountry;
    }

}

Step 7: Getting All Users From SQLite Database

Create a new activity named “GetAllUsersActivity“.

Copy and paste following source code in GetAllUsersActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;

public class GetAllUsersActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<UserModel> userModelArrayList;
    private CustomAdapter customAdapter;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_all_users);

        listView = (ListView) findViewById(R.id.lv);

        databaseHelper = new DatabaseHelper(this);

        userModelArrayList = databaseHelper.getAllUsers();

        customAdapter = new CustomAdapter(this,userModelArrayList);
        listView.setAdapter(customAdapter);

       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               Intent intent = new Intent(GetAllUsersActivity.this,UpdateDeleteActivity.class);
               intent.putExtra("user",userModelArrayList.get(position));
               startActivity(intent);
           }
       });
    }
}

Add below code in activity_get_all_users.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.updatesqlitedemonuts.GetAllUsersActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginTop="10dp"
        android:textSize="20sp"
        android:textColor="#000"
        android:text="Data from SQLite"/>

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


    </ListView>

</LinearLayout>

Step 8: Updating and deleting user information

Create a new activity named “UpdateDeleteActivity

Add below source code in UpdateDeleteActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class UpdateDeleteActivity extends AppCompatActivity {

    private UserModel userModel;
    private EditText etname, ethobby;
    private Button btnupdate, btndelete;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_delete);

        Intent intent = getIntent();
        userModel = (UserModel) intent.getSerializableExtra("user");

        databaseHelper = new DatabaseHelper(this);

        etname = (EditText) findViewById(R.id.etname);
        ethobby = (EditText) findViewById(R.id.ethobby);
        btndelete = (Button) findViewById(R.id.btndelete);
        btnupdate = (Button) findViewById(R.id.btnupdate);

        etname.setText(userModel.getName());
        ethobby.setText(userModel.getHobby());

        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                databaseHelper.updateUser(userModel.getId(),etname.getText().toString(),ethobby.getText().toString());
                Toast.makeText(UpdateDeleteActivity.this, "Updated Successfully!", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(UpdateDeleteActivity.this,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        btndelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                databaseHelper.deleteUSer(userModel.getId());
                Toast.makeText(UpdateDeleteActivity.this, "Deleted Successfully!", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(UpdateDeleteActivity.this,MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

    }
}

Copy following code in activity_update_delete.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.updatesqlitedemonuts.UpdateDeleteActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:textColor="#000"
        android:textSize="20sp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etname"
        android:background="#fff"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:hint="Enter Name"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hobby"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:textColor="#000"
        android:textSize="20sp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/ethobby"
        android:background="#fff"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:hint="Enter Hobby"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:id="@+id/btnupdate"
        android:text="update"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:id="@+id/btndelete"
        android:text="delete"/>


</LinearLayout>

Step 9: Preparing MainActivity

Add below code in MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button btnStore, btnGetall;
    private EditText etname, ethobby;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseHelper = new DatabaseHelper(this);

        btnStore = (Button) findViewById(R.id.btnstore);
        btnGetall = (Button) findViewById(R.id.btnget);
        etname = (EditText) findViewById(R.id.etname);
        ethobby = (EditText) findViewById(R.id.ethobby);

        btnStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                databaseHelper.addUserDetail(etname.getText().toString(), ethobby.getText().toString());
                etname.setText("");
                ethobby.setText("");
                Toast.makeText(MainActivity.this, "Stored Successfully!", Toast.LENGTH_SHORT).show();
            }
        });

        btnGetall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,GetAllUsersActivity.class);
                startActivity(intent);
            }
        });

    }
}

Copy following in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorAccent"
    tools:context="com.exampledemo.parsaniahardik.simplesqlitedemonuts.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#fff"
        android:textSize="20sp"
        android:layout_marginTop="10dp"
        android:text="Enter Name, Hobby to store in SQLite" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etname"
        android:background="#fff"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:hint="Enter Name"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/ethobby"
        android:background="#fff"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:hint="Enter Hobby"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnstore"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:text="Store"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnget"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:text="Get All Users from SQLite"/>

</LinearLayout>

So that is all for crud operations in SQLite in Android example.

Feel free to comment your queries and reviews in the comment section. Thank you.

3. View Or Display SQLite Database Table In Android Studio

Hello, developers. Welcome to display or view SQLite database table in Android Studio Example.

Browse or view SQLite database in Android tutorial guides you to see or show whole SQLite database from Android Studio.

If you are making medium or large android project with SQLite, then you will need to view whole SQLite database.

At the end of the tutorial, you will be able to browse all tables, it’s columns and it’s rows.

Step 2: Opening Android Device Monitor.

In Android Studio, click on Android Device Monitor icon as shown in below image.

browse or view sqlite database in android
Click On Android Device Monitor

Now your android device monitor should start. If it doesn’t, then follow below steps(for windows.)

Go to directory(inside orange square) as shown in following image.

browse or view SQLite database in Android
Directory

Now right click on monitor and select “Run as administrator” as below image.

browse or view sqlite database in android
Admin

Now Android Device Monitor will start.

Note: If you find error like “Could not open Selected VM debug port (8700). Make sure you do not have another instance of DDMS or of the eclipse plugin running. If it’s being used by something else, choose a new port number in the preferences.”, click here for more reference. 

Step 3: Going through database file in device monitor.

Now select device or emulator from left panel, then select File Explorer from upper right tab bar.

Now select data->data as shown in following image.

browse or view SQLite database in Android
Data->Data

Find your project’s package name as shown in below image.

browse or view sqlite database in android
Package

After finding package name, click on that name. You will see following structure.

browse or view sqlite database in android
Structure

My database name is “user_database“. You should find your database here.

Single click on database name and then click on upper right icon as shown in above image to export database file.

After clicking on that button following will open.

Save DB

After saving, it is time to open this database file.

Step 4: Opening Database File

We will need Sqlitebrowser software to open database file.

Download Sqlitebrowser software from this link: sqlitebrowser.org

Install and open Sqlitebrowser. See below image to open database(File-> Open Database…).

browse or view sqlite database in android
Open DB

After clicking Open Database, following will open. Select All Files as shown in below image.

All Files

Select your database file and open it.

Step 5: Browsing Tables.

From tab bar, select “Browse Data“, then select table as shown in below image.

browse or view sqlite database in android
Select Table

After selecting table finally, you will see table as shown in below image.

Final

So that is all for browse or view SQLite database in Android example.