Android SQLite Database Tutorial
Android SQLite Database Tutorial
BEGINNER
In Android, there are several ways to store persistent data. SQLite is one way of storing
app data. It is very lightweight database that comes with Android OS. In Android,
integrating SQLite is a tedious task as it needs writing lot of boilerplate code to store
simple data. Consider SQLite when your app needs to store simple data objects.
Alternatively you can consider Room Persistence Library for better APIs and easier
integration.
In this article we are going to learn basics of SQLite database with a realtime example of
Notes App.
VIDEO DEMO
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 1/40
11/05/2018 Android SQLite Database Tutorial
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 2/40
11/05/2018 Android SQLite Database Tutorial
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 3/40
11/05/2018 Android SQLite Database Tutorial
2. Open build.gradle under app directory and add RecyclerView dependency. The
RecyclerView will be used to display the Notes in list manner.
build.gradle
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// ..
implementation 'com.android.support:recyclerview-v7:26.1.0'
}
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#455399</color>
<color name="colorPrimaryDark">#455399</color>
<color name="colorAccent">#00c6ae</color>
<color name="msg_no_notes">#999</color>
<color name="hint_enter_note">#89c3c3c3</color>
<color name="timestamp">#858585</color>
<color name="note_list_text">#232323</color>
</resources>
dimens.xml
<resources>
<dimen name="fab_margin">16dp</dimen>
<dimen name="activity_margin">16dp</dimen>
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 4/40
11/05/2018 Android SQLite Database Tutorial
<dimen name="dot_margin_right">10dp</dimen>
<dimen name="msg_no_notes">26sp</dimen>
<dimen name="margin_top_no_notes">120dp</dimen>
<dimen name="lbl_new_note_title">20sp</dimen>
<dimen name="dimen_10">10dp</dimen>
<dimen name="input_new_note">20sp</dimen>
<dimen name="dot_height">30dp</dimen>
<dimen name="dot_text_size">40sp</dimen>
<dimen name="timestamp">14sp</dimen>
<dimen name="note_list_text">18sp</dimen>
</resources>
strings.xml
<resources>
<string name="app_name">Notes</string>
<string name="action_settings">Settings</string>
<string name="activity_title_home">Notes</string>
<string name="msg_no_notes">No notes found!</string>
<string name="lbl_new_note_title">New Note</string>
<string name="lbl_edit_note_title">Edit Note</string>
<string name="hint_enter_note">Enter your note!</string>
</resources>
4. Quickly create few packages named database, database/model, utils and view. Below
is the nal project structure and les we gonna need.
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 5/40
11/05/2018 Android SQLite Database Tutorial
We also need a model class to create Note objects to manage the notes easily.
The `notes` table needs three columns i.e `id`, `note` and `timestamp`.
Column `id` is de ned as Primary Key and Auto Increment which means each
note will be uniquely identi ed by its id.
Column `timestamp` stores the date and time of the note that is created.
Note.java
public class Note {
public static final String TABLE_NAME = "notes";
public Note() {
}
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 6/40
11/05/2018 Android SQLite Database Tutorial
6. Under database package, create a class named DatabaseHelper.java and extend the
class from SQLiteOpenHelper. This class holds the database related methods to perform
the CRUD operations.
onCreate() will be called only once when the app is installed. In this method, we
execute the create table sql statements to create necessary tables.
DatabaseHelper.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;
import java.util.List;
import info.androidhive.sqlite.database.model.Note;
/**
* Created by ravi on 15/03/18.
*/
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "notes_db";
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVe
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + Note.TABLE_NAME);
Now we’ll see the methods required to store or retrieve the notes. Add the following
methods to same class.
a. Inserting Note
ContentValues() is used to de ne the column name and its data to be stored. Here,
we are just setting the note value only ignoring `id` and `timestamp` as these two
will be inserted automatically.
Every time the database connection has to be closed once you are done with
database access. Calling db.close() closes the connection.
Once the note is inserted, the `id` of newly inserted note will be returned.
// insert row
long id = db.insert(Note.TABLE_NAME, null, values);
// close db connection
db.close();
b. Reading Notes
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 9/40
11/05/2018 Android SQLite Database Tutorial
getNote() takes already existed note `id` and fetches the note object.
if (cursor != null)
cursor.moveToFirst();
return note;
}
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 10/40
11/05/2018 Android SQLite Database Tutorial
note.setId(cursor.getInt(cursor.getColumnIndex(Note.COLUMN
note.setNote(cursor.getString(cursor.getColumnIndex(Note.C
note.setTimestamp(cursor.getString(cursor.getColumnIndex(N
notes.add(note);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return count
return count;
}
c. Updating Note
Updating data again requires writable access. Below the note is updated by its `id`.
// updating row
return db.update(Note.TABLE_NAME, values, Note.COLUMN_ID + " = ?",
new String[]{String.valueOf(note.getId())});
}
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 11/40
11/05/2018 Android SQLite Database Tutorial
d. Deleting Note
Deleting data also requires writable access. Below method deletes a note by nding its
`id`.
After adding all the methods, the DatabaseHelper.java class should be like this.
DatabaseHelper.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;
import java.util.List;
import info.androidhive.sqlite.database.model.Note;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "notes_db";
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 12/40
11/05/2018 Android SQLite Database Tutorial
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVe
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + Note.TABLE_NAME);
// insert row
long id = db.insert(Note.TABLE_NAME, null, values);
// close db connection
db.close();
if (cursor != null)
cursor.moveToFirst();
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 13/40
11/05/2018 Android SQLite Database Tutorial
return note;
}
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
notes.add(note);
} while (cursor.moveToNext());
}
// close db connection
db.close();
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 14/40
11/05/2018 Android SQLite Database Tutorial
// return count
return count;
}
// updating row
return db.update(Note.TABLE_NAME, values, Note.COLUMN_ID + " =
new String[]{String.valueOf(note.getId())});
}
RecyclerTouchListener.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by ravi on 21/02/18.
*/
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 15/40
11/05/2018 Android SQLite Database Tutorial
this.clicklistener = clicklistener;
gestureDetector = new GestureDetector(context, new GestureDete
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recycleView.findChildViewUnder(e.getX(),
if (child != null && clicklistener != null) {
clicklistener.onLongClick(child, recycleView.getCh
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clicklistener != null && gestureDetector.
clicklistener.onClick(child, rv.getChildAdapterPosition(ch
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowI
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 16/40
11/05/2018 Android SQLite Database Tutorial
MyDividerItemDecoration.java
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 17/40
11/05/2018 Android SQLite Database Tutorial
}
mOrientation = orientation;
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView p
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 18/40
11/05/2018 Android SQLite Database Tutorial
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
3. Adding Notes UI
Now we have the database helper class ready. Let’s quickly build the main interface and
integrate it with the database.
First we need an adapter to display the notes in list manner. For this, we need a layout le
and Adapter class.
8. Create new xml layout named note_list_row.xml. This layout holds the design of single
note item in the list.
note_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:foreground="?attr/selectableItemBackground"
android:paddingBottom="@dimen/dimen_10"
android:paddingLeft="@dimen/activity_margin"
android:paddingRight="@dimen/activity_margin"
android:paddingTop="@dimen/dimen_10">
<TextView
android:id="@+id/dot"
android:layout_width="wrap_content"
android:layout_height="@dimen/dot_height"
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 19/40
11/05/2018 Android SQLite Database Tutorial
android:layout_marginRight="@dimen/dot_margin_right"
android:layout_marginTop="@dimen/dimen_10"
android:includeFontPadding="false"
android:textColor="@color/colorAccent"
android:lineSpacingExtra="0dp"
android:textSize="@dimen/dot_text_size" />
<TextView
android:id="@+id/timestamp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/dot"
android:textColor="@color/timestamp"
android:textSize="@dimen/timestamp" />
<TextView
android:id="@+id/note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/timestamp"
android:layout_toRightOf="@id/dot"
android:textColor="@color/note_list_text"
android:textSize="@dimen/note_list_text" />
</RelativeLayout>
9. Under view package, create a class named NotesAdapter.java. This adapter class
renders the RecyclerView with de ned layout and data set.
NotesAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 20/40
11/05/2018 Android SQLite Database Tutorial
import info.androidhive.sqlite.R;
import info.androidhive.sqlite.database.model.Note;
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewT
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.note_list_row, parent, false);
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Note note = notesList.get(position);
holder.note.setText(note.getNote());
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 21/40
11/05/2018 Android SQLite Database Tutorial
@Override
public int getItemCount() {
return notesList.size();
}
/**
* Formatting timestamp to `MMM d` format
* Input: 2018-02-21 00:15:42
* Output: Feb 21
*/
private String formatDate(String dateStr) {
try {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH
Date date = fmt.parse(dateStr);
SimpleDateFormat fmtOut = new SimpleDateFormat("MMM d");
return fmtOut.format(date);
} catch (ParseException e) {
return "";
}
}
note_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/androi
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_margin"
android:paddingRight="@dimen/activity_margin"
android:paddingTop="@dimen/activity_margin">
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 22/40
11/05/2018 Android SQLite Database Tutorial
<TextView android:id="@+id/dialog_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/dimen_10"
android:fontFamily="sans-serif-medium"
android:lineSpacingExtra="8sp"
android:text="@string/lbl_new_note_title"
android:textColor="@color/colorAccent"
android:textSize="@dimen/lbl_new_note_title"
android:textStyle="normal" />
<EditText
android:id="@+id/note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:gravity="top"
android:hint="@string/hint_enter_note"
android:inputType="textCapSentences|textMultiLine"
android:lines="4"
android:textColorHint="@color/hint_enter_note"
android:textSize="@dimen/input_new_note" />
</LinearLayout>
11. Open the layout les of main activity (activity_main.xml and content_main.xml) and
add RecyclerView widget. I am also changing the icon of FAB here.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http:/
android:id="@+id/coordinator_layout"
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="info.androidhive.sqlite.view.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 23/40
11/05/2018 Android SQLite Database Tutorial
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@drawable/ic_add_white_24dp" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="info.androidhive.sqlite.view.MainActivity"
tools:showIn="@layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/empty_notes_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 24/40
11/05/2018 Android SQLite Database Tutorial
android:layout_marginTop="@dimen/margin_top_no_notes"
android:fontFamily="sans-serif-light"
android:text="@string/msg_no_notes"
android:textColor="@color/msg_no_notes"
android:textSize="@dimen/msg_no_notes" />
</RelativeLayout>
showNoteDialog() open the alert dialog to create new note. This dialog will be
shown by tapping FAB.
createNote() inserts new note in database and adds the newly inserted note in
RecyclerView list.
showActionsDialog() shows a dialog with Edit and Delete options. This dialog can
be invoked by long pressing the note in the list.
Selecting Edit, opens the update note dialog with already existed note text. You can
modify the note text and update it in database by calling updateNote() method.
deleteNote() deletes a note from database. The deleted note is again removed
from list by calling notifyItemRemoved() on adapter.
toggleEmptyNotes() toggles the visibility of notes and empty note view depending
on the count (db.getNotesCount() > 0) of notes.
MainActivity.java
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 25/40
11/05/2018 Android SQLite Database Tutorial
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import info.androidhive.sqlite.R;
import info.androidhive.sqlite.database.DatabaseHelper;
import info.androidhive.sqlite.database.model.Note;
import info.androidhive.sqlite.utils.MyDividerItemDecoration;
import info.androidhive.sqlite.utils.RecyclerTouchListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = findViewById(R.id.coordinator_layout);
recyclerView = findViewById(R.id.recycler_view);
noNotesView = findViewById(R.id.empty_notes_view);
db = new DatabaseHelper(this);
notesList.addAll(db.getAllNotes());
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 26/40
11/05/2018 Android SQLite Database Tutorial
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new MyDividerItemDecoration(thi
recyclerView.setAdapter(mAdapter);
toggleEmptyNotes();
/**
* On long press on RecyclerView item, open alert dialog
* with options to choose
* Edit and Delete
* */
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(
recyclerView, new RecyclerTouchListener.ClickListener(
@Override
public void onClick(View view, final int position) {
}
@Override
public void onLongClick(View view, int position) {
showActionsDialog(position);
}
}));
}
/**
* Inserting new note in db
* and refreshing the list
*/
private void createNote(String note) {
// inserting note in db and getting
// newly inserted note id
long id = db.insertNote(note);
if (n != null) {
// adding new note to array list at 0 position
notesList.add(0, n);
toggleEmptyNotes();
}
}
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 27/40
11/05/2018 Android SQLite Database Tutorial
/**
* Updating note in db and updating
* item in the list by its position
*/
private void updateNote(String note, int position) {
Note n = notesList.get(position);
// updating note text
n.setNote(note);
// updating note in db
db.updateNote(n);
toggleEmptyNotes();
}
/**
* Deleting note from SQLite and removing the
* item from the list by its position
*/
private void deleteNote(int position) {
// deleting the note from db
db.deleteNote(notesList.get(position));
toggleEmptyNotes();
}
/**
* Opens dialog with Edit - Delete options
* Edit - 0
* Delete - 0
*/
private void showActionsDialog(final int position) {
CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 28/40
11/05/2018 Android SQLite Database Tutorial
if (which == 0) {
showNoteDialog(true, notesList.get(position), posi
} else {
deleteNote(position);
}
}
});
builder.show();
}
/**
* Shows alert dialog with EditText options to enter / edit
* a note.
* when shouldUpdate=true, it automatically displays old note and
* button text to UPDATE
*/
private void showNoteDialog(final boolean shouldUpdate, final Note
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(get
View view = layoutInflaterAndroid.inflate(R.layout.note_dialog
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog
dialogBox.cancel();
}
});
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 29/40
11/05/2018 Android SQLite Database Tutorial
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickL
@Override
public void onClick(View v) {
// Show toast message when no text is entered
if (TextUtils.isEmpty(inputNote.getText().toString()))
Toast.makeText(MainActivity.this, "Enter note!", T
return;
} else {
alertDialog.dismiss();
}
/**
* Toggling list and empty notes view
*/
private void toggleEmptyNotes() {
// you can check notesList.size() > 0
if (db.getNotesCount() > 0) {
noNotesView.setVisibility(View.GONE);
} else {
noNotesView.setVisibility(View.VISIBLE);
}
}
}
If you have followed the article carefully, you can see the app running very smoothly as
shown in the video demo.
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 30/40
11/05/2018 Android SQLite Database Tutorial
5. Further Reading
Once you are comfortable with SQLite, check out Android SQLite Database with Multiple
Tables that explains how to handle SQLite when your app needs more than one table.
Happy Coding
Change Log
Updated On 16th Mar 2018 (Updated code and introduced Notes App)
Ravi Tamada
Ravi is hardcore Android programmer and Android programming
has been his passion since he compiled his rst hello-world
program. Solving real problems of Android developers through
tutorials has always been interesting part for him.
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 31/40
11/05/2018 Android SQLite Database Tutorial
D A T A BASE SQ L I TE
RELATED POSTS
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 32/40
11/05/2018 Android SQLite Database Tutorial
Sort by Newest
Recommend 214 ⤤ Share
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 33/40
11/05/2018 Android SQLite Database Tutorial
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
Hi Abelardo
All the articles will work with little modifications in case of any problem. I need
to spend at least a month to update them all. Are you facing any problem in
following this article?
△ ▽ • Reply • Share ›
Okay.
△ ▽ • Reply • Share ›
BM • 2 months ago
thank you for this useful article, as i was trying to create a datebase to store my data.
my app consists of have live score for football matches. Is it possible to have a save
button on every live match that is occurring, when the button is pressed it
automatically saves that specific match in an another activity called bookmark? do
you have any article on that?
△ ▽ • Reply • Share ›
You won't find the code depending on your requirements. Always you have to
understand the concepts and build the modules on your own.
△ ▽ • Reply • Share ›
△ ▽ • Reply • Share ›
see more
△ ▽ • Reply • Share ›
I'm asking because I have a bit more complex app and database, and now I'm
starting to get a few crashes because I had some leaked Cursor objects. So I'm now
closing all Cursors after I'm done with them. But now I also tried enabling strict mode
for my app, and it reveals that I'm not closing the SQLiteDatabase objects and they
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 37/40
11/05/2018 Android SQLite Database Tutorial
can also leak. So should I perhaps keep only one SQLiteDatabase object in the
DatabaseHandler class?
Last but not least - the SQLiteOpenHelper class (and therefore also the
DatabaseHandler class) have a close() method. Should I for example close the
DatabaseHandler object in onPause or onStop in Fragments/Activites to prevent
memory leaks?
Those single Activity examples are really nice to get started, but once things get more
complicated, there is not enough sources and examples on how we should handle
these things.
△ ▽ • Reply • Share ›
Sorry mate, I missed out your valuable comment. I got your points. I just
updated the article with an example app. Please check once.
△ ▽ • Reply • Share ›
Great:)
△ ▽ • Reply • Share ›
Regards,
△ ▽ • Reply • Share ›
Have you checked your Query? Print the query in Log. and see whether it is
proper or not.
△ ▽ • Reply • Share ›
https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 40/40