Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create a Notepad for Android Devices

In this tutorial we will create a notepad for Android devices. This will allow the users to create, read and edit the text notes.

Introduction:

We assume that the readers of this tutorial have got basic knowledge about relational databases and SQL.

We will start from the basics and incorporate some functionalities step by step. Here we are going to create a very simple database that will serve us as data storage for our app.

At the end of this tutorial you will know how to:

  • create a simple SQLite database in Android.
  • get access to SQLite database via the command prompt (terminal) and execute some simple queries.

Facts about SQLite database

Facts about SQLite:

  • SQLite is free and open-source embedded SQL database engine.
  • SQLite reads and writes directly to ordinary disk files.
  • A complete SQL database is contained in a single disk file.
  • The database file format is cross-platform.
  • It supports standard relational database features including syntax, transactions and prepared statements. Transactions are ACID.

Database Structure

Our database will contain only one table and the following columns to persist notes:

  • title -- text (note title)
  • body -- text (note body text)
  • _id -- integer, autoincrement (the id of the note)

Creating the Database

Let's create a new project with default settings which contain a single activity called NotesListActivity. Now, in the same package with our activity, create a class called NotesDbAdapter. This class will contain SQLiteOpenHelper as a subclass which is a class to manage database creation and versioning. NotesDbAdapter will grant us an access to our database by defining CRUD methods . So let's create the wrapper class for our database and define all the constants we need and static inner class to get a database connection.

Listing1: Defining NotesDbAdapter.java

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 
public class NotesDbAdapter {
 
 public static final String COLUMN_TITLE = "title";
 public static final String COLUMN_BODY = "body";
 public static final String COLUMN_ID = "_id";
 
 public static final String TAG = NotesDbAdapter.class.getSimpleName();
 private DatabaseHelper mDbHelper;
 private SQLiteDatabase mDb;
 
 private static final String DATABASE_NAME = "notes.db";
 private static final String TABLE_NAME = "notes";
 private static final int DATABASE_VERSION = 1;
 
 private static final String DATABASE_CREATE = 
   "create table notes (_id integer primary key autoincrement, "
   + "title text not null, body text not null);";
  
 private final Context mContext;
 
 private static class DatabaseHelper extends SQLiteOpenHelper {
  DatabaseHelper(Context context) {
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
   
  @Override
  public void onCreate(SQLiteDatabase db) {
   db.execSQL(DATABASE_CREATE);
   Log.d(TAG, "onCreate() database");
  }
 
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   db.execSQL("DROP TABLE IF EXISTS notes");
   onCreate(db);
   Log.d(TAG, "onUpdate() database");
  }
 }
 
 public NotesDbAdapter(Context context) {
  this.mContext = context;
 }
  
 public NotesDbAdapter open() throws SQLException {
  mDbHelper = new DatabaseHelper(mContext);
  mDb = mDbHelper.getWritableDatabase();
  return this;
 }
}

The code looks quite big but actually there is nothing special here. We create static subclass ofSQLiteOpenHelper and implement abstract methods onCreate() and onUpgrade(). The onCreate() method is invoked when there is no database available for our app, so in this method we have to execute all the statements to create our database. onUpgrade() is invoked when the version of the current database is smaller than new version (database version is provided when SQLiteOpenHelper subclass instance is created and this version is passed as a parameter to a superclass constructor).

NotesDbAdapter is a wrapper class that holds the instance of SQLiteOpenHelper and provides API for database access. Now we need to create an instance of our NotesDbAdapter in our activity by calling the open() method to create the database. That's all the code we need to have a working database.

Listing2: Defining NotesListActivity.java

 import android.os.Bundle;
import android.app.Activity;
 
public class NotesListActivity extends Activity {
  
 private NotesDbAdapter mDbHelper;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes_list);
         
        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();
    }
}

Accessing SQLite Database from ADB Shell

Now we need to make sure that our database is created and in a working state. Let's open DDMS perspective in Eclipse (or launch monitor from tools folder in your SDK location) and locate the database file on the device file system.

Emulator/device instances store SQLite3 databases in the folder:

/data/data/<package_name>/databases/<database_name>

To issue SQL queries to your database enter a remote shell on the emulator instance and enter sqlite3command following with the full path to our database. Here is an example:

Listing3: Entering a remote shell on the emulator

root@android:/ # sqlite3
/data/data/<package_name>/databases/<database_name>database_path
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>

In Windows, to acces ADB directly from command prompt add path of your SDK to your environment variables. In Mac OS, follow the below instructions:

If you have only one USB device or emulator connected you don't need to specify what device is the target for your commands. Otherwise you need to direct your commands to the targeted device by specifying arguments after adb command.

Listing4: Using the adb command

adb [-d|-e|-s <serialNumber>] shell

Now you can execute your SQL queries directly to your database. Let's insert a few rows into our database and then query all of them.

Listing5: Executing SQL queries

sqlite> INSERT INTO notes (title, body) VALUES ("Title1", "Body1");
INSERT INTO notes (title, body) VALUES ("Title1", "Body1");
sqlite> INSERT INTO notes (title, body) VALUES ("Title2", "Body2");
INSERT INTO notes (title, body) VALUES ("Title2", "Body2");
sqlite> INSERT INTO notes (title, body) VALUES ("Title3", "Body3");
INSERT INTO notes (title, body) VALUES ("Title3", "Body3");
sqlite> SELECT * FROM notes;
SELECT * FROM notes;
1|Title1|Body1
2|Title2|Body2
3|Title3|Body3

As you can see, everything is great.Our database is fine and ready to use. The first step now is to import the Notepad_Start project into Eclipse. To do this, create a new Android project in Eclipse, and then select Create project from existing source in the New Android Project dialog box.

The Notepad_Start project is the starting point of our tutorial and this is a modified version of Notepad tutorial.

Right-Click the Notepad_Start project in eclipse and click Properties. This brings up the Properties dialog box. Click Android in the left pane to bring up the Project build target list. Check that Android 3.0 ( or higher) is available as one of the targets. If it is not, please bring up the Android SDK and AVD Manager and follow the steps outlined at Installing Android sdk to install Android 3.0, API Level 11. Once the target Android 3.0 has been installed, change the Build Target to Android 3.0, API Level 11.

Listing6: Specify the android:minSdkVersion as 7 and android:targetSdkVersion as 11.

<manifest>
     <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="11"/>
       ...
</manifest>

For SDK Level 7 add the following style definition to the file res/values/styles.xml. We are extending Theme.Light

Listing7: Extending Theme.light

<style name="ThemeNotePad" parent="android:Theme.Light"/>

Turn on the hardware acceleration by specifying android:hardwareAccelerated="true" in the AndroidManifest.xml file.

Listing8: Specifying android: hardwareAccelerated=’true’

<manifest android:hardwareAccelerated="true">
    ...
</manifest >

The next step is to create a new Activity to host Fragments. Right-click on the src folder in Package Explorer and click on New --> class: In the 'New Java Class' window which comes up add the class name as NotepadActivity in the package com.example.android.Notepad . Add the super class as android.support.v4.app.FragmentActivity and click FINISH.

Open layout file res--> layout--> notepad.xml, this will be the layout for this activity. It uses a container to host the fragments @+id/list.

Listing9: Layout for the activity

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/list" android:layout_width="match_parent"
        android:layout_height="match_parent" /> 

Override onCreate(..) method of NotepadActivity and set the notepad.xml as the content view.

Listing10: Defining Overide onCreate(..) method

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.notepad);
}    

The last step is to add Action Item to the Action Bar. In this step we will add an action item AddNote to the Options Menu in the Action Bar.

Override onCreateOptionsMenu in NotepadActivity class. Populate it using the MenuInflater from R.menu.notepad_menu resource file defined in res/menu/notepad_menu.xml file.

Listing11: Defining Override onCreateOptionsMenu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.notepad_menu, menu);
    return super.onCreateOptionsMenu(menu);
}   

Listing12: Code showing the contents of res/menu/notepad_menu.xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/add_note" 
    android:title="@string/menu_add"
    android:icon="@drawable/ic_menu_add"
    android:showAsAction="ifRoom|withText"  />

</menu>

Sample Output:

Notepad in Android Device

Figure 1: Notepad in Android Device

Conclusion

We learned how to create notepad application for Android devices explaining from scratch how to create a database and then use it to develop notepad.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login