Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Update Data in Back4App Database in Android?
Next article icon

How to Update Data to SQLite Database in Android?

Last Updated : 03 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

We have seen How to Create and Add Data to SQLite Database in Android as well as How to Read Data from SQLite Database in Android. We have performed different SQL queries for reading and writing our data to SQLite database. In this article, we will take a look at updating data to SQLite database in Android. 

What we are going to build in this article?  

We will be building a simple application in which we were already adding as well as reading the data. Now we will simply update our data in a new activity and we can get to see the updated data. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Creating a new activity for updating our course

As we want to update our course, so for this process we will be creating a new activity where we will be able to update our courses in the SQLite database. To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as UpdateCourseActivity and create new Activity. Make sure to select the empty activity. 

Step 2: Working with the activity_update_course.xml file

Navigate to the app > res > Layout > activity_update_course.xml and add the below code to it. 

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"     tools:context=".UpdateCourseActivity">      <!--Edit text to enter course name-->     <EditText         android:id="@+id/idEdtCourseName"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="10dp"         android:hint="Enter course Name" />      <!--edit text to enter course duration-->     <EditText         android:id="@+id/idEdtCourseDuration"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="10dp"         android:hint="Enter Course Duration" />      <!--edit text to display course tracks-->     <EditText         android:id="@+id/idEdtCourseTracks"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="10dp"         android:hint="Enter Course Tracks" />      <!--edit text for course description-->     <EditText         android:id="@+id/idEdtCourseDescription"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="10dp"         android:hint="Enter Course Description" />      <!--button for updating our course-->     <Button         android:id="@+id/idBtnUpdateCourse"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_margin="10dp"         android:text="Update Course"         android:textAllCaps="false" />      </LinearLayout> 

Step 3: Updating our DBHandler class

Navigate to the app > java > your app's package name > DBHandler and add the below code to it. In this, we simply have to create a new method to update our course. 

Java
// below is the method for updating our courses public void updateCourse(String originalCourseName, String courseName, String courseDescription,                              String courseTracks, String courseDuration) {                  // calling a method to get writable database.         SQLiteDatabase db = this.getWritableDatabase();         ContentValues values = new ContentValues();                  // on below line we are passing all values         // along with its key and value pair.         values.put(NAME_COL, courseName);         values.put(DURATION_COL, courseDuration);         values.put(DESCRIPTION_COL, courseDescription);         values.put(TRACKS_COL, courseTracks);                  // on below line we are calling a update method to update our database and passing our values.         // and we are comparing it with name of our course which is stored in original name variable.         db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName});         db.close(); } 

Below is the updated code for the DBHandler.java file after adding the above code snippet.

Java
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper;  import java.util.ArrayList;  public class DBHandler extends SQLiteOpenHelper {      // creating a constant variables for our database.     // below variable is for our database name.     private static final String DB_NAME = "coursedb";      // below int is our database version     private static final int DB_VERSION = 1;      // below variable is for our table name.     private static final String TABLE_NAME = "mycourses";      // below variable is for our id column.     private static final String ID_COL = "id";      // below variable is for our course name column     private static final String NAME_COL = "name";      // below variable id for our course duration column.     private static final String DURATION_COL = "duration";      // below variable for our course description column.     private static final String DESCRIPTION_COL = "description";      // below variable is for our course tracks column.     private static final String TRACKS_COL = "tracks";      // creating a constructor for our database handler.     public DBHandler(Context context) {         super(context, DB_NAME, null, DB_VERSION);     }      // below method is for creating a database by running a sqlite query     @Override     public void onCreate(SQLiteDatabase db) {         // on below line we are creating         // an sqlite query and we are         // setting our column names         // along with their data types.         String query = "CREATE TABLE " + TABLE_NAME + " ("                 + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "                 + NAME_COL + " TEXT,"                 + DURATION_COL + " TEXT,"                 + DESCRIPTION_COL + " TEXT,"                 + TRACKS_COL + " TEXT)";          // at last we are calling a exec sql         // method to execute above sql query         db.execSQL(query);     }      // this method is use to add new course to our sqlite database.     public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {          // on below line we are creating a variable for         // our sqlite database and calling writable method         // as we are writing data in our database.         SQLiteDatabase db = this.getWritableDatabase();          // on below line we are creating a         // variable for content values.         ContentValues values = new ContentValues();          // on below line we are passing all values         // along with its key and value pair.         values.put(NAME_COL, courseName);         values.put(DURATION_COL, courseDuration);         values.put(DESCRIPTION_COL, courseDescription);         values.put(TRACKS_COL, courseTracks);          // after adding all values we are passing         // content values to our table.         db.insert(TABLE_NAME, null, values);          // at last we are closing our         // database after adding database.         db.close();     }      // we have created a new method for reading all the courses.     public ArrayList<CourseModal> readCourses() {         // on below line we are creating a         // database for reading our database.         SQLiteDatabase db = this.getReadableDatabase();          // on below line we are creating a cursor with query to read data from database.         Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);          // on below line we are creating a new array list.         ArrayList<CourseModal> courseModalArrayList = new ArrayList<>();          // moving our cursor to first position.         if (cursorCourses.moveToFirst()) {             do {                 // on below line we are adding the data from cursor to our array list.                 courseModalArrayList.add(new CourseModal(cursorCourses.getString(1),                         cursorCourses.getString(4),                         cursorCourses.getString(2),                         cursorCourses.getString(3)));             } while (cursorCourses.moveToNext());             // moving our cursor to next.         }         // at last closing our cursor         // and returning our array list.         cursorCourses.close();         return courseModalArrayList;     }      // below is the method for updating our courses     public void updateCourse(String originalCourseName, String courseName, String courseDescription,                              String courseTracks, String courseDuration) {          // calling a method to get writable database.         SQLiteDatabase db = this.getWritableDatabase();         ContentValues values = new ContentValues();          // on below line we are passing all values         // along with its key and value pair.         values.put(NAME_COL, courseName);         values.put(DURATION_COL, courseDuration);         values.put(DESCRIPTION_COL, courseDescription);         values.put(TRACKS_COL, courseTracks);          // on below line we are calling a update method to update our database and passing our values.         // and we are comparing it with name of our course which is stored in original name variable.         db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName});         db.close();     }      @Override     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {         // this method is called to check if the table exists already.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);         onCreate(db);     } } 

Step 4: Updating our CourseRVAdapter.java  class

As we will be opening a new activity to update our course. We have to add on click listener for the items of our RecycleView. For adding onClickListener() to our recycler view items navigate to the app > java > your app's package name > CourseRVAdapter class and simply add an onClickListener() for our RecyclerView item. Add the below code to your adapter class. 

Java
// below line is to add on click listener for our recycler view item. holder.itemView.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                                // on below line we are calling an intent.                 Intent i = new Intent(context, UpdateCourseActivity.class);                  // below we are passing all our values.                 i.putExtra("name", modal.getCourseName());                 i.putExtra("description", modal.getCourseDescription());                 i.putExtra("duration", modal.getCourseDuration());                 i.putExtra("tracks", modal.getCourseTracks());                  // starting our activity.                 context.startActivity(i);         } }); 

Below is the updated code for the CourseRVAdapter.java file after adding the above code snippet.

Java
import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;  import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView;  import java.util.ArrayList;  public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {      // variable for our array list and context     private ArrayList<CourseModal> courseModalArrayList;     private Context context;      // constructor     public CourseRVAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) {         this.courseModalArrayList = courseModalArrayList;         this.context = context;     }      @NonNull     @Override     public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {         // on below line we are inflating our layout         // file for our recycler view items.         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);         return new ViewHolder(view);     }      @Override     public void onBindViewHolder(@NonNull ViewHolder holder, int position) {         // on below line we are setting data         // to our views of recycler view item.         CourseModal modal = courseModalArrayList.get(position);         holder.courseNameTV.setText(modal.getCourseName());         holder.courseDescTV.setText(modal.getCourseDescription());         holder.courseDurationTV.setText(modal.getCourseDuration());         holder.courseTracksTV.setText(modal.getCourseTracks());          // below line is to add on click listener for our recycler view item.         holder.itemView.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                                  // on below line we are calling an intent.                 Intent i = new Intent(context, UpdateCourseActivity.class);                  // below we are passing all our values.                 i.putExtra("name", modal.getCourseName());                 i.putExtra("description", modal.getCourseDescription());                 i.putExtra("duration", modal.getCourseDuration());                 i.putExtra("tracks", modal.getCourseTracks());                  // starting our activity.                 context.startActivity(i);             }         });     }      @Override     public int getItemCount() {         // returning the size of our array list         return courseModalArrayList.size();     }      public class ViewHolder extends RecyclerView.ViewHolder {          // creating variables for our text views.         private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV;          public ViewHolder(@NonNull View itemView) {             super(itemView);             // initializing our text views             courseNameTV = itemView.findViewById(R.id.idTVCourseName);             courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);             courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);             courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks);         }     } } 

Step 5: Working with the UpdateCourseActivity.java file 

Navigate to the app > java > your app's package name > UpdateCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail.

Java
import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;  import androidx.appcompat.app.AppCompatActivity;  public class UpdateCourseActivity extends AppCompatActivity {      // variables for our edit text, button, strings and dbhandler class.     private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;     private Button updateCourseBtn;     private DBHandler dbHandler;     String courseName, courseDesc, courseDuration, courseTracks;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_update_course);                  // initializing all our variables.         courseNameEdt = findViewById(R.id.idEdtCourseName);         courseTracksEdt = findViewById(R.id.idEdtCourseTracks);         courseDurationEdt = findViewById(R.id.idEdtCourseDuration);         courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);         updateCourseBtn = findViewById(R.id.idBtnUpdateCourse);          // on below line we are initializing our dbhandler class.         dbHandler = new DBHandler(UpdateCourseActivity.this);                  // on below lines we are getting data which          // we passed in our adapter class.         courseName = getIntent().getStringExtra("name");         courseDesc = getIntent().getStringExtra("description");         courseDuration = getIntent().getStringExtra("duration");         courseTracks = getIntent().getStringExtra("tracks");                  // setting data to edit text          // of our update activity.         courseNameEdt.setText(courseName);         courseDescriptionEdt.setText(courseDesc);         courseTracksEdt.setText(courseTracks);         courseDurationEdt.setText(courseDuration);          // adding on click listener to our update course button.         updateCourseBtn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                                  // inside this method we are calling an update course                  // method and passing all our edit text values.                 dbHandler.updateCourse(courseName, courseNameEdt.getText().toString(), courseDescriptionEdt.getText().toString(), courseTracksEdt.getText().toString(), courseDurationEdt.getText().toString());                                  // displaying a toast message that our course has been updated.                 Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show();                                  // launching our main activity.                 Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class);                 startActivity(i);             }         });     } } 

Now run your app and see the output of the app. Make sure to add data to the SQLite database before updating it. 

Output:

Below is the complete project file structure after performing the update operation:


Next Article
How to Update Data in Back4App Database in Android?

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

  • How to Update Data in Realm Database in Android?
    In previous articles, we have seen adding and reading data from our realm database in Android. In that article, we were adding course details in our database and reading the data in the form of a list. In this article, we will take a look at updating this data in our android app.  What we are going
    7 min read
  • How to Update Data in Back4App Database in Android?
    In the previous article, we have seen adding as well as reading data from our Bac4App database in the Android app. In this article, we will take a look at Updating this data in your database.  What we are going to build in this article?  We will be building a simple application in which we will be u
    7 min read
  • How to Update Data to SQLite Database in Android using Jetpack Compose?
    We have seen How to Create and Add Data to SQLite Database in Android using Jetpack Compose as well as How to Read Data from SQLite Database in Android using Jetpack Compose. We have performed different SQL queries for reading and writing our data to SQLite database. In this article, we will take a
    15 min read
  • How to Create and Add Data to SQLite Database in Android?
    SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required. In this article, we will take a look at creating an SQLite database in the Android app and adding data to that database in the Android app. This is a series of 4 ar
    8 min read
  • How to Delete Data in SQLite Database in Android?
    In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at adding delete operation for deleting our items stored in the SQLite database.  What we are going to build in this article?
    8 min read
  • How to Read Data from SQLite Database in Android?
    In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in RecyclerView. What we are going to
    12 min read
  • How to pre populate database in Android using SQLite Database
    Introduction : Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Databas
    7 min read
  • How to View and Locate SQLite Database in Android Studio?
    SQLite is an open-source relational database that is used to perform database operations on android devices such as storing, manipulating, or retrieving persistent data from the database. In this article, we will learn how to view and locate SQLite database in Android Studio using device file explor
    2 min read
  • How to Update Data in API using Retrofit in Android?
    We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Retrofit library for updating our data in our API.  What we are going to build in this article?  We will be
    6 min read
  • How to Update Data in Firebase Firestore in Android?
    In the previous article, we have seen on How to Add Data to Firebase Firestore in Android, How to Read the data from Firebase Firestore in Android. Now we will see How to Update this added data inside our Firebase Firestore. Now we will move towards the implementation of this updating data in Androi
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences