Saturday, October 6, 2012

An outrageously simple note taking android app (part 1)

Hi all, in this post we will create a very basic note taking app. It will store only single note and retrieve it back. In later post we will keep extending it until it become a fully working app. So bear with it as the attempt  is to learn android programming not anything else.

Instructions here are being done with IntelliJ IDEA IDE.But they shall be convertible for any IDE,or command line.

First off course create a blank project.





This newly created project already has one activity MyActivity Consider this as window in a desktop app as this has also got screen area and can have button, text, etc.

Activities in android are usually tied with an XML file where the UI is designed, in this case main.xml. Open it to design the first Activity(window) of this app.


Change the XML to remove the TextView and have a button instead.


<Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/AddNote"
            android:onClick="addNote"/>


This button property width as "fill_parent" which will specify that it spans the whole width of Activity, height as "wrap_content" which specify that its height will only be accommodate its label. text property sets the label of the button, which is string to be defined in strings.xml under "values" as following.

<string name="AddNote">+ Add a new note</string>

onClick defines the function which will be called when the button is pressed and wiil be defined in "MyActivity.java" file.

At this point of time UI will look like this in IntelliJ IDEA.


Here you can experiment with different device and android profiles to preview how well it will look like.

The onClick function addNote will be defined as this.


public void addNote ( View theButton) {
        Intent intent = new Intent(this, EditNoteActivity.class);
        startActivity(intent);
    }

This function does only two things, first create an intent which is like a message passing to the new Activity(window) and start new Activity EditeNoteActivity which we will shortly define.


Now create a new activity EditNoteActivity by right clicking on src--com.example -> New -> Android Component


Now we need to create a resource xml file, right click on layout directory in project view and select New->Layout resource file.



This is an empty layout file we need an edit text here, and a hew buttons. So here they are, first EditText.


<EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="text"
            android:hint="Enter note here..."
            android:gravity="top|left" >

        <requestFocus />
    </EditText

id uniquely identifies the field in your java code. setting the height to 0dp and weight set the field to take up screen space to its fullest. inputType specifies the default type of input like text, number etc. hint specifies the subtle non editable text to be displayed in EditText which will disappear when the user enters text. Rest of the fields can be looked up in API reference of Google site.

Set the orientation of layout to be vertical
android:orientation="vertical"

Here we have chosen LinearLayout which is more feasible for this app. There are different types of layout which can be seen on Google reference.

Now create two buttons as below


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2">
    <Button
            android:id="@+id/button1"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:onClick="onClickSave"

            android:text="Save" />
    <Button
            android:id="@+id/button1"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:onClick="onClickBack"

            android:text="Back" />
    </LinearLayout>

Here the orientation of layout is horizontal so that buttons are sideways aligned. weightSum is 2 so that buttons are equally spaced in all type of screens. Rest of the fields are self explanatory I guess by now.

At this point the whole xml file is like this

http://snipt.org/vWP3



Now open your EditNoteActivity.java file and add onclickSave method to look like this


    public void onClickSave(View theButton) {
        String FILENAME = "note_file";

        EditText text = (EditText) findViewById(R.id.editText1);


        FileOutputStream fos = null;
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        assert fos != null;
        try {
            String str = new String (text.getText().toString());
            fos.write(str.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        finish();
    }

Here you get the handle of the button1by findViewById and passing the resourse ID. openFileOutput opens up the file on internal memory exclusively for this app as specified by MODE_PRIVATE. You take the text out of the field by getText and convert it to bytes by getBytes method before saving it to file and close it.


Now make your onCreate method to look like this


public void onCreate(Bundle savedInstanceState) {
        String FILENAME = "note_file";
        byte[] buffer = new byte[100];

        super.onCreate(savedInstanceState);
        setContentView(R.layout.editnote);
        EditText text = (EditText) findViewById(R.id.editText1);

        FileInputStream fos = null;
        try {
            fos = openFileInput(FILENAME);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if ( fos != null){
        try {
            fos.read(buffer, 0, 10);
            String str = new String(buffer, "UTF8");
            text.setText(str);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        }
    }

This one is self explanatory mostly as it open the file and read the node. Only one worth mentioning is setContentView which takes the editnote.xml defined and create the UI. Remember it to put first before findViewById to avoid crash as this needs to be done first.

Also add onClickBack method


    public void onClickBack(View theButton) {
        finish();
    }
This one only calls finish which returns to the main Activity MyActivity.


Now build and compile and run it on emulator to see how it goes. This is fairly shortcoming app as it saves only one note and retrieves it back, however I am sure this helps in understanding many concepts in android. Especially as if you try this and the go around the reference or books you will find yourself eased out a bit.

Hope this helps and many thanks to guys on http://stackoverflow.com for helping.






3 comments:

  1. I’m flattened for your blogs writings and blogs as well.
    rooting android tablet

    ReplyDelete
  2. Hey ashish..A big thanks to you for making this android app development too easy for us. At least i can get a idea from this post.
    Mobile Apps Development india

    ReplyDelete
  3. Oh great, nicely presented post. Thanks for sharing this post to us.
    mobile application development

    ReplyDelete