Android SQLite Database CRUD Tutorial with Example Application

android-sqlite-database-crud-tutorial-min

This is a step by step android CRUD tutorial where we’ll create an Android application that demonstrates Android’s SQLite database capabilities.

Operations such as create, read, update and delete (CRUD) in Android is an essential skill every aspiring Android developer must have.

In this post, we will cover the following contents:

1.0 Source Code Output
2.0 Create a record in Android SQLite Database
3.0 Count records from Android SQLite Database
4.0 Read records from Android SQLite Database
5.0 Update a record in Android SQLite Database
6.0 Delete a record in Android SQLite Database
7.0 Download Source Code
8.0 What’s Next?
9.0 Notes

1.0 Source Code Output

We have to know where are we heading.

1.1 LEVEL 1 Source Code Output

android-crud-tutorial-update

2.0 Create a record in Android SQLite Database

This will answer your question about how to create a record in Android SQLite database.

2.1 Place a “Create Student” button

2.1.1 Put a “Create Student” button on your res/layout/activity_main.xml

2.1.2 Remove the “Hello World!” TextView there

2.1.3 Make button text to “Create Student”

2.1.4 Make button id value to “@+id/buttonCreateStudent”

Code should look like the following.

<Button
    android:id="@+id/buttonCreateStudent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Create Student" />

2.2 Put an OnClickListener for the button

2.2.1 We will set up the OnClickListener of the “Create Student” button.

2.2.2 We can identify the button by its ID “buttonCreateStudent”

2.2.3 The following code will be placed inside the onCreate() method, under setContentView(R.layout.activity_main); code of your java/your.package.name/MainActivity.java file.

Button buttonCreateStudent = (Button) findViewById(R.id.buttonCreateStudent);
buttonCreateStudent.setOnClickListener(new OnClickListenerCreateStudent());

2.3 Create a listener class “OnClickListenerCreateStudent.java”

2.3.1 Right click on your package name > click “New” > click “Java Class” > put the name “OnClickListenerCreateStudent” > click “OK”

2.3.2 Remove the default code except the first line (your package code).

2.3.2 Put the following code on OnClickListenerCreateStudent.java

import android.view.View;

public class OnClickListenerCreateStudent implements View.OnClickListener {
    @Override
    public void onClick(View view) {

    }
}

2.4 Prepare your student input form

2.4.1 Right click on your res/layout/ directory > Click “New” > Click “File” > Name it “student_input_form.xml”

2.4.2 Put the following code inside student_input_form.xml

<RelativeLayout 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" >

    <EditText
        android:id="@+id/editTextStudentFirstname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:hint="Student Firstname"
        android:singleLine="true" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editTextStudentEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextStudentFirstname"
        android:hint="Student Email"
        android:singleLine="true" />

</RelativeLayout>

2.5 Show the “create form” to user

2.5.1 Go back and open your “OnClickListenerCreateStudent.java”

2.5.2 Get the application context, this is needed to inflate an XML layout file. Put the following code inside the onClick() method.

final Context context = view.getContext();

2.5.3 Inflate the student_input_form.xml, this will make UI elements or widgets accessible using code. Put the following code after the code in 2.5.2

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.student_input_form, null, false);

2.5.4 List down form widgets inside student_input_form.xml as “final” variables. This is because we will use them inside an AlertDialog. Put the following code after the code in 2.5.3

final EditText editTextStudentFirstname = (EditText) formElementsView.findViewById(R.id.editTextStudentFirstname);
final EditText editTextStudentEmail = (EditText) formElementsView.findViewById(R.id.editTextStudentEmail);

2.5.5 Create an AlertDialog with the inflated student_input_form.xml and an “Add” button. Put the following code after the code in 2.5.4

new AlertDialog.Builder(context)
    .setView(formElementsView)
    .setTitle("Create Student")
    .setPositiveButton("Add",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                dialog.cancel();
            }

        }).show();

2.5.5 Try to run. The following image should be the output when you clicked the “Create Student” button.

android-crud-tutorial-create

2.6 Save user input

2.6.1 Inside the AlertDialog’s “Add” onClick() method, we will save the record.

2.6.2 Get the user inputted values using the following code. Put them inside the AlertDialog’s “Add” onClick() method

String studentFirstname = editTextStudentFirstname.getText().toString();
String studentEmail = editTextStudentEmail.getText().toString();

2.6.3 We’re actually using an OOP approach here. Create a new “ObjectStudent.java” file with properties “firstname” and “email”. Put the following code inside ObjectStudent.java file.

public class ObjectStudent {

    int id;
    String firstname;
    String email;

    public ObjectStudent(){

    }
}

2.6.4 Going back to AlertDialog’s “Add” onClick() method, set the input values as a object, so we can save it to the database.

ObjectStudent objectStudent = new ObjectStudent();
objectStudent.firstname= studentFirstname;
objectStudent.email= studentEmail;

2.6.5 Create a new “DatabaseHandler.java” file. This file will handle all the SQLite database connection. It will have the following code.

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    protected static final String DATABASE_NAME = "StudentDatabase";

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

    @Override
    public void onCreate(SQLiteDatabase db) {

        String sql = "CREATE TABLE students " +
                "( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "firstname TEXT, " +
                "email TEXT ) ";

        db.execSQL(sql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        String sql = "DROP TABLE IF EXISTS students";
        db.execSQL(sql);

        onCreate(db);
    }

}

2.6.6 Create new “TableControllerStudent.java” file, extending the DatabaseHandler. This file will control all the operations related to the student’s table. It will have the following code.

public class TableControllerStudent extends DatabaseHandler {

    public TableControllerStudent(Context context) {
        super(context);
    }

}

2.6.7 Do the create() method for creating new record. The following method is inside TableControllerStudent class.

public boolean create(ObjectStudent objectStudent) {

    ContentValues values = new ContentValues();

    values.put("firstname", objectStudent.firstname);
    values.put("email", objectStudent.email);

    SQLiteDatabase db = this.getWritableDatabase();

    boolean createSuccessful = db.insert("students", null, values) > 0;
    db.close();

    return createSuccessful;
}

2.6.8 Go back inside the AlertDialog of OnClickListenerCreateStudent.java file and call the create() method of TableControllerStudent class.

boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);

2.6.9 Tell the user whether insert was a success or failure. We will use Android Toast to do this task.

if(createSuccessful){
    Toast.makeText(context, "Student information was saved.", Toast.LENGTH_SHORT).show();
}else{
    Toast.makeText(context, "Unable to save student information.", Toast.LENGTH_SHORT).show();
}

2.6.10 Try to run. You should be able to see a toast message and create a record.

3.0 Count records from Android SQLite Database

3.1 On your res/layout/activity_main.xml, place a TextView under your “Create Student” button.

<TextView
    android:id="@+id/textViewRecordCount"
    android:gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/buttonCreateStudent"
    android:text="0 records found"
    android:padding="1dp" />

3.2 On your MainActivity.java file, create a countRecords() method

public void countRecords() {

}

3.3 On your TableControllerStudent.java, create a count() method.

public int count() {

    SQLiteDatabase db = this.getWritableDatabase();

    String sql = "SELECT * FROM students";
    int recordCount = db.rawQuery(sql, null).getCount();
    db.close();

    return recordCount;

}

3.4 Go back to your MainActivity.java > countRecords() method and call the count() method you just created.

int recordCount = new TableControllerStudent(this).count();

3.5 Display the count to the text view.

TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");

3.6 On your MainActivity.java > onCreate() method, call the countRecords() method.

countRecords();

3.7 On your OnClickListenerCreateStudent.java > inside AlertDialog, also call the countRecords() method. This will change the count value everytime a new record was created.

countRecords();

3.8 Try to run. Output should look like the following.

android-crud-tutorial-count-records

4.0 Read records from Android SQLite Database

4.1 On your activity_main.xml, put a ScrollView with LinearLayout inside. Put the following code under the TextView textViewRecordCount.

<ScrollView
    android:id="@+id/scrollViewRecords"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textViewRecordCount" >

    <LinearLayout
        android:id="@+id/linearLayoutRecords"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

    </LinearLayout>
</ScrollView>

4.2 On your TableControllerStudent.java, create a read() method.

public List<ObjectStudent> read() {

    List<ObjectStudent> recordsList = new ArrayList<ObjectStudent>();

    String sql = "SELECT * FROM students ORDER BY id DESC";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(sql, null);

    if (cursor.moveToFirst()) {
        do {

            int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
            String studentFirstname = cursor.getString(cursor.getColumnIndex("firstname"));
            String studentEmail = cursor.getString(cursor.getColumnIndex("email"));

            ObjectStudent objectStudent = new ObjectStudent();
            objectStudent.id = id;
            objectStudent.firstname = studentFirstname;
            objectStudent.email = studentEmail;

            recordsList.add(objectStudent);

        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();

    return recordsList;
}

4.3 On your MainActivity.java, create the readRecords() method. This will display database records to user interface.

public void readRecords() {

    LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
    linearLayoutRecords.removeAllViews();

    List<ObjectStudent> students = new TableControllerStudent(this).read();

    if (students.size() > 0) {

        for (ObjectStudent obj : students) {

            int id = obj.id;
            String studentFirstname = obj.firstname;
            String studentEmail = obj.email;

            String textViewContents = studentFirstname + " - " + studentEmail;

            TextView textViewStudentItem= new TextView(this);
            textViewStudentItem.setPadding(0, 10, 0, 10);
            textViewStudentItem.setText(textViewContents);
            textViewStudentItem.setTag(Integer.toString(id));

            linearLayoutRecords.addView(textViewStudentItem);
        }

    }

    else {

        TextView locationItem = new TextView(this);
        locationItem.setPadding(8, 8, 8, 8);
        locationItem.setText("No records yet.");

        linearLayoutRecords.addView(locationItem);
    }

}

4.4 Call readRecords() method on your MainActivity.java > onCreate() method

readRecords();

4.5 On your OnClickListenerCreateStudent.java > inside AlertDialog, call the readRecords() method as well, so it will refresh the list every time we add new record.

((MainActivity) context).readRecords();

4.6 Try to run. Output should look like the following.

android-crud-tutorial-read-records

5.0 Update a record in Android SQLite Database

5.1 Create new OnLongClickListenerStudentRecord.java file. We will use long click to give user an update option.

public class OnLongClickListenerStudentRecord implements OnLongClickListener {

    @Override
    public boolean onLongClick(View view) {

        return false;
    }

}

5.2 Set the OnLongClickListener for each of the display records. Go to your MainActivity.java > readRecords() method, inside the ‘for’ loop, put the following code under the textViewStudentItem.setTag(Integer.toString(id)); code.

textViewStudentItem.setOnLongClickListener(new OnLongClickListenerStudentRecord());

5.3 Go back to your OnLongClickListenerStudentRecord.java file, set the following as class variables

Context context;
String id;

5.4 Put the following code inside the onLongClick() method.

context = view.getContext();
id = view.getTag().toString();

5.5 Add an AlertDialog with simple list view for ‘Edit’ and ‘Delete’ options. Put the following code below 5.4

final CharSequence[] items = { "Edit", "Delete" };

new AlertDialog.Builder(context).setTitle("Student Record")
    .setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            dialog.dismiss();

        }
    }).show();

5.6 Try to run. Output should look like the following.

android-crud-tutorial-edit-delete

5.7 Inside the onClick() method of AlertDialog in section 5.5, put the following code. “Edit” has an item index of 0.

if (item == 0) {
    editRecord(Integer.parseInt(id));
}

5.8 On your OnLongClickListenerStudentRecord.java, add the following editRecord() method.

public void editRecord(final int studentId) {

}

5.9 Inside the editRecord() method, we will use the following code to read single record. Data will be used to fill up the student form for updating it.

final TableControllerStudent tableControllerStudent = new TableControllerStudent(context);
ObjectStudent objectStudent = tableControllerStudent.readSingleRecord(studentId);

5.10 On your TableControllerStudent.java, add the following method readSingleRecord() code.

public ObjectStudent readSingleRecord(int studentId) {

    ObjectStudent objectStudent = null;

    String sql = "SELECT * FROM students WHERE id = " + studentId;

    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery(sql, null);

    if (cursor.moveToFirst()) {

        int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
        String firstname = cursor.getString(cursor.getColumnIndex("firstname"));
        String email = cursor.getString(cursor.getColumnIndex("email"));

        objectStudent = new ObjectStudent();
        objectStudent.id = id;
        objectStudent.firstname = firstname;
        objectStudent.email = email;

    }

    cursor.close();
    db.close();

    return objectStudent;

}

5.11 Going back to OnLongClickListenerStudentRecord.java > editRecrod() method, inflate student_input_form.xml, this time we will use it for updating a record.

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.student_input_form, null, false);

5.12 List down form elements. Put the following code under the code in section 5.11

final EditText editTextStudentFirstname = (EditText) formElementsView.findViewById(R.id.editTextStudentFirstname);
final EditText editTextStudentEmail = (EditText) formElementsView.findViewById(R.id.editTextStudentEmail);

5.13 Set single record values to the EditText form elements. Put the following code under the code in section 5.12

editTextStudentFirstname.setText(objectStudent.firstname);
editTextStudentEmail.setText(objectStudent.email);

5.14 Show an AlertDialog with the form and single record filling it up. Put the following code under the code in section 5.13

new AlertDialog.Builder(context)
    .setView(formElementsView)
    .setTitle("Edit Record")
    .setPositiveButton("Save Changes",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                dialog.cancel();
            }

        }).show();

5.15 Inside the AlertDialog > onClick() method, create the object with the updated value. We are still in the editRecord() method.

ObjectStudent objectStudent = new ObjectStudent();
objectStudent.id = studentId;
objectStudent.firstname = editTextStudentFirstname.getText().toString();
objectStudent.email = editTextStudentEmail.getText().toString();

5.16 Update the record and tell the user whether it was updated or not. Put the following code under the code in section 5.15

boolean updateSuccessful = tableControllerStudent.update(objectStudent);

if(updateSuccessful){
    Toast.makeText(context, "Student record was updated.", Toast.LENGTH_SHORT).show();
}else{
    Toast.makeText(context, "Unable to update student record.", Toast.LENGTH_SHORT).show();
}

5.17 On your TableControllerStudent.java, add the update() method.

public boolean update(ObjectStudent objectStudent) {

    ContentValues values = new ContentValues();

    values.put("firstname", objectStudent.firstname);
    values.put("email", objectStudent.email);

    String where = "id = ?";

    String[] whereArgs = { Integer.toString(objectStudent.id) };

    SQLiteDatabase db = this.getWritableDatabase();

    boolean updateSuccessful = db.update("students", values, where, whereArgs) > 0;
    db.close();

    return updateSuccessful;

}

5.18 Refresh the count and record list. Put the following code under the code in section 5.16

((MainActivity) context).countRecords();
((MainActivity) context).readRecords();

5.19 Try to run. The output should look like the following.

android-crud-tutorial-update

6.0 Delete a record in Android SQLite Database

6.1 Go to your OnLongClickListenerStudentRecord.java > onLongClick() method > inside the AlertDialog onClick() method. Put the following code after the first if statement.

