0%
Loading ...

SQLite in Android

This category contains tutorials related to SQLite in Android.

Delete data from SQLite database

In this tutorial, we’ll explore the process of deleting data from an SQLite database, building on our previous lesson where we covered updating data in the database. Specifically, we’ll focus on enhancing our Phone Book app by adding functionality to delete contact numbers. In our prior tutorial, we implemented a popup triggered by clicking a list item, offering two choices: update and delete. In this tutorial, we’ll guide you through the steps to delete a contact when the user selects the delete option. Let’s dive into the process of efficiently managing and modifying your SQLite database. To initiate the deletion of data, our first step involves introducing a new method named deleteData() within the DatabaseHelper class. This method serves as a crucial component in our process of removing specific records from the database. Take a look at the following code snippet to integrate this functionality into your application. DatabaseHelper Class Code: Following the implementation of the deleteData() method in our DatabaseHelper class, the subsequent action involves invoking this method in our main class when the user opts for the delete option within the popup. Please check out the provided code snippet to integrate this functionality into your main class. MainActivity Java Code: Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Delete data from SQLite database Read More »

Update Data in SQLite Database

In this tutorial, we will learn about how to Update data in SQLite Database. In the last tutorial, we have learned how to fetch data from the SQLite database. In this tutorial, we will update existing contacts. We will show a popup with options update and delete when a user will click on the list item. If a user will choose update option then we will show a new activity called UpdateContact where a user can update contact. First of all, we will show and popup when a user will click on an item of listView. To show popup first step is to add make a new file in res/menu (if there is no menu resource folder create a new menu folder by right-clicking on res) with options check this code: Menu XML code: <?xml version=”1.0″ encoding=”utf-8″?> <menu xmlns:android=”http://schemas.android.com/apk/res/android”> <item android:id=”@+id/update” android:title=”Update” /> <item android:id=”@+id/delete” android:title=”Delete” /> </menu> After this we will write code in MainActivity to show popup on list item click and to open UpdateContact activity on choose of Update option in popup. MainActivity Java Code: public class MainActivity extends AppCompatActivity { ListView listView; DatabaseHelper databaseHelper; List<contactmodel> contactList=new ArrayList<contactmodel>(); int i=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); databaseHelper = new DatabaseHelper(getApplicationContext()); Cursor cursor = databaseHelper.getData(); String namesArray[] = new String[cursor.getCount()]; while (cursor.moveToNext()) { namesArray[i] = cursor.getString(cursor.getColumnIndex(“NAME”)); contactList.add(new ContactModel(cursor.getInt(cursor.getColumnIndex(“ID”)),cursor.getString(cursor.getColumnIndex(“NAME”)),cursor.getString(cursor.getColumnIndex(“CONTACT”)))); i++; } ArrayAdapter<string> arrayAdapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_list_item_1, namesArray); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<!–?–> adapterView, View view,final int i, long l) { PopupMenu popup = new PopupMenu(getApplicationContext(), view); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.popup_menu, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case R.id.update: Intent intent=new Intent(getApplicationContext(),UpdateContact.class); intent.putExtra(“ID”,contactList.get(i).getId()); intent.putExtra(“NAME”,contactList.get(i).getName()); intent.putExtra(“CONTACT”,contactList.get(i).getNumber()); startActivity(intent); break; case R.id.delete: break; } return true; } }); popup.show(); } }); } } Now we will write code in layout file of UpdateContact activity. Check this code: UpdateContact 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=”.UpdateContact”> <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/updateContactB” android:text=”Update Contact”/> </LinearLayout> Now we will define a new method in DatabaseHelper to update contact information. check this code: 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 the 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; } } //getData method to fetch data from SQLite database public Cursor getData() { SQLiteDatabase db = this.getWritableDatabase(); String query = “SELECT * FROM ” + TABLE_NAME; Cursor cursor = db.rawQuery(query, null); return cursor; } //updateData method to update contact info public int updateData(int id, String name, String contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(“NAME”, name); contentValues.put(“CONTACT”, contact); int i = db.update(TABLE_NAME, contentValues, “ID =” + id, null); return i; } } Now we will write code in java file of UpdateContact activity to update contact information in SQLite database. UpdateContact Activity Java Code: public class UpdateContact extends AppCompatActivity { EditText nameET, contactET; Button updateContactB; DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_contact); nameET=(EditText)findViewById(R.id.nameET); contactET=(EditText)findViewById(R.id.contactET); updateContactB=(Button)findViewById(R.id.updateContactB); databaseHelper=new DatabaseHelper(getApplicationContext()); Bundle bundle=getIntent().getExtras(); final int id=bundle.getInt(“ID”); String name=bundle.getString(“NAME”); final String contact=bundle.getString(“CONTACT”); nameET.setText(name); contactET.setText(contact); updateContactB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { databaseHelper.updateData(id,nameET.getText().toString(),contactET.getText().toString()); startActivity(new Intent(getApplicationContext(),MainActivity.class)); } }); } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Update Data in SQLite Database Read More »

