Pages

Ads 468x60px

Saturday, 6 July 2013

Resolving Intent Filter Collision

Resolving Intent Filter Collision

In the previous lesson , you learned that the <intent-filter> element defines how your activity can be invoked by another activity. 
What happens if another activity (in either the same or a separate application) has the same filter name? 

For example, suppose your application has another activity named Activity3, with the following entry in the AndroidManifest.xml file:

<?xml version=”1.0” encoding=”utf-8”?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”net.learn2develop.Activities”
android:versionCode=”1”
android:versionName=”1.0”>
<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
<activity android:name=”.MainActivity”
android:label=”@string/app_name” >
<! -- android:theme=”@android:style/Theme.Dialog” -- >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity android:name=”.Activity2”
android:label=”Activity 2”>
<intent-filter>
<action android:name=”net.learn2develop.ACTIVITY2” />
<category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</activity>
<activity android:name=”.Activity3”
android:label=”Activity 3”>
<intent-filter>
<action android:name=”net.learn2develop.ACTIVITY2” />
<category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion=”9” />
</manifest>

If you call the startActivity() method with the following intent, then the Android OS will display
a selection as shown in Figure :

startActivity(new Intent(“net.learn2develop.ACTIVITY2”));

If you check the “Use by default for this action” item and then select an activity, then the next time the intent “net.learn2develop.ACTIVITY2” is called again, it will always launch the previous activity that you have selected.

To clear away this default, go to the Settings application in Android and select Applications 
➪ Manage applications and select the application name (see Figure). When the details of the application are shown, scroll down to the bottom and click the Clear defaults button.



 
Reade more >>

Wednesday, 3 July 2013

Linking Activities Using Intents

An Android application can contain zero or more activities. When your application has more than one activity, you may need to navigate from one activity to another. In Android, you navigate between activities  through what is known as an intent.

The best way to understand this very important but somewhat abstract concept in Android is to experience it first hand and see what it helps you to achieve.The following Try It Out shows how to add another activity to an existing project and then navigate between the two activities.

Linking Activities with intents

1 Using the Activities project created earlier, add the following statements in bold to the
AndroidManifest.xml file:

<?xml version=”1.0” encoding=”utf-8”?>
      <manifest xmlns:android=”http://schemas.android.com/apk/res/android”
             package=”net.learn2develop.Activities”
              android:versionCode=”1”
              android:versionName=”1.0”>
       <application android:icon=”@drawable/icon” android:label=”@string/app_name”>
       <activity android:name=”.MainActivity”  android:label=”@string/app_name”
          android:theme=”@android:style/Theme.Dialog” >
       <intent-filter>
          <action android:name=”android.intent.action.MAIN” />
          <category android:name=”android.intent.category.LAUNCHER” />
      </intent-filter>
  </activity>
   <activity android:name=”.Activity2” android:label=”Activity 2”>
<intent-filter>
   <action android:name=”net.learn2develop.ACTIVITY2” />
   <category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion=”9” />

2. Right click on the package name under the src folder and select New ➪ Class (see Figure  ).

3. Name the new class fi le Activity2 (see Figure) and click Finish.

4. Make a copy of the main.xml file by right-clicking on it and selecting Copy. Then, right-click on the res/layout folder and select Paste. Name the file activity2.xml. The res/layout folder will now contain the activity2.xml file (see Figure)




5. Modify the activity2.xml file as follows:

  <?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” >
<TextView
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”This is Activity 2!”
/> </LinearLayout>

6. In the Activity2.java file, add the following statements in bold:
    package net.learn2develop.Activities;
        import android.app.Activity;
        import android.os.Bundle;
        public class Activity2 extends Activity {
    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);
        }
    }

7. Modify the MainActivity.java file as shown in bold:

    package net.learn2develop.Activities;
            import android.app.Activity;
            import android.os.Bundle;
            import android.util.Log;
            import android.view.Window;
            import android.view.KeyEvent;
            import android.content.Intent;
        public class MainActivity extends Activity
        {
                String tag = “Events”;
            /** Called when the activity is first created. */
        @Override
            public void onCreate(Bundle savedInstanceState)
            {
                super.onCreate(savedInstanceState);
                //---hides the title bar---
                //requestWindowFeature(Window.FEATURE_NO_TITLE);
                setContentView(R.layout.main);
                Log.d(tag, “In the onCreate() event”);
            }
        public boolean onKeyDown(int keyCode, KeyEvent event)
        {
            if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
            {
            startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
    }
          return false;
  }
             public void onStart() { //... }
             public void onRestart() { //... }
             public void onResume() { //... }
             public void onPause() { //... }
             public void onStop() { //... }
             public void onDestroy() { //... }
   }

8. Press F11 to debug the application on the Android Emulator. When the first activity is loaded, click the center of the directional pad (see Figure), on a real device this can be achieved by pressing down the trackball). The second activity will now be loaded.


How It Works

As you have learned, an activity is made up of a UI component (for example, main.xml) and a class component (for example, MainActivity.java). Hence, if you want to add another activity to a project, you need to create these two components.

In the AndroidManifest.xml file, specifically you have added the following:
     <activity android:name=”.Activity2”
             android:label=”Activity 2”>
<intent-filter>
        <action android:name=”net.learn2develop.ACTIVITY2” />
        <category android:name=”android.intent.category.DEFAULT” />
        </intent-filter>
</activity>

Here, you have added a new activity to the application. Note the following:

➤➤ The name of the new activity added is “Activity2”.

➤➤ The label for the activity is named “Activity 2”.

➤➤ The intent filter name for the activity is “net.learn2develop.ACTIVITY2”. Other activities that wish to call this activity will invoke it via this name. Ideally, you should use the reverse domain name of your company as the intent filter name in order to reduce the chances of another application having the same intent filter. The next section discusses what happens when two or more activities have the same intent filter.

➤➤ The category for the intent filter is “android.intent.category.DEFAULT”. You need to add this to the intent filter so that this activity can be started by another activity using the startActivity() method (more on this shortly). In the MainActivity.java file, you implemented the onKeyDown event handler. This event is fired whenever the user presses one of the keys on the device. When the user presses the center key on the directional pad (as represented by the KeyEvent.KEYCODE_DPAD_CENTER constant), you use the startActivity() method to display Activity2 by creating an instance of the Intent class and passing it the intent filter name of Activity2 (which is net.learn2develop.ACTIVITY2):

   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
           if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
           {
                startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
           }
        return false;
  }

Activities in Android can be invoked by any application running on the device. For example, you can create a new Android project and then display Activity2 by using its net.learn2develop.ACTIVITY2 intent filter. This is one of the fundamental concepts in Android that enables an application to invoke another easily.
If the activity that you want to invoke is defined within the same project, you can rewrite the preceding statement like this:

startActivity(new Intent(this, Activity2.class));
However, this approach is applicable only when the activity you want to display is within the same project as the current activity.

Reade more >>

Tuesday, 2 July 2013

Displaying a Progress Dialog

Displaying a Progress Dialog

Besides the plain dialog that you created in the previous section, you can also create a progress dialog. A progress dialog is useful for showing the progress of some activities, such as the status of a download operation.

Displaying a Progress Dialog Window Using an Activity

1. Using the same project created in the previous section, add the following statements in bold to the MainActivity.java file:

            package net.learn2develop.Dialog;
                import android.app.Activity;
                import android.app.AlertDialog;
                import android.app.Dialog;
                import android.content.DialogInterface;
                import android.os.Bundle;
                import android.view.View;
                import android.widget.Button;
                import android.widget.Toast;
                import android.app.ProgressDialog;
                import android.os.Handler;
                import android.os.Message;
            public class MainActivity extends Activity
            {
                    CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
                    boolean[] itemsChecked = new boolean [items.length];
                    private ProgressDialog _progressDialog;
                    private int _progress = 0;
                    private Handler _progressHandler;
                    /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    Button btn = (Button) findViewById(R.id.btn_dialog);
                    btn.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v)
               {
                        showDialog(1);
                         _progress = 0;
                         _progressDialog.setProgress(0);
                         _progressHandler.sendEmptyMessage(0);
            }
            });
        _progressHandler = new Handler() {
       
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                    if (_progress >= 100) {
                    _progressDialog.dismiss();
            }
            else
            {
                _progress++;
                _progressDialog.incrementProgressBy(1);
                _progressHandler.sendEmptyMessageDelayed(0, 100);
            }
         }
        };
       }
            @Override
       protected Dialog onCreateDialog(int id)
       {
            switch (id) {
            case 0:
            return new AlertDialog.Builder(this)
            //...
            //...
            .create();
            case 1:
                _progressDialog = new ProgressDialog(this);
                _progressDialog.setIcon(R.drawable.icon);
                _progressDialog.setTitle(“Downloading files...”);
                _progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                _progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, “Hide”, new
            DialogInterface.OnClickListener()
            {
                 public void onClick(DialogInterface dialog,  int whichButton)
                 {
                    Toast.makeText(getBaseContext(),
                    “Hide clicked!”, Toast.LENGTH_SHORT).show();
                 }
            });
                _progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, “Cancel”, new
                DialogInterface.OnClickListener()
             {
                public void onClick(DialogInterface dialog,  int whichButton)
                {
                        Toast.makeText(getBaseContext(),
                        “Cancel clicked!”, Toast.LENGTH_SHORT).show();
                   }
              });
                 return _progressDialog;
             } return null;
            }
          }

2. Press F11 to debug the application on the Android Emulator. Click the button to display the progressdialog (see Figure ). Observe that the progress bar will count up to 100.


How It Works

To create a progress dialog, you first create an instance of the ProgressDialog class and set its various properties, such as icon, title, and style:

            _progressDialog = new ProgressDialog(this);
            _progressDialog.setIcon(R.drawable.icon);
            _progressDialog.setTitle(“Downloading files...”);
            _progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

You then set the two buttons that you want to display inside the progress dialog:

     _progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, “Hide”, new
       DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                        Toast.makeText(getBaseContext(),
                    “Hide clicked!”, Toast.LENGTH_SHORT).show();
            }
         });
         _progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, “Cancel”, new
            DialogInterface.OnClickListener()
             {
                    public void onClick(DialogInterface dialog, int whichButton)
                    {
                        Toast.makeText(getBaseContext(),
                           “Cancel clicked!”, Toast.LENGTH_SHORT).show();
                     }
                });
                return _progressDialog;
             }

The preceding causes a progress dialog to appear (see Figure)


To display the progress status in the progress dialog, you need to use a Handler object to run a background thread:

            _progress = 0;
            _progressDialog.setProgress(0);
           _progressHandler.sendEmptyMessage(0);

The background thread counts up to 100, with each count delayed by 100 milliseconds:

       _progressHandler = new Handler()
        {
            public void handleMessage(Message msg)
            {
                super.handleMessage(msg);
                if (_progress >= 100)
                {
                _progressDialog.dismiss();
                } else
                {
                        _progress++;
                        _progressDialog.incrementProgressBy(1);
                     _progressHandler.sendEmptyMessageDelayed(0, 100);
            }
         }
      };

When the count reaches 100, the progress dialog is dismissed.

Reade more >>

Monday, 1 July 2013

Displaying a Dialog Window

Displaying a Dialog Window

There are times where you need to display a dialog window to get a confirmation from the user. In this case, you can override the onCreateDialog() protected method defined in the base Activity  class to display a dialog window. The following Try It Out shows you how.

1. Using Eclipse, create a new Android project and name it Dialog.
2. Add the following statements in bold to the main.xml file:
 
<?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” >
     <TextView
            android:layout_width=”fill_parent”
            android:layout_height=”wrap_content”
            android:text=”@string/hello” />
     <Button
            android:id=”@+id/btn_dialog”
            android:layout_width=”fill_parent”
           android:layout_height=”wrap_content”
           android:text=”Click to display a dialog” />
     </LinearLayout>

3. Add the following statements in bold to the MainActivity.java file:

        package net.learn2develop.Dialog;
            import android.app.Activity;
            import android.os.Bundle;
            import android.app.AlertDialog;
            import android.app.Dialog;
            import android.content.DialogInterface;
            import android.view.View;
            import android.widget.Button;
            import android.widget.Toast;
      public class MainActivity extends Activity
      {
             CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
             boolean[] itemsChecked = new boolean [items.length];
            /** Called when the activity is first created. */
             @Override
      public void onCreate(Bundle savedInstanceState) 
      {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button btn = (Button) findViewById(R.id.btn_dialog);
        btn.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v) 
          {
               showDialog(0);
          }
     });
}
  @Override
    protected Dialog onCreateDialog(int id) 
    {
       switch (id) {
        case 0: return new AlertDialog.Builder(this)
        .setIcon(R.drawable.icon)
        .setTitle(“This is a dialog with some simple text...”)
        .setPositiveButton(“OK”, new
    DialogInterface.OnClickListener() 
    {
       public void onClick(DialogInterface dialog, int whichButton)
       {
            Toast.makeText(getBaseContext(),
            “OK clicked!”, Toast.LENGTH_SHORT).show();
       }
 })
         .setNegativeButton(“Cancel”, new
         DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
  {
          Toast.makeText(getBaseContext(),
           “Cancel clicked!”, Toast.LENGTH_SHORT).show();
   }
})

    .setMultiChoiceItems(items, itemsChecked, new
     DialogInterface.OnMultiChoiceClickListener() {
     @Override
   public void onClick(DialogInterface dialog, int which, boolean isChecked) 
    {
       Toast.makeText(getBaseContext(),
        items[which] + (isChecked ? “ checked!”: “ unchecked!”),
        Toast.LENGTH_SHORT).show();
    }
  }
) .create();
} return null;
  }
}

4. Press F11 to debug the application on the Android Emulator. Click the button to display the dialog (see Figure). Checking the various checkboxes will cause the Toast class to display the text of the item checked/unchecked. To dismiss the dialog, click the OK or Cancel button.


How It Works

  To display a dialog, you first override the onCreateDialog() method in the Activity class:
      @Override
       protected Dialog onCreateDialog(int id) 
       {
        //... some code
       }

This method is called when you call the showDialog() method:

  Button btn = (Button) findViewById(R.id.btn_dialog);
  btn.setOnClickListener(new View.OnClickListener() 
  {
     public void onClick(View v) 
      {
          showDialog(0);
      }
});

The onCreateDialog() method is a callback for creating dialogs that are managed by the activity. When you call the showDialog() method, this callback will be invoked. The showDialog() method accepts an integer argument identifying a particular dialog to display.
To create a dialog, you use the AlertDialog class’s Builder constructor. You set the various properties, such as icon, title, and buttons, as well as checkboxes:

   @Override
   protected Dialog onCreateDialog(int id)
   {
        switch (id) {
        case 0: return new AlertDialog.Builder(this)
               .setIcon(R.drawable.icon)
               .setTitle(“This is a dialog with some simple text...”)
               .setPositiveButton(“OK”, new
      DialogInterface.OnClickListener() 
      {
          public void onClick(DialogInterface dialog, int whichButton)
          {
                  Toast.makeText(getBaseContext(),
                  “OK clicked!”, Toast.LENGTH_SHORT).show();
           }
})
                  .setNegativeButton(“Cancel”, new
         DialogInterface.OnClickListener()
         {
             public void onClick(DialogInterface dialog, int whichButton)
             {
                     Toast.makeText(getBaseContext(),
                     “Cancel clicked!”, Toast.LENGTH_SHORT).show();
              }
    })
                      .setMultiChoiceItems(items, itemsChecked, new
                       DialogInterface.OnMultiChoiceClickListener() 
                        {
           @Override
           public void onClick(DialogInterface dialog, int which, boolean isChecked)
           {
                 Toast.makeText(getBaseContext(),
                  items[which] + (isChecked ? “ checked!”: “ unchecked!”),
                  Toast.LENGTH_SHORT).show();
            }
        }
    ) .create();
  } return null;
}


The preceding code sets two buttons: OK and Cancel, using the setPositiveButton() and setNegativeButton() methods, respectively. You also set a list of checkboxes for users to choose via the setMultiChoiceItems() method. For the setMultiChoiceItems() method, you passed in two arrays: one for the list of items to display and another to contain the value of each item to indicate if they are checked. When each item is checked, you use the Toast class to
display a message (see Figure).




Reade more >>

Applying Styles and themes to Activity

Applying Styles and themes to Activity

By default, an activity occupies the entire screen. However, you can also apply a dialog theme to an activity so that it is displayed as a fl oating dialog. For example, you might want to customize your activity to display as a pop-up, warning the user about some actions that they are going to perform. In this case, displaying the activity as a dialog is a good way to get their attention.

To apply a dialog theme to an activity, simply modify the <Activity> element in the
AndroidManifest.xml file by adding the android:theme attribute:

<?xml version=”1.0” encoding=”utf-8”?>
  <manifest xmlns:android=”http://schemas.android.com/apk/res/android”
     package=”net.learn2develop.Activities”
     android:versionCode=”1” android:versionName=”1.0”>
<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
   <activity android:name=”.MainActivity” android:label=”@string/app_name”
       android:theme=”@android:style/Theme.Dialog” >
    <intent-filter>
 <action android:name=”android.intent.action.MAIN” />
    <category android:name=”android.intent.category.LAUNCHER” />
           </intent-filter>
          </activity>
        </application>
       <uses-sdk android:minSdkVersion=”9” />