else if (item == 1) {

    boolean deleteSuccessful = new TableControllerStudent(context).delete(Integer.parseInt(id));

    if (deleteSuccessful){
        Toast.makeText(context, "Student record was deleted.", Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(context, "Unable to delete student record.", Toast.LENGTH_SHORT).show();
    }

    ((MainActivity) context).countRecords();
    ((MainActivity) context).readRecords();

}

6.2 Go back to your TableControllerStudent.java and add the following delete code.

public boolean delete(int id) {
    boolean deleteSuccessful = false;

    SQLiteDatabase db = this.getWritableDatabase();
    deleteSuccessful = db.delete("students", "id ='" + id + "'", null) > 0;
    db.close();

    return deleteSuccessful;

}

7.0 Download Source Code

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:

✔ Value or skill upgrade it can bring you, orYES
✔ Income you can get from your Android app project or business.YES
✔ Precious time you save.YES
✔ Expert advice you can get from me, just in case you have any questions with the code.YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

7.1 Download the LEVEL 1 Source Code

FEATURESLEVEL 1
Source code developed in Android StudioYES
Create recordYES
Read productYES
Update productYES
Delete productYES
Read single recordYES
Count recordsYES
Easy to understand UIYES
Free source code updateYES
Free email support (mike@codeofaninja.com) for 6 monthsYES
LEVEL 1: BUY AND DOWNLOAD NOW USING

Let me know if you have any questions. If this Android CRUD Tutorial helps you, please like or share it to your friends! Thanks!

8.0 What’s Next?

Today we have learned how to create, read, update and delete a record from Android SQLite database.

Did you know that you can do the same using text files? Read our next tutorial: Working with Text Files in Android

9.0 Notes

Important note:

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page! Thank you!

82 replies
  1. Tim
    Tim says:

    Thanks so much for the great tutorial! I have successfully develop a new Assets Management Systems apps with SQLite db based on this tutorial for my office project. Keep sharing and helping those newbie like me! XOXO

    Reply
  2. Christian
    Christian says:

    Thanks great tutorial. I have a problem by delete.the number of records don’t decrease. By adding a new item it starts with 2. not with 1. Please what can I do to fix this…

    Reply
  3. Alexey
    Alexey says:

    Very interesting tutorial! But there is an error in the program.

    When you need to update an any item of the database (not the last one), after you click Edit you see not the correct values for edited item in the Edit form. The program picks values from the last created item but not from the item you need. I guess the error in LocationsTableController.java getLocation method. You move the cursor to the first db item, but the cursor must be moved to the db item selected by fieldLocationId.

    Reply
    • Mike Dalisay
      Mike Dalisay says:

      Thanks for pointing that out @79104e1d41701c0b29a1d7bce793dcfe:disqus! That’s certainly a bug, I forgot to include a WHERE clause to get the proper record. I updated the code a bit. Thanks again!

      Reply
  4. choyno
    choyno says:

    WOW dude this tutorial is so great <3 <3

    just have some correction in here

    String studentFirstname = cursor.getString(cursor.getColumnIndex("studentFirstname"));
    String studentEmail = cursor.getString(cursor.getColumnIndex("studentEmail"));

    ObjectStudent objectStudent = new ObjectStudent();
    objectStudent.id = id;
    objectStudent.studentFirstname = studentFirstname;
    objectStudent.studentEmail = studentEmail;

    ——————–TO

    String studentFirstname = cursor.getString(cursor.getColumnIndex("firstname"));
    String studentEmail = cursor.getString(cursor.getColumnIndex("email"));

    ObjectStudent objectStudent = new ObjectStudent();
    objectStudent.id = id;
    objectStudent.firstname = studentFirstname;
    objectStudent.email = studentEmail;

    Reply
    • ninjazhai
      ninjazhai says:

      Glad you liked and followed this tutorial @choyno! Wow, thanks for pointing out a correction, I’ll update the post! :)

      Reply
      • Gudo Hombe
        Gudo Hombe says:

        Hi guys,

        On which file do I put this code:

        ObjectStudent objectStudent = new ObjectStudent();
        objectStudent.id = id;
        objectStudent.firstname = studentFirstname;
        objectStudent.email = studentEmail

        I have followed step by step so far and I am stuck here as I am not sure where to put this code. when I run the code on the “second run it” I got recordCount ZERO. Which means I am not writing to anything to the database as I am not getting a count of something I have entered into the database.

        Thank you

        Gudo

        Reply
    • ninjazhai
      ninjazhai says:

      @choyno: We didn’t have to use getters and setters in this case since we can assign the value this way:
      objectStudent.firstname = firstname;

      and access the value this way:
      String firstname = objectStudent.firstname;

      Reply
  5. Tito Leiva
    Tito Leiva says:

    This tutorial is awesome! Some mistakes or incomplete methods arguments but it’s ok. In fact, it’s better because I can understand what is happening. Thank you so much!

    Reply
    • ninjazhai
      ninjazhai says:

      Glad it helped @Tito Leiva, thanks for your awesome and honest comment. I will continue to improve this post and make things clearer for the readers like you. :)

      Reply
  6. Risk Taker
    Risk Taker says:

    Hi ! how can i I do If the user not insert data in form and click the data is not added and give the hint please insert the required fields, waiting your prompt response

    Reply
    • ninjazhai
      ninjazhai says:

      Hello @risk_taker:disqus , do you mean the form validation? For example the user did not enter anything and clicked the save button?

      Reply
  7. ninjapanda
    ninjapanda says:

    Hi, great tutorial. Do you have any idea how do i link the input data i have from the table to generate an XY chart using android’s aChartEngine? I’m using the first example.

    Reply
    • ninjazhai
      ninjazhai says:

      Hello @disqus_DAIVsdOvYX:disqus, sorry but I haven’t tried the aChartEngine yet, but basically you just have to capture its onclicklistener and execute the insert command… (sorry for the late reply too…)

      Reply
  8. Veniamin
    Veniamin says:

    Hi.
    The archive accompanied with the article looks to be damaged. Cannot open it. Could you please re-download the complete source code.
    Thanks.

    Reply
    • ninjazhai
      ninjazhai says:

      Shay, I haven’t tried that yet, but I think, what you are trying to do is all about web services… you can search for JSON too…

      Reply
  9. Raylite
    Raylite says:

    I’ve been trying to understand and use SQLite for so many months with nothing but confusion. This tutorial is by far the easiest to understand and I’ve even learned a few more OOP tricks in Java from how well put together this example it is. 好厉害! Thanks for your efforts, difficult to search for such good tutorials in China without Google.

    Reply
  10. Youssef Echcherif El Kettani
    Youssef Echcherif El Kettani says:

    Hello and thank you for this tutorial! I have done everything as you mentioned in the descriptions but encountered a problem. The update functionality does not work. When i debug and check the contents, it always returns the id as -1. What do you think the problem is? Problem solved, I had a small mistake in my code.

    Reply
  11. bee
    bee says:

    error on bold text;

    package com.test;

    public class ObjectStudent {
    int id;

    String firstname;

    String email;

    public ObjectStudent(){

    ObjectStudent objectStudent = new ObjectStudent();

    objectStudent.studentFirstname = studentFirstname;

    objectStudent.studentEmail = studentEmail;

    }

    }

    Reply
  12. bee
    bee says:

    error in bold txt!

    new AlertDialog.Builder(context)

    .setView(formElementsView)

    .setTitle(“Create Student”)

    .setPositiveButton(“Add”,

    new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int id) {

    dialog.cancel();

    String studentFirstname = editTextStudentFirstname.getText().toString();

    String studentEmail = editTextStudentEmail.getText().toString();

    boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);

    if(createSuccessful){

    Toast.makeText(context, “Student information was saved.”, Toast.LENGTH_SHORT).show();

    }else{

    Toast.makeText(context, “Unable to save student information.”, Toast.LENGTH_SHORT).show();

    }

    }

    Reply
  13. Dian Putri Indah Mardika
    Dian Putri Indah Mardika says:

    Hi Mike your tutorial is really helpful, I am really grateful for this.
    But I have found a tiny error which is in the section 6.1
    OnLongClickListenerStudentRecord.java > onLongClick() method > inside the AlertDialog onClick() method.

    The last sentence in the second line:

    boolean deleteSuccessful = new TableControllerStudent(context).delete(id);
    it cannot work and it needed to be written like this:

    boolean deleteSuccessful = new TableControllerStudent(context).delete(Integer.parseInt(id));

    That way I can run the app successfully.

    Reply
  14. Ethel Tadz
    Ethel Tadz says:

    Thank you so much for this tutorial, i created my SIS that is required in my subject, thank you so much, it really help a lot :3

    Reply
  15. Ethel Tadz
    Ethel Tadz says:

    Thank you so much, it really helped me a lot, though I have encountered errors but I definitely pulled it out. Thank you very much, after two weeks of working on my project finding the best sqlite tutorial, this is the best so far, two weeks of searching and almost losing hope, but when i found this site it gives back hope to keep on going w/ my school project. Thank you very much sir! :3 ^_^

    Reply
  16. Lee
    Lee says:

    Hi, thank you so much for this tutorials, everything work great except that I can’t get to edit and delete, which under Update a record in Android SQLite Database. After adding new record, we suppose to able to click the record to able to update and delete? Thanks.

    Reply
    • Lee
      Lee says:

      Its okay, my bad. I manage to do it already, but anyway is there any method to call the readRecords(); method to another activity? It seems that I’m able to use the countRecords(); method on another activity but not readRecords();

      Any tutorials on passing data to another activity would be nice. Thanks

      Reply
  17. Mike Dalisay
    Mike Dalisay says:

    @Lee, you can import the MainActivity class to be able to use the readRecords(); method, as written above:

    ((MainActivity) context).countRecords();
    ((MainActivity) context).readRecords();

    Reply
  18. nur
    nur says:

    Hi. your tutorial is helped me a lot. i am trying to use your tutorial in my assignment. but i am having problem with calling readRecord() since my mainActivity extends fragment. so this code ((mainActivity) context).readRecords(); can’t be use. is there any way for me to call readRecords? i can’t change “extends fragment” because it will ruin my others codes. tq in advance :)

    Reply
    • Mike Dalisay
      Mike Dalisay says:

      Hello @nur, thanks for your good feedback! You can try putting in in a different class and call it from there just like what we did in tableControllerStudent.update(objectStudent);

      Reply
  19. Patrick
    Patrick says:

    Thank you so much for this great tutorial! It helped a lot but I’m still stuck and get error (after trying everything and days after days) with: linearLayoutRecords.removeAllViews(); and linearLayoutRecords.addView(locationItem); in public void readRecords(). Could you please help me? Thanks again :) !!

    Reply
  20. Alisha
    Alisha says:

    Hi there, I am doing a school project and I hope that you are able to help me asap:) Is there anything wrong with this code? Because I could not insert any values inside even though it shows a toast that says “Student information was saved”. Please help, thank you!

    new AlertDialog.Builder(context)
    .setView(formElementsView)
    .setTitle(“Create Student”)
    .setPositiveButton(“Add”,
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    String studentFirstname = editTextStudentFirstname.getText().toString();
    String studentEmail = editTextStudentEmail.getText().toString();
    dialog.cancel();

    ObjectStudent objectStudent = new ObjectStudent();
    objectStudent.firstname= studentFirstname;
    objectStudent.email= studentEmail;

    boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);
    if(createSuccessful){
    Toast.makeText(context, “Student information was saved.”, Toast.LENGTH_SHORT).show();
    }else{
    Toast.makeText(context, “Unable to save student information.”, Toast.LENGTH_SHORT).show();
    }

    }
    }).show();
    }
    }

    Reply
  21. Lewis Fitzgerald
    Lewis Fitzgerald says:

    Hey thanks for the great tutorial, but the only problem was the delete method should take a parameter of type String as you declared id as a string in section 5.3. Apart from that it worked!

    Reply
  22. Sanjiv
    Sanjiv says:

    Thank you very much. It’s very useful. I’m a php and c# developer. Now i wanted to learn android. i have tried in many CRUD from many other pages. But it has not work or i had not understand. But this was page is very help full to me. I’m not very well in english, but have understand this CRUD thanks a lot.

    Reply
  23. Angoranator777
    Angoranator777 says:

    Please Help!!!

    I follow the instructions meticulously, but as soon as I add the countRecords() and ((MainActivity) context).readRecords(); to the OnClickStudentListener.java – in steps 3.7 and 4.5 respectively, the app fails when the “Add” button is clicked

    If I remove them, the app does not fail when the “Add” button is clicked and therefore the TextView’s are not refreshed.

    I’ve been googling and moving stuff around to no avail…

    What could be the problem dudes??

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *