Labels

Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Sunday, February 17, 2013

Android - Simple Calculator


1) Run Eclipse.
2) Create new Android Application. Type "SimpleCalc".


2) Accept Default Project Configuration. Click Next.

3) Accept Default Launcher Configuration. Click Next.

4) Create New Blank Activity. Click Next.

5) Accept Default Activity and Layout name. Click Finish.

6) Edit Codes.
6.1) MainActivity.Java

6.2) activity_main.xml

6.3) strings.xml

Android - Login Request Example



This tutorial is moderated from http://www.edumobile.org/android/android-development/login-request-example-in-android/ .

1) Run Eclipse.

2) Create New Android Application. Type name "LoginRequestTest".


3) Accept Default Project Configuration. Click Next.

4) Accept Default Launcher Configuration. Click Next.

5) Select New Blank Activity. Click Next.

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

7) Edit the codes.
7.1) MainActivity.Java



ppackage com.example.loginrequesttest;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    EditText txtUserName;
     EditText txtPassword;
     Button btnLogin;
     Button btnCancel;
      
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtUserName=(EditText)this.findViewById(R.id.txtUname);
        txtPassword=(EditText)this.findViewById(R.id.txtPwd);
        btnLogin=(Button)this.findViewById(R.id.btnLogin);
        btnLogin=(Button)this.findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new OnClickListener() {
    
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
     
    if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
           Toast.makeText(MainActivity.this, "Login Successful",Toast.LENGTH_LONG).show();
          } else{
           Toast.makeText(MainActivity.this, "Invalid Login",Toast.LENGTH_LONG).show();
          }
     
   }
  });       
    }
      
}



7.2) activity_main.xml



<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" >
 
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">
      
<TableRow> 
 <TextView 
 android:text="User Name: "
 android:id="@+id/TextView01"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content">
 </TextView>
  
 <EditText 
 android:text=""
 android:id="@+id/txtUname"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
 </EditText>
</TableRow>
 
 
<TableRow>
 <TextView 
 android:text="Password: "
 android:id="@+id/TextView02"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content">
 </TextView>
 
 
 <EditText 
 android:text=""
 android:id="@+id/txtPwd"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:password="true">
 </EditText>
</TableRow>
 
 
<TableRow>
 <Button
 android:text="Cancel"
 android:id="@+id/btnCancel"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
 </Button>
 
 
 <Button
 android:text="Login"
 android:id="@+id/btnLogin"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">
 </Button>
 
 
</TableRow>
 
 
</TableLayout>
 
</RelativeLayout>




8) Run


8.1) Enter Username/password as "user/user"

Android - Create FullScreen activity


1) Run Eclipse.
2) Create New Android Application. Type FullScreenTest.



3) Accept Default Configuration. Click Next.




4) Accept Default Launcher Configuration. Click Next.


5) Select Create Login Activity. Click Next.


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


7)Accept Default FullScreen Activity. Click Finish.


Project Generated.

Run As Android Application.

Android - Toasts UI



This tutorial is based on http://developer.android.com/guide/topics/ui/notifiers/toasts.html .

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. For example, navigating away from an email before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout.


The following steps is moderated from http://android-apps-blog.blogspot.com/2011/04/how-to-display-simple-toast-notificatin.html .

1) Run Eclipse.
2) Create a new Android Application Project. Type a name "SimpleToast". Click Next.


3. Accept Default Project Configuration. Click Next.

4. Accept Default Launcher settings. Click Next.

5. Select New Blank Activity. Click Next.

6. Accept Default Activity and Layout name. Click Finish.

7. Edit {project root}/srccom.example.simpletoast/MainActivity.java.



 package com.example.simpletoast;

 import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.Toast;
  
 public class MainActivity extends Activity {
  
  private Button button;
  
  public void onCreate(Bundle savedInstanceState) {
  
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
  
   button = (Button) findViewById(R.id.buttonToast);
  
   button.setOnClickListener(new OnClickListener() {
  
      @Override
      public void onClick(View arg0) {
  
         Toast.makeText(getApplicationContext(), 
                                "Button is clicked", Toast.LENGTH_LONG).show();
  
      }
   });
  }
} 



8. Edit {project root}/res/layout/activity_main.xml .
Note: You may get warning message "[I18N] Hardcoded string "Show Toast", should use @string resource" for the statement "android:text="Show Toast" />". At this moment, ignore it.


<?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" >
 
    <Button
        android:id="@+id/buttonToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Toast" />
 
</LinearLayout>



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 - Starting the second activity


This tutorial is a continuation of http://basic-steps.blogspot.com/2013/02/android-building-simple-user-interface.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 - Building a Simple User Interface


This tutorial is a continuation of http://basic-steps.blogspot.com/2013/02/android-understanding-my-first-app.html.   

The steps in this tutorial is based on http://developer.android.com/training/basics/firstapp/building-ui.html#Button. It guides the reader to learn about Simple User Interface.

