Sunday, December 25, 2011

Android Tutorial Part 4 - Using Intents for passing data from one activity to other


Earlier we navigated from one activity to other. Now we will check how to pass data from one activity to other.

You may remember how we navigated to the second activity.

public void goToMyNextActivity(View view) {
        Intent myIntent;
        myIntent = new Intent(this, SecondActivity.class);
        startActivity(myIntent);
    }


To pass data we need to add the data as a bundle extra, to the object we created. You can pass any type of data as a *key value pair. Here I'm going to pass a string and an int.

public void goToMyNextActivity(View view) {
        Intent myIntent;
        myIntent = new Intent(this, SecondActivity.class);
        myIntent.putExtra("name", "Tom");
        myIntent.putExtra("age", 25);
        startActivity(myIntent);
       
    }


Take a look at

myIntent.putExtra("name", "Tom");

Here 'name' is my key and 'Tom' is the value. In the next line 'age' is the key and '25' is the value.

Now we will move to the onCreate function of the next activity(SecondActivity). To retrieve the above values I have to refer the corresponding keys used. Check the following code:

String name = getIntent().getStringExtra("name");
int age = getIntent().getIntExtra("age", 0);

In getting some data types from an intent you have to define a default value also. That's why in the second line while getting the int value I had defined the defalt value as 0. So due to some reason if you forgot to pass the value for 'age' then it will take the default  value. You can set the default value as you like.

To check whether the data has reached the second activity, here I'm going to use the Logcat. On my last post I told you how to access the Logcat.

To print some thing in the log you have to use the following syntax

Log.<debugging level> (String tag, String  message);

debugging level: Based upon the level of debugging you can use i(INFO), e(ERROR), d(DEBUG), v(VERBOSE) etc.

tag: Used to identify the source of a log message. It usually identifies the class or activity where the log call occurs.

message: The message you would like logged.

Here I'm going to use INFO level logs.

Log.i("NAME", ""+name);
Log.i("AGE", ""+age); 


Ir's time to text our code. From the first screen tap the 'Next Activity' button. You will reach the next screen now check the Logcat.



Now in the first activity(Sample2Activity) where we created an object for Intent remove the following line and check logcat.

myIntent.putExtra("age", 25);

You can see the default value in the logcat!














































*key value pair - Each value will be stored against a key. To retrieve the value you have to refer that key

Monday, December 19, 2011

Android Tutorial Part3 - Using Intent to start an activity.

Hello,

I think it's time to add more than one page to our app. You may have read that each screen/page in android is called an activity. To start an activity we use the intents.

To implement an activity we need two files
  1. a class file which extends the Activity
  2. a xml file which describes how the activity looks like. If you want you can avoid the xml!. But you have to describe how the class looks like in the class file.
You should mention the name of the activity in the AndroidManifest.xml file in order to make it accessible by the system. We will come into this after declaring the activity.

To introduce the use of intents I will be creating a new project with a button on the home screen. When you taps it, you will be taken to the next activity.

Lets start together. Create a new android project with whatever name and target you like. After that place a button on the first activity. In my last post I had said how to implement the button action. I think you had done upto that in this project also!

For those who forget those steps check my steps below.

1. Created a project with following details
  • Project Name: Sample2
  • Build Target: Android 2.2
  • Package Name: com.android.sample2
You can change the above settings as you wish

2. Added a button(Next Activity) on the main.xml file with onClick action goToNextActivity. This action has to be defined in the class file. The main.xml now looks as

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToMyNextActivity"
        android:text="Next Activity" />

</LinearLayout>

Before start editing the class file I'm going to create the second activity. For that right click your package name inside the src folder in 'Package Explorer'. In my case the com.android.sample2.

Select New>Class. In the window that appears give the name of the second activity and click 'Finish'. You can name the activity as you wish. I named it as SecondActivity.

Now in the package explorer just below the Sample2Activity ypu can see the new activity we created. It's time to create an xml file for this activity.

For creating the xml file right click the layout folder inside the res folder. Select New>Android XML Layout File. If you didn't see the 'Android XML Layout File' then select the 'other' option and find it from the 'Select a wizard' window. Once selected click 'Next'.

Enter the name of your xml file in 'File:'. Here also you can enter the name you like! But names must contain only lowercase a-z, 0-9, or _.

