Create a Note App using SQLite Database in Android – Android Studio

Create a note app on Android is easy and a damn cool thing you can use by yourself. Oh, don’t worry, you don’t need to setup database in your home or not need to buy any kind of hosting also. In this tutorial we will get to learn how to create a simple note app for the android environment that saves text notes using SQLite database technologies.

Create a Note App using SQLite in Android – Android Studio

Download projct file of Create a Note App using SQLite in Android – Android Studio

Before you begin


Check and double check that your Android Studio is the latest version or not, also be sure to have the latest SDK tools installed into your Android Studio.

Steps to Create Note app using SQLite database – Android Studio


  1. Create a new project in Android Studio in a normal way.
  2. Open your build.gradle file and add the following lines in your dependencies. This will download the Float Action Button library .
    compile 'com.getbase:floatingactionbutton:1.10.1'
  3. Open your AndroidManifest.xml file. Your manifest file will look like this-
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.andrious.notebook" >
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" >
            <activity android:name=".MainActivity" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name=".Input_Note_DataActivity" >
            </activity>
            <activity android:name=".NoteViewActivity" >
            </activity>
        </application>
    
    </manifest>
  4. Open your colors.xml and add this color.Your color.xml file will look like this-
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="colorPrimary">#3F51B5</color>
        <color name="colorPrimaryDark">#303F9F</color>
        <color name="colorAccent">#FF4081</color>
        <color name="black_semi_transparent">#B2000000</color>
        <color name="background">#e5e5e5</color>
        <color name="half_black">#808080</color>
        <color name="white">#fafafa</color>
        <color name="white_pressed">#f1f1f1</color>
        <color name="pink">#e91e63</color>
        <color name="pink_pressed">#ec407a</color>
        <color name="blue_semi_transparent">#805677fc</color>
        <color name="blue_semi_transparent_pressed">#80738ffe</color>
    </resources>
  5.  Open your activity_main.xml file.We are going to add a ListView  here that will contain a list of notes and add Floating Action Button in  Relative Layout.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:fab="http://schemas.android.com/apk/res-auto"
        android:background="@color/background"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
    
    
        <com.getbase.floatingactionbutton.AddFloatingActionButton
            android:id="@+id/normal_plus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            fab:fab_plusIconColor="@color/white"
            fab:fab_colorNormal="@color/pink_pressed"
            fab:fab_colorPressed="@color/white_pressed"
            android:layout_marginBottom="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginStart="16dp"
            android:onClick="addNew"/>
    
        <ListView
            android:id="@+id/mobile_list"
            android:layout_gravity="center"
            android:clipToPadding="false"
            android:padding="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:dividerHeight="4dp">
    
        </ListView>
    
    </RelativeLayout>
  6. Add activity_display_contact.xml on res/layout/activity_listview.xml.It is List Item design xml.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:orientation="vertical"
            android:background="@drawable/border"
            android:weightSum="5">
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/blue_semi_transparent_pressed"
                android:gravity="center"
                android:layout_weight="2">
    
                <TextView
                    android:id="@+id/list_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:text="title"/>
    
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_weight="3">
    
                <TextView
                    android:id="@+id/list_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:ellipsize="end"
                    android:maxLines="3"
                    android:text="text"/>
    
            </LinearLayout>
    
    
        </LinearLayout>
    
    
    </LinearLayout>
  7. Add activity_display_contact.xml on res/layout/activity_input_note_data.xml.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:padding="15dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:text="Title"
            android:textColor="@color/black_semi_transparent"
            />
        <EditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:paddingLeft="5dp"
            android:background="@drawable/border"
            android:inputType="textCapSentences|textAutoCorrect|textMultiLine"
            android:hint="title"/>
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="10dp"
            android:textColor="@color/black_semi_transparent"
            android:text="Text"/>
    
        <EditText
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:paddingLeft="5dp"
            android:background="@drawable/border"
            android:inputType="textCapSentences|textAutoCorrect|textMultiLine"/>
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/clickButton"
            android:text="save"/>
    
    </LinearLayout>
  8. Add note_view.xml on res/layout/note_view.xml.If you click on a list item than open this xml and show your notes.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Title:"
            android:textColor="@color/black_semi_transparent"
            android:textSize="15dp"
            android:textStyle="bold"
            android:layout_marginBottom="5dp"/>
        <TextView
            android:id="@+id/title_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:text="ksdhaksdghkadgakg"/>
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Text:"
            android:textStyle="bold"
            android:textColor="@color/black_semi_transparent"
            android:textSize="15dp"
            android:layout_marginBottom="5dp"/>
        <TextView
            android:id="@+id/text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ksdhaksdghkadgakg"/>
    
    </LinearLayout>

    Now let’s start java coding.

  9. Now we are going to create a Java class file named ExampleDBHelper.java. Here we will build our database so that we can use them letter.
    package com.andrious.notebook;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    /**
     * Created by MD.ISRAFIL MAHMUD on 3/15/2017.
     */
    
    public class ExampleDBHelper extends SQLiteOpenHelper {
    
        public static final String DATABASE_NAME = "SQLiteExample.db";
        private static final int DATABASE_VERSION = 1;
        public static final String INPUT_TABLE_NAME = "input";
        public static final String INPUT_COLUMN_ID = "_id";
        public static final String INPUT_COLUMN_Title = "title";
        public static final String INPUT_COLUMN_Text = "text";
    
        public ExampleDBHelper(Context context) {
            super(context, DATABASE_NAME , null, DATABASE_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + INPUT_TABLE_NAME + "(" +
                    INPUT_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    INPUT_COLUMN_Title + " TEXT, " +
                    INPUT_COLUMN_Text + " TEXT )"
            );
        }
    
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + INPUT_TABLE_NAME);
            onCreate(db);
        }
    
    
    
    
        public boolean insertPerson(String title,String text) {
            SQLiteDatabase db = getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(INPUT_COLUMN_Title, title);
            contentValues.put(INPUT_COLUMN_Text, text);
            db.insert(INPUT_TABLE_NAME, null, contentValues);
            return true;
        }
    
    
        public Cursor getAllPersons() {
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor res = db.rawQuery( "SELECT * FROM " + INPUT_TABLE_NAME, null );
            return res;
        }
    
    
        public Cursor getPerson(String id) {
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor res = db.rawQuery( "SELECT * FROM " + INPUT_TABLE_NAME + " WHERE " +
                    INPUT_COLUMN_ID + "=?", new String[] { id } );
            return res;
        }
    
    
        public void deleteSingleContact(String id){
    
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(INPUT_TABLE_NAME, INPUT_COLUMN_ID + "=?", new String[]{id});
    //KEY_NAME is a column name
        }
    
    
    }
  10. Add  java file is Input_Note_DataActivity.java.
    package com.andrious.notebook;
    
    import android.support.v7.app.AppCompatActivity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    /**
     * Created by MD.ISRAFIL MAHMUD on 7/19/2017.
     */
    
    public class Input_Note_DataActivity extends AppCompatActivity {
        ExampleDBHelper db;
        EditText n_title;
        EditText n_text;
        String title,text;
        public static SharedPreferences pref;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_input_note_data);
            db=new ExampleDBHelper(getApplicationContext());
            pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
    
    
            n_title=(EditText) findViewById(R.id.title);
            n_text=(EditText) findViewById(R.id.text);
    
    
    
            Button clickButton = (Button) findViewById(R.id.clickButton);
            clickButton.setOnClickListener( new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    title = n_title.getText().toString();
                    text = n_text.getText().toString();
    
                    if(title.length() == 0){
                        SharedPreferences.Editor editor = pref.edit();
    
                        int idName = pref.getInt("name", 0);
                        idName++;
                        title="new document "+idName ;
                        editor.putInt("name",idName);
                        editor.commit();
    
                    };
    
                    if( text.length() == 0){
                        Toast.makeText(getApplicationContext(), "title or text box is empty !!!",
                                Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        db.insertPerson(title,text);
                        Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
                        finish();}
                }
            });
        }
    
    }
  11. Add java file is NoteViewActivity.java
    package com.andrious.notebook;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.TextView;
    
    /**
     * Created by MD.ISRAFIL MAHMUD on 7/15/2017.
     */
    
    public class NoteViewActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.note_view);
    
           TextView titleview=(TextView)findViewById(R.id.title_view);
           TextView textview=(TextView)findViewById(R.id.text_view);
    
            String sub_id = getIntent().getStringExtra("id");
            String title=getIntent().getStringExtra("title");
            String text=getIntent().getStringExtra("text");
            titleview.setText(title);
            textview.setText(text);
        }
    }
  12. Finaly we can work MainActivity.java.Your MainActivity.java will look like-
    package com.andrious.notebook;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.Cursor;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.text.Html;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.BaseAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    
    public class MainActivity extends AppCompatActivity {
        ListView mobile_list;
        ExampleDBHelper mydb;
        ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
        public static final String INPUT_COLUMN_ID = "_id";
        public static final String INPUT_COLUMN_Title = "title";
        public static final String INPUT_COLUMN_Text = "text";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mydb = new ExampleDBHelper(getApplicationContext());
            mobile_list = (ListView) findViewById(R.id.mobile_list);
            loadData();
        }
    
        @Override
        public void onResume(){
            super.onResume();
            loadData();
    
        }
    
    
        public void addNew(View view) {
            Intent intent = new Intent(this, Input_Note_DataActivity.class);
            startActivity(intent);
        }
    
    
        public void loadData() {
            dataList.clear();
            Cursor cursor = mydb.getAllPersons();
            if (cursor.moveToFirst()) {
                while (cursor.isAfterLast() == false) {
    
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(INPUT_COLUMN_ID, cursor.getString(cursor.getColumnIndex(INPUT_COLUMN_ID)));
                    map.put(INPUT_COLUMN_Title, cursor.getString(cursor.getColumnIndex(INPUT_COLUMN_Title)));
                    map.put(INPUT_COLUMN_Text, cursor.getString(cursor.getColumnIndex(INPUT_COLUMN_Text)));
    
    
                    dataList.add(map);
    
                    cursor.moveToNext();
                }
            }
    
    
            NoticeAdapter adapter = new NoticeAdapter(MainActivity.this, dataList);
            mobile_list.setAdapter(adapter);
    
            mobile_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
    
                    Intent i = new Intent(MainActivity.this, NoteViewActivity.class);
                    i.putExtra("id", dataList.get(+position).get(INPUT_COLUMN_ID));
                    i.putExtra("title", dataList.get(+position).get(INPUT_COLUMN_Title));
                    i.putExtra("text", dataList.get(+position).get(INPUT_COLUMN_Text));
                    startActivity(i);
    
                }
            });
    
    
            //  list item long press to delete -------------start-----------
    
            mobile_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
                    return onLongListItemClick(v,pos,id);
                }
                protected boolean onLongListItemClick(View v, final int pos, long id) {
                    
                    /////Display Dialog Here.......................
    
                    AlertDialog alertDialog = new AlertDialog.Builder(v.getContext()).create();
                    alertDialog.setTitle("Delete...");
                    alertDialog.setMessage("Are you sure?");
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            String a=dataList.get(+pos).get(INPUT_COLUMN_ID);
                            mydb.deleteSingleContact(a);
                            loadData();
                        }
                    });
                    alertDialog.show();
                    return true;
                }});
    
            //--------finish------------
        }
    }
    
    class NoticeAdapter extends BaseAdapter {
    
        private Activity activity;
        private ArrayList<HashMap<String, String>> data;
    
        public NoticeAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
            activity = a;
            data = d;
        }
    
        public int toInt(String s)
        {
            return Integer.parseInt(s);
        }
    
        public int getCount() {
            return data.size();
        }
    
        public Object getItem(int position) {
            return position;
        }
    
        public long getItemId(int position) {
            return position;
        }
    
        public View getView(int position, View convertView, ViewGroup parent) {
            NoticeViewHolder holder = null;
            if (convertView == null) {
                holder = new NoticeViewHolder();
                convertView = LayoutInflater.from(activity).inflate(
                        R.layout.activity_listview, null);
    
                holder.title = (TextView) convertView.findViewById(R.id.list_title);
                holder.text = (TextView) convertView.findViewById(R.id.list_text);
    
                convertView.setTag(holder);
            } else {
                holder = (NoticeViewHolder) convertView.getTag();
            }
            holder.title.setId(position);
            holder.text.setId(position);
    
            HashMap<String, String> song = new HashMap<String, String>();
            song = data.get(position);
    
            holder.title.setText(Html.fromHtml(song.get(MainActivity.INPUT_COLUMN_Title)));
            holder.text.setText(Html.fromHtml(song.get(MainActivity.INPUT_COLUMN_Text)));
    
            return convertView;
    
        }
    }
    
    class NoticeViewHolder {
        TextView title, text;
    }
    
  13. If you can Update data or Edit data ,use this code in ExampleDBHelper.java

    public boolean updatePerson(//--argument name--//) {
    
    SQLiteDatabase db = this.getWritableDatabase();
     ContentValues contentValues = new ContentValues();
     
    contentValues.put(INPUT_COLUMN_ //--your database collum name--//, //--argument name--//);
     
    db.update(INPUT_TABLE_NAME, contentValues, INPUT_COLUMN_ID + " = ? ", new   String[] { id } );
     return true;
     }

    Now let’s run and test the app. Don’t forget to comment.

Leave a Reply