</manifest>

Doing so will make the activity appear as a dialog, as shown in Figure


Hiding the Activity Title

You can also hide the title of an activity if desired (such as when you just want to display a status update to the user). To do so, use the requestWindowFeature() method and pass it the Window.FEATURE_NO_TITLE constant, like this: 

 package net.learn2develop.Activities;
     import android.app.Activity;
     import android.os.Bundle;
     import android.util.Log;
     import android.view.Window;

          public class MainActivity extends Activity
          {
                   String tag = “Events”;
                   /** Called when the activity is first created. */
                   @Override
            public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    //---hides the title bar---
                          requestWindowFeature(Window.FEATURE_NO_TITLE);
                          setContentView(R.layout.main);
                         Log.d(tag, “In the onCreate() event”);
                      }
               }

This will hide the title bar, as shown in Figure


Reade more >>

Practice: Life Cycle of an Android Activity

Practice: Life Cycle of an Android Activity

1. Using Eclipse, create a new Android project and name it as shown in Figure Below.

2.   In the MainActivity.java file, add the following statements in bold:
     
        package net.learn2develop.Activities;
        import android.app.Activity;
        import android.os.Bundle;
        import android.util.Log;
  
public class MainActivity extends Activity
  {
         String tag = “Events”;
         /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Log.d(tag, “In the onCreate() event”);
       }
     public void onStart()
     {
         super.onStart();
        Log.d(tag, “In the onStart() event”);
     }
    public void onRestart()
    {
            super.onRestart();
             Log.d(tag, “In the onRestart() event”);
     }
  public void onResume()
  {
        super.onResume();
        Log.d(tag, “In the onResume() event”);
   }
   public void onPause()
   {
        super.onPause();
        Log.d(tag, “In the onPause() event”);
   }
    public void onStop()
    {
        super.onStop();
        Log.d(tag, “In the onStop() event”);
     }
     public void onDestroy()
    {
            super.onDestroy();
           Log.d(tag, “In the onDestroy() event”);
     }
}

3.   Press F11 to debug the application on the Android Emulator.
4.   When the activity is first loaded, you should see the following in the LogCat window (click on the Debug perspective; see also Figure below :

12-28 13:45:28.115: DEBUG/Events(334):      In the onCreate() event
12-28 13:45:28.115: DEBUG/Events(334):      In the onStart() event
12-28 13:45:28.115: DEBUG/Events(334):      In the onResume() event



5 When you now press the back button on the Android Emulator, observe that the following is printed:

       12-28 13:59:46.266: DEBUG/Events(334): In the onPause() event
       12-28 13:59:46.806: DEBUG/Events(334): In the onStop() event
       12-28 13:59:46.806: DEBUG/Events(334): In the onDestroy() event
6  Click the Home button and hold it there. Click the Activities icon and observe the following:

         12-28 14:00:54.115: DEBUG/Events(334): In the onCreate() event
         12-28 14:00:54.156: DEBUG/Events(334): In the onStart() event
         12-28 14:00:54.156: DEBUG/Events(334): In the onResume() event

7 Press the Phone button on the Android Emulator so that the activity is pushed to the background. Observe the output in the LogCat window:

       12-28 14:01:16.515: DEBUG/Events(334): In the onPause() event
       12-28 14:01:17.135: DEBUG/Events(334): In the onStop() event

8 Notice that the onDestroy() event is not called, indicating that the activity is still in memory. Exit the phone dialer by pressing the Back button. The activity is now visible again. Observe the output in the LogCat window:

         12-28 14:02:17.255: DEBUG/Events(334): In the onRestart() event
         12-28 14:02:17.255: DEBUG/Events(334): In the onStart() event
         12-28 14:02:17.255: DEBUG/Events(334): In the onResume() event

The onRestart() event is now fi red, followed by the onStart() and onResume() events.
How It Works As you can see from this simple experiment, an activity is destroyed when you press the Back button. 

This is crucial to know, as whatever state the activity is currently in will be lost; hence, you need to write additional code in your activity to preserve its state when it is destroyed (Next Lesson  will show you how).

At this point, note that the onPause() event is called in both scenarios — when an activity is sent to the background, as well as when it is killed when the user presses the Back button.
When an activity is started, the onStart() and onResume() events are always called, regardless of whether the activity is restored from the background or newly created.

Reade more >>

.

Education blog