Friday, February 14, 2014

Android-Eclipse: Managing The Activity Life Cycle

---
Android - Managing the Activity Lifecycle

This tutorial is based on 
http://developer.android.com/training/basics/activity-lifecycle/index.html . The steps in this tutorial is moderated from: http://katsoft.net



1) Run Eclipse.

2) Create a new Android Application. Name it as "LifeCycleTest". Click Next.


3) Accept Default Project Configuration. Click Next.


4) Accept Launcher Configuration.


5) Accept Default BlankActivity. Click Next.


6) Accept Default Activity and Layout Name. Click Finish.



7) Edit 
{project root}/src/com.example.lifecycletest/MainActivity.java
package com.example.lifecycletest;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tToast("onCreate");
    }

    public void onStart() {
    super.onStart();
    tToast("onStart");
    }

    public void onRestart() {
    super.onRestart();
    tToast("onRestart");
    }

    public void onResume() {
    super.onResume();
    tToast("onResume");
    }

    public void onPause() {
    super.onPause();
    tToast("onPause: bye bye!");
    }

    public void onStop() {
    super.onStop();
    tToast("onStop.");
    }

    public void onDestroy() {
    super.onStop();
    tToast("onDestroy.");
    }

    private void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, s, duration);
        toast.show();
    }

}



8) Edit 
{project root}/res/layout/activity_main.xml

<!--?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" />
</LinearLayout>



9) Edit 
{project root}/res/values/strings.xml .
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LifeCycleTest</string>
    <string name="hello">Hello world!</string>
    <string name="menu_settings">Settings</string>
</resources>?



10) Launch app.



11) Observe the output.
11.1) Notice the activity status message when the application is activated; "OnCreate", "OnStart", "OnResume)


11.2) Tap the Back button. Notice the Activity Status message; "OnPause","OnStop","OnDestroy".

11.3) Tap Home button. Browse app and tap "LifeCycleTest" to start the application again.

11.4) When the application is activated, tap Home button and observe the Activity Status message.

Android-Eclipse: Starting The Second Activity

---
Android - Starting the second activity

This tutorial is a continuation of 
http://android-steps.blogspot.com/2014/02/android-eclipse-building-simple-user.html.

The steps is based on 
http://developer.android.com/training/basics/firstapp/starting-activity.html. In this lesson, you’ll add some code to MainActivity that starts a new activity when the user clicks the Send button.

1) Run Eclipse and open 
MyFirstApp project.
2) Adding respond to button.
2.1) To respond to the button's on-click event, open the {project root|/res/layout/activity_main.xml layout file and add the android:onClick attribute to the <Button> element:


2.2) Open the {project root}/src/com.example.myfirstapp/MainActivity.java and add the corresponding method (refer line no. 21-24)


2.3) This requires that you import the View class (refer line no. 6)


3) Build an Intent
3.1) An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.
3.2) Inside the sendMessage() method, create an Intent to start an activity called DisplayMessageActivity:


3.3) You need to import statements for android.content.Intent and android.widget.EditText. Refer line no.5 and 8.




3.4) Add the EXTRA_MESSAGE definition to the top of the MainActivity class. Refer line no. 11.


4) Start the Second Activity
4.1) To start an activity, call startActivity() and pass it your Intent. The system receives this call and starts an instance of the Activity specified by the Intent. Refer line no. 30.



5) Create the Second Activity
5.1) Click New  in the toolbar.


5.2) Select Android Activity. Click Next.


5.3) Select Blank Activity. Click Next.


5.4) Fill-in the details. Click Finish.


5.5) Check DisplayMessageActivity Class.
package com.example.myfirstapp;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class DisplayMessageActivity extends Activity {
 @SuppressLint("NewApi")
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_display_message);

        // Make sure we're running on Honeycomb or higher to use ActionBar APIs
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Show the Up button in the action bar.
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }

     // Get the message from the intent
     Intent intent = getIntent();
     String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
     // Create the text view
     TextView textView = new TextView(this);
     textView.setTextSize(40);
     textView.setText(message);
     // Set the text view as the activity layout
     setContentView(textView);
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.activity_display_message, menu);
 return true;
 }
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
 case android.R.id.home:
  // This ID represents the Home or Up button. In the case of this
  // activity, the Up button is shown. Use NavUtils to allow users
  // to navigate up one level in the application structure. For
  // more details, see the Navigation pattern on Android Design:
  //
  // http://developer.android.com/design/patterns/navigation.html#up-vs-back
  //
  NavUtils.navigateUpFromSameTask(this);
   return true;
  }
  return super.onOptionsItemSelected(item);
 }
}


5.6) Check Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myfirstapp"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.myfirstapp.MainActivity"
            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="com.example.myfirstapp.DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.example.myfirstapp.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myfirstapp.MainActivity" />
        </activity>      
    </application>
</manifest>


5.7) Check String.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_display_message">My Message</string>
</resources>

6) Test run
6.1) Type "Hello World!"


6.2) Observe the response.

---

Android-Eclipse: Building a Simple User Interface with Toast

-----

1) RUN ADT


If you haven't started Eclipse, run ADT.

2) OPEN PROJECT


2.1) Open My First App Project.

3) EDIT THE (LAYOUT) VIEW


3.1) Clear existing layout.

3.2) In the Layouts section of Palette, click and drag LinearLayout (Vertical) to the top left corner of the main layout.
3.3) Find the Outline Panel.
Notice that there is a warning icon.
If you hover your mouse over the icon, the explanation message pops up.
We will add child objects into this layout.
3.4) Find the abc Text Fields object in the Palette.
3.5) Click the object and drag it into the LinearLayout item in the Outline Panel.
3.6) Outcome:
3.7) Find the button object in the Palette.
3.8) Drag it into LinearLayout and place it under editText1 object as follows:
3.9) Your view will look like below:
3.10) Save.
3.11) Switch to activity_main.xml tab.
You should see the following codes:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >
        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <requestFocus />
        </EditText>
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />
    </LinearLayout>
</RelativeLayout>
Take note of the highlighted (id) texts, i.e editText1 and button1.
Later, we will use these id names to bind Java codes to the XML layout.

4) VIEW JAVA CODES

4.1) In the Package Explorer panel, find the source file MainActivity.java.
4.2) Double-click the file name.
Notice two panels.
4.2.1) Main Panel.

5) EDITING JAVA CODES

5.1) Initially, XML Layout and Java Codes are not related and thus they do not know one another. Objects in the XML Layout (e.g. editText1 and button1) must be identified first before they can be processed by Java Codes.
5.2) Let’s say we want …
the button to respond to clicks by …
popping up a message containing text entered by user in the text field.
5.3) We need the following algorithm:
(blue colour text refers to the codes in Step 5.4)
1) Bind a button object to the button layout identified by button1. (line no.13)
2) Attach an onClickListener (a method to listen for click events) method to the button. (line no.14)
3) Override the onClick (a method to respond to click events) method to the button. (line no.16)
4) Bind a text object to the text layout identified by textEdit1. (line no.17)
5) Get the input value from the text object and convert the value to a string. (line no.18)
6) Display the string value using toast object. (line no.19)
5.4) Edit the codes as follows:
5.5) Error markers appear under certain keywords that are not recognized by Java compiler. However, Eclipse has a smart debugging function that is able to suggest corrections. In this example, choose the option to import the missing class.
5.6) Repeat the same technique to the other error markers. Do it carefully and ensure that you are choosing option to import class only.
5.7) Outcome:
5.8) Run as Android Application…
5.9) Outcome: