Mini NotePad

This is a sample application, having the features as the notepad like cut, copy, paste and save. You can also edit the Note by opening it again.

Underlying Algorithm:

Basic description of algorithm in step by step form:
1.) Create a Project MyNoteEditer.
2.) Create a class NotesDbAdapter.java, in this class we will use SQLiteDatabase and SQLiteOpenHelper to handle the database, to save and edit the data.

 

package com.app.MyNoteEditer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
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 KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_ROWID = "_id";

private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, " + "title text not null, body text not null);";

private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;

private final Context mCtx;

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);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}

public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}

public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

public void close() {
mDbHelper.close();
}

public long createNote(String title, String body) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

public void deleteAllNote() {
mDb.delete(DATABASE_TABLE, null, null);
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY}, null, null, null, null, null);
}

public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

public boolean updateNote(long rowId, String title, String body) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}

 

 

3.) Create a class NewText.java having save, cut, copy and paste functionality:

 

package com.app.MyNoteEditer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class NewText extends Activity implements OnClickListener
{
EditText editbox1;
EditText editbox2;
Button cutb;
Button copyb;
Button pasteb;
Button saveb,backb;
Editable s1,s2;

Spannable str;
Spannable str2;

private Long mRowId;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.new_text);
editbox1 =(EditText) findViewById(R.id.title);
editbox2 =(EditText) findViewById(R.id.insertdata);
mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (title != null) {
editbox1.setText(title);
}
if (body != null) {
editbox2.setText(body);
}
}
cutb =(Button) findViewById(R.id.cut);
cutb.setOnClickListener(this);
copyb =(Button)findViewById(R.id.copy);
copyb.setOnClickListener(this);
pasteb =(Button)findViewById(R.id.paste);
pasteb.setOnClickListener(this);
saveb =(Button) findViewById(R.id.save);
saveb.setOnClickListener(this);
backb =(Button) findViewById(R.id.back);
backb.setOnClickListener(this);
}
public void onBackPressed() {
moveTaskToBack(true);
return;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.save :
Bundle bundle = new Bundle();
bundle.putString(NotesDbAdapter.KEY_TITLE, editbox1.getText().toString());
bundle.putString(NotesDbAdapter.KEY_BODY, editbox2.getText().toString());
if (mRowId != null) {
bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
}
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
break;
case R.id.copy :
//String selectedText = editbox2.getText().substring(editbox2.getSelectionStart(), editbox2.getSelectionEnd());
if(editbox2.getSelectionEnd() > editbox2.getSelectionStart())
{
s1 = (Editable) editbox2.getText().subSequence(editbox2.getSelectionStart(), editbox2.getSelectionEnd());
}else
{
s1 = (Editable) editbox2.getText().subSequence(editbox2.getSelectionEnd(), editbox2.getSelectionStart());
}
break;
case R.id.cut :
if(editbox2.getSelectionEnd() > editbox2.getSelectionStart())
{
s1 = (Editable) editbox2.getText().subSequence(editbox2.getSelectionStart(), editbox2.getSelectionEnd());
}else
{
s1 = (Editable) editbox2.getText().subSequence(editbox2.getSelectionEnd(), editbox2.getSelectionStart());
}
editbox2.getText().replace(Math.min(editbox2.getSelectionStart(), editbox2.getSelectionEnd()), Math.max(editbox2.getSelectionStart(), editbox2.getSelectionEnd()),"", 0, 0);
break;
case R.id.paste :
editbox2.getText().replace(Math.min(editbox2.getSelectionStart(), editbox2.getSelectionEnd()), Math.max(editbox2.getSelectionStart(), editbox2.getSelectionEnd()),s1, 0, s1.length());
break;

case R.id.back :
Intent mIntent2 = new Intent(this,OpenNotes.class);
startActivity(mIntent2);
finish();
break;
}
}
}

 

 

4.) Create new_text.xml and put the following code in that:

 

<!--?xml version="1.0" encoding="utf-8"?-->
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

android:layout_height="wrap_content" android:text="Body Text" />
android:layout_height="wrap_content" android:layout_weight="1"
android:scrollbars="vertical" />

<button>
</button><button>
</button><button>
</button><button>
</button><button>

 

 

5.) Register this new Activity in AndroidManifest.xml :

 

<!--?xml version="1.0" encoding="utf-8"?-->
package="com.app.MyNoteEditer"
android:versionCode="1"
android:versionName="1.0">

 

 

6.) Replace the code of main.xml with following code:

 

<!--?xml version="1.0" encoding="utf-8"?-->
android:layout_width="wrap_content" android:layout_height="wrap_content">

 

 

7.) Create notes_list.xml and put the following code in that:

 

<!--?xml version="1.0" encoding="utf-8"?-->

 

 

8.) Create notes_row.xml and put the following code in that:

 

<!--?xml version="1.0" encoding="utf-8"?-->

 

 

9.) Run the Application.

Steps to Create:

1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. MyNoteEditer. Enter following information:
Project name: MyNoteEditer
Build Target: Android 2.1
Application name: MyNoteEditer
Package name: com.app.MyNoteEditer
Create Activity: OpenNotes

On Clicking Finish MyNoteEditer code structure is generated with the necessary Android Packages being imported along with OpenNotes.java. Replace the default code of OpenNotes.java with the following:

 

package com.app.MyNoteEditer;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class OpenNotes extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;

private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;

private NotesDbAdapter mDbHelper;
private Cursor mNotesCursor;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
public void onBackPressed() {
moveTaskToBack(true);
this.finish();
return;
}
private void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, mNotesCursor, from, to);
setListAdapter(notes);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, "New Note");
return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createNote();
return true;
}
return super.onMenuItemSelected(featureId, item);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, "Delete");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}

private void createNote() {
Intent i = new Intent(this, NewText.class);
startActivityForResult(i, ACTIVITY_CREATE);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NewText.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras =intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.createNote(title, body);
fillData();
break;
case ACTIVITY_EDIT:
Long rowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (rowId != null) {
String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.updateNote(rowId, editTitle, editBody);
}
fillData();
break;
}
}
}

 

 

Output : The final output

Leave a Comment:

10 comments
shanisk says September 20, 2011

[…] Mini NotePad Posted by Sushant on August 17, 2011 This is a sample application, having the features as the notepad like cut, copy, paste and save. You can also edit the Note by opening it again. Underlying Algorithm: Basic description of algorithm in step by step form: 1.) Create a Project MyNoteEditer. 2.) Create a class NotesDbAdapter.java, in this… Filed in: Android Development 0 […]

Reply
Johan du Plessis says September 24, 2011

Thanx – This helped me to understand the basics

Reply
Rick says May 17, 2012

Awesome. Can you put some kind of open source licence on this or do you not want other s using your code?

Reply
masum says November 14, 2012

I’m new in adroid. I’m trying to follow and build as advised. But I couldn’t build it for various error. As all the code is given but not as a project. Could you please give a Eclips project. Thanks in advance!

Reply
Android example project compilation failed? - Android Forums says November 14, 2012

[…] project compilation failed? I'm new at Anroid world. Just learning. I want to study build this project. But it fails for all R.* members and so other reasons. After searching the web I found […]

Reply
Sumit says January 18, 2013

awesome !

Reply
Jeff says April 3, 2013

Hello,
Great app, It worked beautifully. Is there a way to delete the saved notes?

Reply
paresh says May 11, 2013

thankx for help

Reply
Imran says June 28, 2013

sir,
Your post was very good but i am unable to open it again after it saved plz help me sir

Reply
Imran says June 28, 2013

fill data requires deprecation………..

Reply
Add Your Reply