I entered second_activity and clicked 'Finish'. The default root element selected will be LinearLayout. We will discuss on different layouts later. For now use the LinearLayout.

On the new xml file add a text view and display whatever you like. I added the following code in second_activity.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="THIS IS MY SECOND ACTIVITY" />

</LinearLayout>

Now we have to connect this layout to the class file. For that open the SecondActivity.java. It will be like

package com.android.sample2;

public class SecondActivity {

}

As I said earlier the class file should extend the Activity.

package com.android.sample2;

import android.app.Activity;

public class SecondActivity extends Activity{

}

The import will automatically come when you types the class name. If not simply press Ctrl+Shift+O. Use Alt instead of Ctrl on your Mac OS.

The next step is to link the xml to the class file when this activity is created. When an activity is created the onCreate() function on the Activity class is called. So we have to add this inside the onCreate overriding method.

There is no need to write the onCreate function. What you have to do is to select Source>Override/Implement methods.


In the new window select the onCreate(Bundle) and click OK.

Now your class file will be like

public class SecondActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

}

Below the super,onCreate we are going to set the xml file for this activity class. For that use the setContentView(int layoutResID) function. Here layoutResID points the name of your layout file. It should be like R.layout.your_layout_file_name. As my layout file name is second_activity this function will be like setContentView(R.layout.second_activity);

public class SecondActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
    }

}

Ok. Lets go back to the first activity and implement the button click function now. The name of the button click function I gave in the xml file was 'goToMyNextActivity'. So my function will be like

public void goToMyNextActivity(View view) {
       
    }

We have to implement the navigation to the second activity inside this function. For this as I said earlier we have to use Intent. The steps are

  1. Create an object of Intent.
  2. Initialise it with the current class name and the resulting class name.
  3. start activity using the intent we created.
I will be like 

public void goToMyNextActivity(View view) {
        Intent myIntent;
        myIntent = new Intent(this, SecondActivity.class);
        startActivity(myIntent);
    }

*You can replace those 3 lines with a single line
startActivity(new Intent(this, SecondActivity.class));

I think you understand what it means. Now try to run the project. The first screen will be like



Click the 'Next Activity' button!
What happens now?

The app crashes!! When an android app crashes a 'Force Close' alert will be presented.



Simply click that 'Force close' button. Its time to investigate the reason for the crash :)

For that come back to the eclipse. From Window select show view - Window>Show View>LogCat. You may not see LogCat immediately from the Show View. So select other and search for LogCat. Double click the LogCat for a larger view. It will show the error in RED.



In this place you mouse over the marked line. Now you may know the reason!


The activity is not declared in the AndroidManifest.xml file. So open the AndroidManifest.xml and select the 'Application' view.


Scroll to the bottom. There you can see the Application Nodes. Select 'Add' to add our new activity. In the new alert box that appears select 'Activity'. Now the 'Attributes for Activity' will appear next to the 'Application Nodes'. In the name edit text you have to enter the name of you activity. For that click the 'Browse' button. A new window will appear. Please wait for a moment. The name of the activities will be loaded there.



Click OK save the manifest file and run the app again. This time when you click the 'Next Activity' button the new screen will be shown.


So that's it. You navigated to your second activity!


Sunday, December 18, 2011

Android Tutorial Part2 - EditText and Button

Hello everybody. You might have read my last blog on creating an android app and using a TextView. Here I'll help you to implement the EditText. The basic differences between an EditText and TextView are
  • The user can edit the contents of an EditText, where the user has no control over the TextView.
  • The data to be displayed in a textview is set by the developers. 
Lets start by editing the xml file. You can either use the xml file created earlier or create a new file. Any way I decided to continue with my old xml file.

Before starting you gays can give a try. The goal is to place an EditText below the TextView we created earlier. Try it youself first, then check my code.


  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ANDROID IS INTERESTING :)"
        android:textSize="50sp" />

    <EditText
        android:layout_width="200dp"
        android:layout_height="50dp" />

</LinearLayout>

My edittext looks as in the following pic.


I had set the height and width of the edit text with constant values so that the size of the edittext will always remains constant. Set the height and width of the EditText to wrap content and check what happens.

How was that? If tried you might have seen at first the edittext seen on the emulator was a very small one...while entering texts it start growing!

Here you might have noticed that you can enter whatever characters you like. That's a default property. You can restrict this as you wish. If you wants to enter only numbers in a text field then you can set the input type of the edit text to number as follows:
android:inputType="number"
Take a look at the keyboard that appears now. What difference did you see? Are you able to enter any characters other than numbers?

A lot of other input types are also available. For now check input types like phone, text, textPassword etc.

After doing the above exercises now it's time to read the data an user entered in the EditText. This has to be done in the class file. For refering the edittext in the class file we need a name for the edittext we created. In android we refer the name as id. So we have to set an id for our edittext. This is done as follows:

android:id="@+id/myEditText"

Button
Before moving to the class file we have to decide when to read the text from edit text. I had decided to read when a button is clicked. So I decided to put a button below the edit text. Here also you can try to put a button before checking my code!

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="Read"
        android:onClick="readButtonPressed"/>

I think there is no need to explain any features other than the last line. The last line says that there is a function with name 'readButtonPressed' in the class file. When this button is pressed the control has to be passed to that function. (We have to implement this function in the class file). Here when the read button is clicke the readButtonPressed function will be triggered.

I had removed the old textviews in my layout file and added a new textview to display the text entered in edittext.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/myEditText"
        android:layout_width="200dp"
        android:layout_height="50dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="readButtonPressed"
        android:text="Read"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


 Now take the activity class file. On the previous blog we had created a class file with name 'Sample1Activity'. On that file you have to write the 'readButtonPressed' function. 

public void readButtonPressed(View view) {
      
    }  


You might have seen the 'View' is underlined in red. Place your mouse over that. Now you can see

On that select Import 'View' to import the class view. If there were no errors then your IDE may have automatically imported the necessary classes!

Now to read the data in the editext, create an object of editext and read data from that edittext using getText() function. We have to create an object of the edittext and initialise it to the edittext we created in the xml file as follows:

EditText editTextObj = (EditText) findViewById(R.id.myEditText);

To create an object of the textview we defined you can use the same syntax as above. The only difference is that you have to replace the EditText with TextView and has to specify the id of the textview.

TextView textViewObj = (TextView) findViewById(R.id.myTextView);

The only thing remains is to read the text from edittext object and set it to the text view object. That includes two functions -

getText() - to read the text from an element.

setText() - to set the text of an element.

    public void readButtonPressed(View view) {
       
        // Creates an object of the edit text class and initialise that 
        // with the edit text we created in xml.
        EditText editTextObj = (EditText) findViewById(R.id.myEditText);
        // Creates an object of the text view class and initialise that 
        // with the text view we created in xml.
        TextView textViewObj = (TextView) findViewById(R.id.myTextView);
        // Reads the data entered on the edit text to a string.
        String textEntered = editTextObj.getText().toString();
        textViewObj.setText(textEntered);
    }

Now run the app. Enter some data to the edit text and click read. You can see the data you entered on a textview below the read button!


I think you may now understand the basic idea of using an edittext. Please post your comments. Will help you to use intents to navigate from one activity to other on my next blog.

Android Tutorial Part1 - Introduction to android programming

Hi,

The main idea behind this blog is to help you to start coding in android. I think you may have already selected the IDE for android development and added the android sdk and ADT plugin. For those who hadn't installed the above items, please check the android developer site. This blog is mainly based on the latest ADT Plugin.(ADT-16)

Hopes now you have succesfully installed the required packages. If you have any queries in installing please post your comments.

ANDROID

You may be familiar with the term 'android', as it's one of the most popular mobile phone OS. The android platform is using the Java platform. But this doesn't means you have to learn java before starting to learn android.

I don't have a plan to go to the theories, architecture etc. You can learn those from the developer site. Here I will be introducing some of the key features of android and will explain how to implements those.

Let's set go
Now everything to start developing is ready. I had selected eclipse as the IDE for developing android. You can select any other IDE's. When you start eclipse you have to set a workplace location. All the projects you start from eclipse will be saved in that location. After setting the workplace when you open the eclipse it will be like the following pic.




To start a new android project click the 'File' on the top  left and select 'New'. If 'Android Project' is in that drop down list then select that otherwise select 'Other' on the bottom of that drop down and select 'Android Project' under the folder 'Android'. Now you will be seeing a new window like the following pic.




  • Enter a project name as you like and make sure that 'Create new project in workspace' is selected. Here I'm going to name the project as "Sample1". Now click 'Next'.
  • You will be asked to select an SDK target. You can select any target, here I'm selecting Android 2.2.  Then click 'Next'.
  • Now, you will be asked to enter the 'Application Info'. Some fields will be prefilled with values. You can edit it and change the preferences as you wish later. For now change only the package name. You can set any package name for your project. The only condition is an emulator/device will run only one app with a package name. Here I'm giving the package name 'com.android.sample1'.  Now click 'Finish'.
Run the app in an android emulator

You can simply run this project in an android emulator/device. Here we are going to run this on an android emulator. An emulator is a virtual android device that runs on your computer. You can test the apps you develop on this emulator even if you don't have a device.

Creating the virtual device.
Before running the app you have to create an AVD (Android Virtual Device).  For this follow the steps
:
  1.  Select Window>AVD Manager. The 'Android Virtual Device Manager' window will be presented now.
  2. Click 'New'. I'm going to create an AVD with OS 2.2 and resolution HVGA. Because we selected the application target ad Android 2.2 earlier.
  3. Enter a name for you AVD. You can enter any name as you like. The only condition is it should atleast reflect the OS version. Will explain that after creating the AVD. I entered the name Android2.2HVGA.
  4. Select the target. I selected Android 2.2 to run our Sample app.
  5. Enter the size of the SD card. You can enter any value there. Here I'm going to enter 1024.
  6. Click 'Create AVD'.
You AVD will be created now. You can edit these info at any time by selecting the avd in the 'Android Virtual Device Manage' and tapping 'Edit'. For all your apps with target 2.2 you can use this avd.

Now select the AVD in the Android Virtual Device Manage and click 'Start'. In the new window that appears click 'Launch'. Your AVD will be as follows:

It will take some time to start the AVD completely. Let it be there and come back to eclipse!


Your project will be having the a  folder structure as in the following figure.


In android an activity represents a single screen with a user interface. So for an activity there will be a class file and a layout file. The class file will be in the src>your package name folder (src>com.android.sample1 for me) and the layout file in the res>layout folder.

 To run the app select the project name on the top of this hierarchial tree and select Run>Run As>Android Application. The following figure will help you.


 
Take a look at the emulator now. It will be like


"Hello Word, Sample1Activity"!. When ever a new project is created in android it will automaticall displays the hello world text with the base activity and app name. Now get ready to play with it!

Open the main.xml file inside the res>layout. It will be having two type of views 'Graphical Layout' and 'main.xml'


You can add the code in the main.xml and view the changes in the graphical layout. Go to the main.xml. There will be a TextView inside a LinearLayout.

In android a TextView is used to display a text/data in the screen. Inside the TextView tag there will a text set using android:text="@string/hello"(I will mention about @string later). Replace the @string/hello with whatever text you like and run the app.  Please give a little time for the emulator to build and run the app.You can always check the status of your app in the console.


When it says Activity Manager: Starting ... check the emulator. What did you see in the emulator now? You can see the text you entered in the screen!

Now come back to the main.xml. Inside the TextView tag there are other options like android:layout_width and android:layout_height. They specify the width and height of your textview. The width will be prefilled with 'fill_parent' and height with 'wrap_content'.

If width of an element in the layout is set to fill parent then it means that element will stretch to the full width of its parent. Here the LinearLayout is the parent of the text view. So the width of text view set to fill parent means it covers the entire width of the linear layout.

The height of the text view is set to wrap content. If the width of an element is set to wrap content then it means the height of that element will adjust according to the height of it's contents.

Now let's play with the height and width. Try setting both as wrap content, fill parent, in any way you like. Also try to change the text. Don't forget to replace these terms with values you like. If you wants to set height to 50, then set it as android:layout_height="50dp".

dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion.
Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent.


How was that research with height and width?  Thinks it will be interesting. Now take a look at that linear layout. The height and width of is set to fill parent. What does that mean? I think you may now know that this means the linear layout will fill the entire width and height of the screen as its height and width are set to fill parent.

Now what about placing another text view below the textview? We are going to place a text view with text size 50 saying "ANDROID IS INTERESTING :)". Just give a try first and then check my code.

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
  
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ANDROID IS INTERESTING :)"
        android:textSize="50sp"/>

</LinearLayout>


I had mentioned the text size in sp.
sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.

You have to use sp for font sizes and dp for everything else.


Will post how to use Edit Text in my next post. Please post your comments and suggestions.