Fetch Data from SQLite Database

In this tutorial, we will learn about how to fetch data from SQLite Database. In the last tutorial, we learned how to add data in the SQLite database in this tutorial we will fetch data from the database. we will continue with the same app which we started in the last tutorial. In this tutorial, we will fetch data from and SQLite and will show data in the form of a list in MainActivity. We will start with the layout file of the main activity and add a listview. MainActivity 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” tools:context=”.MainActivity”> <ListView android:layout_width=”match_parent” android:layout_height=”match_parent” android:id=”@+id/listView” /> </LinearLayout> Before going to java file of MainActivity. We will add a method in DatabaseHelper class to which would help us to fetch data from SQLite database. Check this code: 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 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; } } //getMethod defined to get data from SQLite database public Cursor getData() { SQLiteDatabase db = this.getWritableDatabase(); String query = “SELECT * FROM ” + TABLE_NAME; Cursor cursor = db.rawQuery(query, null); return cursor; } } As you can see we have added getData() method in DatabaseHelper class to fetch data from the SQLite database. Here you can see I have used a new class called Cursor it is same as ResultSet in core java. Now we will create a model class for Contact called ContactModel which would later help us to save data in the form of a list. check this code of model class: ContactModel Class Code: public class ContactModel { int id; String name; String number; public ContactModel(int id, String name, String number) { this.id = id; this.name = name; this.number = number; } public int getId() { return id; } public String getName() { return name; } public String getNumber() { return number; } } After this step is our next step is to call this getData() method call in MainActivity and to show data in our ListView of MainActivity. Check this code here: MainActivity Java Code: public class MainActivity extends AppCompatActivity { ListView listView; DatabaseHelper databaseHelper; List<contactmodel> contactList=new ArrayList<contactmodel>(); String namesArray[]; int i=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=(ListView)findViewById(R.id.listView); databaseHelper=new DatabaseHelper(getApplicationContext()); Cursor cursor=databaseHelper.getData(); namesArray=new String[cursor.getCount()]; while (cursor.moveToNext()){ namesArray[i]=cursor.getString(cursor.getColumnIndex(“NAME”)); contactList.add(new ContactModel(cursor.getInt(cursor.getColumnIndex(“ID”)),cursor.getString(cursor.getColumnIndex(“NAME”)),cursor.getString(cursor.getColumnIndex(“CONTACT”)))); i++; } ArrayAdapter<string> arrayAdapter=new ArrayAdapter<>(getApplication(),android.R.layout.simple_list_item_1,namesArray); listView.setAdapter(arrayAdapter); } }   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Fetch Data from SQLite Database Read More »

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. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Insert data in SQLite database Read More »

What is SQLite in Android

In this tutorial we will learn about what is SQLite Database. Android provides the facility to use the SQLite database to store data on the device in the form of the file. SQLite is an open-source SQL database. Furthermore, it is so easy to use SQLite we can access data from the database without even establishing a connection with the database. Apart from this In android, there is a dedicated package to work with SQLite database. SQLite package: As I mention in previous paragraph that Android has dedicated package to work with SQLIte which is android.database.sqlite. This package have various classes which makes it so easy to use SQLIte in a application What we will do: In upcoming tutorials we will see how to create new SQLite database in device and how to perform operations like: Insert Data in Database Fetch Data from Database Update Data in Database Delete Data from Database To learn this we will create a small application called Phone Book in which we will store contact number. So stay connected and follow all the upcoming tutorials.   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

What is SQLite in Android Read More »

Scroll to Top
×