1) Run Eclipse and open MyFirstApp project.

2) Open {project root}/res/layout/activity_main.xml



3) First, delete the <TextView> element and change the <RelativeLayout> element to <LinearLayout>. Then add the android:orientation attribute and set it to "horizontal". The result looks like this:


4) To create a user-editable text field, add an <EditText> element inside the <LinearLayout>.


5) Add String Resources.
5.1) Open {project root}/res/values/strings.xml and edit as follows:


6) Add a Button.
6.1) Get back to {project root}/res/layout/activity_main.xml and  add a <Button> to the layout, immediately following the <EditText> element:


7) Run app.
7.1) Make sure that your Android Emulator is running and detected by Eclipse.
7.2) In project explorer panel, Right-click {project root}, choose Run As/Android Application.


7.3) Type Hello and click Send.


8) Re-edit the layout and run
8.1) Re-edit layout.xml as follows:


8.2) Run and observe the output.






Android - Understanding My First App


The next thing to do after the first Android Application (app) successfully ran is to understand the codes and structures behind itself.

This tutorial is a continuation of http://basic-steps.blogspot.com/2013/02/android-building-your-first-app.html which was based on  http://developer.android.com/training/basics/firstapp/creating-project.html.


1) Run Eclipse. Open MyFirstApp project.

2) In Eclipse, look at the project explorer panel. Examine MyFirstApp folder structure.


3) As for a start, we are going to look at MainActivity.java, AndroidManifest.xml and project.properties.

4) MainActivity.java
4.1) Double-click the item MyFirstApp/src/com.example.myfirstapp/MainActivity.java


4.2) By default, the editor doesn't show line numbers.
4.2.1) You can turn on this feature via menu Window/Preferences.
4.2.2) The Preferences window pops up. Click general/Editors/Text Editors. Tick Show line numbers. Click Apply. Click OK.


4.2.3.) As a result you get a better view of the codes.


4.3) There are three segments of codes; Package segment, Import segment and Class Declaration segment.

4.3) Package segment (line no.2) identifies your app as a unique app and is especially important when the app is published in the Internet.

4.4) The import segment (line no. 3 - 5) declares the standard Android classes that are required by your app.
4.4.1) android.os.Bundle - is used to send arbitrary data from one activity to another.
4.4.2) android.app.Activity - is used to create activity (one of the several components that can make up an Android Application). What distinguishes an Activity from all other components is that it is the only component that can (and must) have a user interface.
4.4.3) android.view.Menu -Interface for managing the items in a menu.

5) The file MainActivity.java contains the declaration of the class MainActivity at line no.7
public class MainActivity extends Activity {...}

5.1) Class MainActivity extends the class Activity. This means that MainActivity will inherit all the properties and methods of the class Activity.

5.2) Class MainActivity may define instructions for the methods that it has inherited, which is called overrides. (Line no 9 and line no 15). For the methods onCreate and onCreateOptionsMenu, MainActivity has its own instructions to be executed.

@Override
protected void onCreate(Bundle savedInstanceState) {...
...


@Override
public boolean onCreateOptionsMenu(Menu menu) {...


6) The super keyword is not specific to Android. It's a concept belonging to OOP, and represents the parent class of the class in which you use it. In Android, it's mostly usefull when you create your own Activity or component, and lets you call a default behavior before implementing yours.


super.onCreate(savedInstanceState);


7) setContentView and getMenuInflater

7.1)  The setContentView method sets the view layout for the activity.
setContentView(R.layout.activity_main);

The resource is located at {project root}/res/layout/activity_main.xml



7.1.1) Notice that Line no.10 and 11 will cause the text to be placed at the center of the screen.


7.2) The getMenuInflater() method sets the menu item of the app.
getMenuInflater().inflate(R.menu.activity_main, menu);

The resource is located at {project root}/res/menu/activity_main.xml



7.2.1) Whenever the user tap on Menu button, the menu item will be displayed on the screen.

7.3) Both of the files contain the keyword @string. These keywords are pointing to the string resources located at {project root}/res/values/string.xml


8) The app configuration details is stored in {project root}/AndroidManifest.xml


8.1) Line no. 7 defines the minimum SDK and target SDK version. This corresponds to the settings made during the New Android Application dialog window


8.2) Line no. 11 defines the general application settings. This includes the application name and icons to be used.

8.3) Line no. 16 registers the Activity within this application. This corresponds to the {project root}/src/com.example.myfirstapp/MainActivity.java

8.4) Line no. 20 defines the Intent for the Activity, i.e the abstract description of an operation to be performed towards the Activity. In this example, it calls for the Launcher to launch this app.


9) The app properties details is stored in {project root}/project.properties


9.1) As the comment texts have stated, do not modify this file, you need to use menu Project/Properties in order to change the target. Bear in mind that you need to install the relevant SDK version before changing the target, otherwise Eclipse may produce code error message.