Saturday, September 8, 2012

Mini NotePad In Android

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, nullnull);
    }
    public Cursor fetchAllNotes() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY}nullnullnullnullnull);
    }
    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, nullnullnullnullnull);
        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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout android:orientation="horizontal"android:layout_width="fill_parent" android:layout_height="wrap_content">
                <TextView android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="Title" />
                <EditText android:id="@+id/title"android:layout_width="wrap_content"   android:layout_height="wrap_content"android:layout_weight="1" />
        </LinearLayout>
        <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="Body Text" />
        <EditText android:id="@+id/insertdata" android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:layout_weight="1"
                android:scrollbars="vertical" />
        <LinearLayout android:orientation="horizontal"android:layout_width="fill_parent" android:layout_height="wrap_content">
                <Button android:id="@+id/save" android:text="Save"android:layout_width="wrap_content" android:layout_height="wrap_content" />
                <Button android:text="Cut" android:id="@+id/cut"android:layout_width="wrap_content" android:layout_height="wrap_content" />
                <Button android:text="Copy" android:id="@+id/copy"android:layout_width="wrap_content" android:layout_height="wrap_content" />
                <Button android:text="Paste" android:id="@+id/paste"android:layout_width="wrap_content" android:layout_height="wrap_content" />
                <Button android:text="Back" android:id="@+id/back"android:layout_width="wrap_content" android:layout_height="wrap_content" />
        </LinearLayout>
</LinearLayout>
5.) Register this new Activity in AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.app.MyNoteEditer"
     android:versionCode="1"
     android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".OpenNotes" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NewText">
        </activity>
    </application>
</manifest>
6.) Replace the code of main.xml with following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content" android:layout_height="wrap_content">
    <ListView android:id="@+id/android:list" android:layout_width="wrap_content"android:layout_height="wrap_content"/>
        <TextView android:id="@+id/android:empty"android:layout_width="wrap_content" android:layout_height="wrap_content"android:text="No New Notes…Press on Menu to Add New Note"/>
</LinearLayout>
7.) Create notes_list.xml and put the following code in that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content" android:layout_height="wrap_content">
    <ListView android:id="@+id/android:list" android:layout_width="wrap_content"android:layout_height="wrap_content" />
        <TextView android:id="@+id/android:empty"android:layout_width="wrap_content" android:layout_height="wrap_content"android:text="No Notes…"/>
</LinearLayout>
8.) Create notes_row.xml and put the following code in that:
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content" android:layout_height="wrap_content"/>
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

No comments:

Post a Comment