How do you rate this blog

Thursday, December 22, 2011

Introduction to Fragments


    As the name suggests, a fragment is a subset of the UI in an activity. What this means is now  you can create multiple fragments in the same UI of an activity. The fragment can perform actions independent of other fragments while an activity is running. This means a fragment has its own lifecycle and it exists till the activity is running. The fragments can also be reused. This property is released from Android 3.0 API 11 onwards but it can be used in lower version as well, refer to this to get more info.
                So what is the use of fragments, well there are lot of places where these properties can be exploited to the fullest. A developer can create 2 separate fragments where in one fragment can be used to display a list of values and other fragment can be used to display description of the item selected in the list. Developers can also take advantage of this in devices like tablets where the display area is very large and by using fragments they can add many functionality in a single activity.

LifeCycle on a Fragment –
                In this lets see how to use a fragment. The following are the states while you use a fragment.
Creation of Fragment – You need to create a subclass of Fragments. Then you need to attach the fragment to an activity using Attach(). Then you need to call the view hierarchy with which the fragments are associated with using creatView() method.  Then you need to create onCreate() where in you instantiate the fragment and retain the parts of the fragment when it is paused state.

Running state of a fragment- When the activity is started the onStart() method is called by the activity to make the fragment visible to user.  

Resume –  The method onResume() makes the fragment intractable with the user.

Paused – In this state the fragment is processing function after the user action or has been paused. This is done by onPause() method.

Stop – When the activity is completed or closed by the user the method onStop() is called.

Destruction of the fragment – The method onDestroyView() is called to destroy the view hierarchy associated with the fragment. Then it calls onDestroy() to release all the resources used by the fragment. Then the fragment is disassociated from the activity by the method onDettach().

As you can see it’s relatively complex but none the less interesting and helpful in using the screen real estate and providing a nice UI to the users. In the next post will give an example using the fragment.

Sunday, December 18, 2011

Creating Simple Gestures


Gestures are mainly useful in touch screens. Instead of users clicking on the menu and performing actions they can use gestures to perform the same. A gesture can be used to perform actions like add, delete, update etc.
In this post I have used to gestures to display alert dialogues. For this you need to add gestures using the GestureBuilder. The GestureBuilder is available in your emulators. Make sure that your emulator has SD card configured.
If you need to add SD Card into the emulator –
Step1 – Open command prompt go the folder where the android-sdk is located and go to tools and use the below command
“mksdcard 256M <path>\<filename>.iso“
you can vary the size of the SD card based on your needs.
Step2 - Now open the AVD manager, click on the AVD for which you want to add the SD card and click on edit.
Step 4 - Now make the SD card point to the iso file created in the step above.
Open the GestureBuilder app in the emulator and create your own gestures as shown below.



Now that you have added the Gestures you need to copy it to the local environment and add it to the solution since it will be used in the GestureOverlayView.
You can copy the data from the sdcard by –
Step 1 – Start the emulator.
Step2 – open command prompt and go to the <anroid-sdk location>/platform-tools and use the below command
Adb pull /sdcard/gestures <folder on your local environment>

Now create a new project. Then create a new folder called ‘raw’ under ‘res’. Then open ‘main.xml’ file under layouts and remove the default text box. Now add the GestureOverlayView and match its width and height with that of the parent.

Now go to the main java file, you will notice it extends Activity by default. Since we also need gestures we have to implement OnGesturePerformedListener as well. Once you do that you can see it suggests you to implement onGesturePerformed as well. This function is required since we will define the actions based on the gestures which are available.
Before defining actions we need to define GestureOverlayView and bind it to the control which we have defined in the ‘main.xml’ and add function which will read the gesture performed.
GestureOverlayView gov=(GestureOverlayView) findViewById(R.id.gestureOverlayView1);
gov.addOnGesturePerformedListener(this);
Now we need to define the Gesture library and include the gestures we had created earlier.
gl=GestureLibraries.fromRawResource(this, R.raw.gestures);
if(!gl.load()){
  finish();
}

Now we need to define the action when the gesture is performed and this is done inside onGesturePerformed.
Here you need to create an arraylist which will store all the gestures. Then we need to see if the gesture has matched a certain gesture in the library. If the score is above 1 then it’s a pretty good one else its considered poor. Hence we will consider only those gestures which have score greater than 1 and create an alert dialog with the name of the gesture.
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {                        
ArrayList<Prediction> pred=gl.recognize(gesture);         
for(Prediction p:pred){
if(p.score > 1.0){
AlertDialog.Builder ab=new AlertDialog.Builder(GesturesDemoActivity.this);
ab.setTitle("Gesture Demo");
ab.setMessage("You used the gesture"+p.name);
ab.setPositiveButton("OK",null);
ab.show();
                }
}
The code will look like the snapshot shown below


Now run the project in the simulator. Once the app starts running, write a gesture which you have created earlier as shown below.



When you release the touch from the screen you can see an alert dialog appears with the name of the gesture on it.


Thursday, December 15, 2011

Beautiful world of Android Sensors – Accelerometer


Well finally decided to get hands on sensors in android. In my view it’s the most exciting part of android. It will surely light up new ideas.
The sensors are used to detect changes in the phones surrounding environment like change in position, temperature, light etc. Android provides various sensors like – Accelerometer, Gyroscope, Light, Magnetic Field, Pressure, Temperature, Orientation and Proximity. I am sure looking at the list you will be excited to use these features. There is a catch however, not all sensors are available on all the phones. Only in high end android phones there is a high possibility of all the sensor hardware being included. In this post I will use the Accelerometer since it will be available in almost all android phones.
                I will use the accelerometer and try to find out if the phone has been shaked. If the phone has been shaked beyond certain threshold it should display it in the textbox with the value.
                Create a new project and choose Android 2.3.3. Go to the layout under the folder ‘res’ and open the file main.xml and remove the default contents. Add a Large text which will display a text if the phone has been shaked along with the value.
Now open the main java file, and declare a variable which is of the type SensorManager, also declare variable which will hold the acceleration across x, y and z axis as shown below.
SensorManager sensorMgr;
float xaxis,yaxis,zaxis;
float accel;

Next you need to create a SensorEventListener, if you are referring to old android ebooks it might have used SensorListener which is deprecated in android 2.3.3 onwards. When you create SensorEventListener you need to implement 2 functions one is onSensorChanged which is used to detect change in the sensors values and the other is called when accuracy of sensor has changed, this is received by the system and you cannot set anything like high accuracy etc.
Now inside the onSensorChanged function get the values of acceleration across x, y and z axis from the sensorevent as shown below.
xaxis=event.values[0];                                 
yaxis=event.values[1];                                 
zaxis=event.values[2];
Now that we have values lets calculate the acceleration as √x^2+y^2+Z^2.
accel=(float) Math.sqrt((double) ((xaxis*xaxis)+(yaxis*yaxis)+(yaxis*yaxis)));
Since we want the value to be displayed only if it is shaked beyond a point we will use if condition for this. In this case we will make 2 as the threshold value.
if(accel >=2){
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText("The Device was shaked and the acceleration was "+accel);
                                                }

So the SensorEventListener will look like as shown below
private final SensorEventListener listner=new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
xaxis=event.values[0];
yaxis=event.values[1];
zaxis=event.values[2];
accel=(float) Math.sqrt((double) ((xaxis*xaxis)+(yaxis*yaxis)+(yaxis*yaxis)));
if(accel >=2){
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText("The Device was shaked and the acceleration was "+accel);
}                                                                                             
                                }                                                             
                };
Now create a sensor manager and register the accelerometer sensor to it in the OnCreate function as shown below.
sensorMgr=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorMgr.registerListener(listner, sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
In registerListener function, you will have to set the SensorEventListener which you have created above. Then set the sensorManager to Accelerometer.  After this you will have to set the rate at which the sensor data are delivered here we can use for game.
Well you might think that we are done at this part, but its not. The sensors eat up lot of resource in the phone so it’s a good practice that we unregister the listener when it’s paused or stopped and started on resumption as shown below.
 @Override
    protected void onResume(){
super.onResume();
sensorMgr.registerListener(listner, sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
    }

@Override
public void onStop(){
sensorMgr.unregisterListener(listner);
super.onStop();
    }
   
@Override
protected void onPause(){
sensorMgr.unregisterListener(listner);
super.onPause();  }
The code will look the snapshot given below.



Now run the app on your phone and shake it, once you shuffle it the text box should change as shown in the screen shot given below.

The above screen shot is taken from a mobile.

Well this is just a simple application and we have just skimmed the surface. I will post more about various sensors in the future : ).

Saturday, December 3, 2011

Photo Gallery


Well I wanted to try out gallery in android and finally I got time and little idea to do it. In this post I have created a gallery which will display 3 images and you can scroll through it.
Create a new project and open res folder and add images which want to display in the app into this folder. Once you are done open the main.xml file and drag the gallery control onto the screen area. Then you need to create resource called styleable which will be applied to each item of the gallery.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="GalleryTheme">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>

Then create a new class where you will define the images and bind to the gallery. We will extend BaseAdapter since we need adapter to hold all the images. Now create an array which has the names of the all the images which need to be displayed as shown below.
Integer images[]={R.drawable.ferrari,R.drawable.manutd,R.drawable.rcb};
Then create a constructor which takes the context into consideration. Then define the style for the images as shown below.

public MyImageGallery(Context ctx){
context=ctx;
TypedArray ta = ctx.obtainStyledAttributes(R.styleable.GalleryTheme);
galleryItem=ta.getResourceId(galleryItem, R.styleable.GalleryTheme_android_galleryItemBackground);
ta.recycle();
}
When you extend the BaseAdapter the eclipse will give u warning saying you need to implement 4 methods
1) getCount() – to get the number of items in the array.
public int getCount() {
return images.length;
                                          }
2) getItem(int pos) – to get the particular item at the position as specified.
                                @Override
                                public Object getItem(int pos) {
                                                                                return pos;
                                }
3) getItemId(int pos)  - to obtain the Id of the item at the position specified.
                                public long getItemId(int pos) {
                                                return pos;
                                }
4) getView() – where you define the properties related to the image.
@Override
                public View getView(int arg0, View view, ViewGroup vg) {
                                ImageView iv=new ImageView(context);
                                iv.setImageResource(images[arg0]);
                                iv.setLayoutParams(new Gallery.LayoutParams(500, 500));
                                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                                iv.setBackgroundResource(galleryItem);
                                return iv;
                }
The final code will look as shown in the screenshot given below.



Now that we are done creating the adapter for the images, go back to the main java file and create a new Gallery and start the above class which will define all the images as shown in the code below
Gallery gly=(Gallery) findViewById(R.id.gallery1);
gly.setAdapter(new MyImageGallery(this));

The main java file will look as shown below.




Now run the project and the result is as shown below when you scroll through the gallery.





Friday, December 2, 2011

Sliding Drawer with simple Checkboxes


In this post I have created a simple sliding drawer and have placed three checkboxes in it. A sliding drawer is generally used to hide contents and only show it when the user wishes to see them.  Checkboxes are used when you want to select more than one checkbox at a time.

First create a new project and open main.xml file under resà layout. Add a textbox to the top of the layout. Add sliding drawer into the layout, you can see it comes with a default button called Handle, rename this to ‘Click to Open the slider’. Then add 3 check boxes into the sliding drawer. Finally the layout will look like the image shown below.



Now open the java file under src folder. You can see there is a default code already available to you. Now create a sliding drawer component and bind it to the resource as defined by you in the xml file.
SlidingDrawer sh=(SlidingDrawer) findViewById(R.id.slidingDrawer1);
Similarly bind the button and all the check boxes in the layout as shown below.

final CheckBox Messi, Ronaldo,Rooney;
Messi=(CheckBox) findViewById(R.id.checkBox1);
Rooney=(CheckBox) findViewById(R.id.checkBox2);
Ronaldo=(CheckBox) findViewById(R.id.checkBox3);
final Button insideslider=(Button) findViewById(R.id.button1);
final TextView tv=(TextView) findViewById(R.id.textView1);       

Now we need to define action for the sliding drawer when it opens and closes. So when the sliding drawer is opened it has all the checkboxes and the button, so we need to define action when the user ticks the checkboxes and clicks on the ‘Done’ button.  To check if the checkbox is selected or not use the ‘isChecked()’ function. Also we can modify the text of the sliding drawer button and change it ‘Click to Close the Slider’. The code shown below shows the same.

sh.setOnDrawerOpenListener(new OnDrawerOpenListener() {
               
               
                                @Override
                                public void onDrawerOpened() {
                                                button.setText("Click To Close Silder");
                                                insideslider.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                                String Value="You Selected";
                                                                                if(Messi.isChecked()){
                                                                                                 Value+=" Messi ";
                                                                                }
                                                                                if(Rooney.isChecked()){
                                                                                                Value+=" Rooney ";
                                                                                }
                                                                                if(Ronaldo.isChecked()){
                                                                                                Value+=" Ronaldo ";
                                                                                }
                                                                                tv.setText(Value);                          
                                                                }
                                                });
                                }
                                });

Now that we have defined the function when the sliding drawer is opened, we can define the function when the sliding drawer is closed. Here I have changed the text on the sliding drawer button to ‘Click to Open the Sliding Drawer’ button. The code below shows the same.
sh.setOnDrawerCloseListener(new OnDrawerCloseListener() {
                @Override
                public void onDrawerClosed() {
                                button.setText("Click To Open Silder");
                }
  });



Now run the application and the output will be as shown in the screenshot shown below.



Click on the button and you can see the checkboxes and also observe that the text of the button has changed, select on any one of them or all of them and click on ‘Done’ button.  You can see all the checkboxes which you selected appear on in the textbox.



Hope you were able to create the same.