Learning Kivy: Animate widgets

Hello everyone!

The Kivy framework provides the kivy.animation module to animate widgets. For any animation, we must specify certain values that represent the position of the animated object.

To use Animation in Kivy one needs to follow two simple steps namely:

1. Setup an Animation object
2. Use the Animation object on a Widget

There are two kinds of Animation that can be applied:

1. Sequential Animation

As the name suggests, it is used to join animations sequentially using the ‘+’ operator.

Example from Kivy docs:

anim = Animation(x=50) + Animation(size=(80, 80), duration=2.)
anim.start(widget)

The above example will animate to x=50 over 1 second, then animate size to (80, 80) over the next two seconds.

2. Parallel Animation

It is used join animations in parallel. It uses the ‘&’ operator.

Example from Kivy docs:

anim = Animation(pos=(80, 10))
anim &= Animation(size=(800, 800), duration=2.)
anim.start(widget)

The above example will animate position to (80, 10) over 1 second, while in parallel animating the first half of size=(800, 800).

Along with animations one can also use various Animation Transition properties to create custom animations for widgets. One can use built-in or custom transition functions using transition (or t= shortcut).

For example using the β€˜in_quad’ transition as follows:

anim = Animation(x=50, size=(80, 80), t='in_quad')
anim.start(widget)

Here is a sample program to demonstrate the Animation module in Kivy:


import kivy
kivy.require('1.4.0')

from kivy.app import App
from kivy.uix.button import Button
from kivy.animation import Animation
from kivy.uix.widget import Widget

class MyAnimApp(App):

        def build(self):
            parent= Widget()
            button= Button(text='Animated', font_size=14)
            button.bind(on_press=self.on_button_press)
            parent.add_widget(button)
            return parent
          
        def on_button_press(self,instance):
            anim = Animation(x=50, size=(50, 50), t='in_out_bounce')
            #apply sequential animation
            anim += Animation(pos=(200,70),t='in_out_back')
            #apply parallel animation
            anim &= Animation(size=(100,50))
            anim.start(instance)
                        

if __name__== '__main__':
       MyAnimApp().run()

You can write the above code using the Python IDLE and run it as:

kivy yourfilename.py

Tutorial #11: Using TextWatcher in Android

Hello everyone!

Today I will be showing you how to implement the TextWatcher interface in EditText for Android.

To begin with, I will list down three simple methods that need to be overriden each time you implement the TextWatcher interface.

1. beforeTextChanged()

This method is used when the characters are going to be replaced with some new text. In this case, the text is uneditable.

2. onTextChanged()

This method is used when the changes have taken place and the characters have been replaced . In this case too, the text is uneditable.

3. afterTextChanged()

This method is similar to the above two except that the text is now editable.

So in short a TextWatcher is used to keep a watch on EditText while entering data into it.

Now let’s proceed with our tutorial!

Step 1: Create a new Android project named AndroidTextWatcherExample with package name com.example and target platform Android 2.3.3

Step 2: Use the default MainActivity class and start writing the code!

First, implement the TextWatcher interface as:

public class MainActivity extends Activity implements TextWatcher { }

Step 3: Override the three methods as discussed above

   @Override
	public void afterTextChanged(Editable arg0) 
	{
		// TODO Auto-generated method stub
    	
	}
	
    @Override
	public void beforeTextChanged(CharSequence s, int start, int count,int after) 
	{
		// TODO Auto-generated method stub	
	}
	
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) 
	{
		// TODO Auto-generated method stub
				
	}

Step 4: Now for this tutorial I would be implementing a Palindrome String checker to demonstrate the working of TextWatcher. So I add my code to the afterTextChanged method.

 @Override
	public void afterTextChanged(Editable arg0) 
	{
		// TODO Auto-generated method stub
    	 String findpalindrome=et.getText().toString();
		 String reverse="";
		 int length=findpalindrome.length();
		 
		 for (int i = length - 1 ; i >= 0 ; i-- )
			 reverse = reverse + findpalindrome.charAt(i);
		 
		 if(reverse.equalsIgnoreCase(findpalindrome) && length>0)
			 setTitle("String is a palindrome");
		 else
			 setTitle("String is not a palindrome");
				
	}

The complete code is as follows:

package com.example;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.app.Activity;

public class MainActivity extends Activity implements TextWatcher
  {
    
    private EditText et;
     
    @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et=(EditText)findViewById(R.id.edittext1);
        et.addTextChangedListener(this);
     } //end onCreate
	
    @Override
	public void afterTextChanged(Editable arg0) 
	{
		// TODO Auto-generated method stub
    	 String findpalindrome=et.getText().toString();
		 String reverse="";
		 int length=findpalindrome.length();
		 
		 for (int i = length - 1 ; i >= 0 ; i-- )
			 reverse = reverse + findpalindrome.charAt(i);
		 
		 if(reverse.equalsIgnoreCase(findpalindrome) && length>0)
			 setTitle("String is a palindrome");
		 else
			 setTitle("String is not a palindrome");
				
	}
	
    @Override
	public void beforeTextChanged(CharSequence s, int start, int count,int after) 
	{
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) 
	{
		// TODO Auto-generated method stub
					
	}
	   
}

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" >
 
    <EditText 
    android:layout_width="250px" 
    android:layout_height="wrap_content"
    android:textSize="18sp" 
    android:id="@+id/edittext1"> 
    </EditText>

</RelativeLayout>

Here is what the result looks like

TextWatcher in Android – Snapshot 1

TextWatcher in Android – Snapshot 2

For more information please refer: Android TextWatcher

Source code for this tutorial can be found over here

Augmented Reality in Android

Hello!

The concept of Augmented Reality is not new. It has been around for many years now and it’s popularity continues to rise as developers use it for building rich interactive applications.

You may wonder what’s so special about Augmented Reality that people write about it, share their experiences and sometimes even upload videos on Youtube. The answer is pretty simple. You come to know the power of Augmented Reality the moment you start using it.

Today, if one does a quick Google search on Augmented Reality, one would get a list of well known softwares, products, open source projects related to Augmented Reality. The thing that caught my attention on doing the same back then was the very existence of Augmented Reality for mobile platforms including Android, iOS. My first encounter with Augmented Reality in Android was three months back when a friend of mine shared an idea that we took up and began exploring the AR world!

As I mentioned before, there are quite a lot of AR products, open source AR projects out there that will help you build your first AR application. I will list a few of them and then talk about one in detail.

1)Qualcomm Vuforia is a popular Augmented Reality platform that helps recognize 2D and 3D visual targets and supports iOS, Android and Unity 3D.

2)Metaio, provides developers with their own SDK to build quality AR applications.

3)Junaio is a well known Augmented Reality browser.

4)AndAR is an open source Android Augmented Reality project that I will be talking about in this post.

AndAR – Augmented Reality for Android

I have been using AndAR for some time now. It’s a project that helps you display wavefront object 3D models on Augmented Reality markers. You can design your own models and your own markers. To start using the AndAR framework you need to have a version of the Eclipse IDE installed along with the Android SDK.

Important: I strongly recommend you read the Legal Information about the AndAR project before you proceed any further.

Step 1: Get the read-only working copy of the AndAR project from over here. You can do a svn checkout by downloading any SVN client from here

Step 2: After you have downloaded the read-only source you will see three folders namely:

1)AndAR (Android project displaying a cube)
2)AndARModelViewer (Android project displaying 3D models on markers)
3)AndARPong (Android project based on the classic Pong game).

Step 3: Import all these three projects in your Eclipse workspace. Make sure there are no errors. At this point, you can always try running any of these projects by following the precise and simple instructions mentioned on the AndAR Wiki Page. But then you would be viewing the built in 3D models. It’s always better to create your own model to really understand how the project works!

Step 4: Creating a new model

To create a new wavefront object 3D model you need a modelling software like Blender or 3ds Max. There are many tutorials on the Internet that will help you create a 3D model in Blender. At present, AndAR has some restrictions to the models as follows:

1) Every face must have normals specified
2) The object must be triangulated, this means exactly 3 vertices per face.
3) Basic materials and textures are supported.

Make sure you export your model by taking the above factors into consideration.

Step 5: Add the model to the AndARModelViewer project.

In order to add your own 3D model, you need to copy the .mtl, .obj files (generated when you export your model from Blender) in the assets/models folder of the AndARModelViewer project. You can add an image (.png or .jpg) to represent your model inside the same folder.

Step 6: Print out the marker

Download and print the marker upon which your model will be projected. Alternatively you can create your own markers by following this link.

Step 7: Eliminate all errors. Clean the project and then finally its done! Run your first AR application using AndAR! πŸ™‚

Here are some snapshots I took of a simple model displayed using AndAR:

Augmented Reality using AndAR – Snapshot 1

Augmented Reality Android using AndAR- Snapshot 2

Model Courtesy: Ajit Pillai

For more information visit the AndAR website. You can also download the AndAR application from Google Play.

If you have developed applications using AndAR or wish to share anything on Augmented Reality please feel free to comment πŸ™‚

Learning Kivy: Video Player and Scatter widgets

Hello everyone!

Today I would like to share with you something new that I learnt recently while working on the Kivy library. It includes a brief introduction about the Widget class in Kivy along with two sample programs that demonstrate complex UX widgets and behaviors widgets respectively.

Widget class is the base class required to create a Widget. We can add, position and clear widgets using the methods provided by the Widget API. In simpler terms, a widget is defined as an element of a graphical user interface.

Kivy includes various widgets such as:

1) Label, Button, CheckBox, Image, Progress Bar etc (called UX widgets)

2) Scatter, Stencil View (called Behaviors widgets)

3) Drop-Down List, FileChooser, Popup, Spinner, TabbedPanel, Video player etc (called Complex UX widgets)

4) Screen Manager widget

5) Grid Layout, Box Layout, Anchor Layout etc (called Layout widgets)

In this post I will talk about the Video Player and Scatter widgets.

Video Player widget:

As defined in the Kivy docs, “a Video Player widget can be used to play video and let the user control the play/pause, volume and seek. The widget cannot be customized much, because of the complex assembly of numerous base widgets”.

Here is a sample program that demonstrates the working of the Video Player widget:

Step 1: I will be using the softboy.avi video included in the Kivy samples for this purpose. You can also download a short video (.avi , .mkv) and use it. In order to display text at a specific time and duration of the video we can use annotations. An annotation file has a .jsa extension. You can find more information on annotations over here.

Step 2: You can open any editor like Notepad++ to write the code. I will be using the Python IDLE for now.

import kivy
kivy.require('1.4.0')

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.videoplayer import VideoPlayer
    
parent= Widget()
button= Button()
        
class MyApp(App):
    def build(self):
         button = Button(text='Play video', font_size=14)
         button.bind(on_press=on_button_press)  
         parent.add_widget(button) #add button 
         return parent
              
def on_button_press(self):
        video= VideoPlayer(source='softboy.avi', state='play')
        parent.add_widget(video) #add videoplayer
        return parent
    
if __name__ == '__main__':
    MyApp().run()

Step 3: Save this script as videoplayerdemo.py

Note: Make sure you have the video file (.avi), annotation file (.jsa) if any and your Python file (.py) in the same folder. Run the application from the command prompt by typing:

kivy videoplayerdemo.py

Click on the button “Play video” to start the video. Double click on the video to increase it’s size.

VideoPlayer widget snapshot 1

VideoPlayer widget snapshot 2

Scatter widget

The Scatter is a very simple widget to understand. It is basically used to build interactive widgets that can be translated, rotated and scaled with two or more fingers on a multitouch system. It acts as a container and is combined with other widgets.

Create a new Python script named scatterdemo.py and write the following code:

import kivy
kivy.require('1.4.0')

from kivy.app import App
from kivy.uix.scatter import Scatter
from kivy.uix.image import Image    

class MyApp(App):
    def build(self):
         scatter= Scatter()
         # store kivy.jpg image in same folder as the python script
         image= Image(source='kivy.jpg')
         scatter.add_widget(image) #combine image widget with scatter
         return scatter
           
if __name__ == '__main__':
    MyApp().run()

Run the application as done before and you will see an image of the Kivy logo. You can try dragging, rotating the image using the mouse.

Drag image

Rotate image

So that completes a quick look at some of the widgets in Kivy. There is still lots to learn and many more things to do! Have a great day! πŸ™‚

Tutorial #10: Customizing buttons in Android

Hey everyone!

Today’s tutorial will tell you how you should customize and create your own buttons in Android. The Button class represents a push-button widget that users can click or press in order to perform an action on the push-button.

Now, every button is styled using the system’s default button background which differs from device to device and from one version of the platform to another. In order to customize a button we need to replace the button’s background image with something known as a State List Drawable

What exactly is a State List Drawable? This is answered very well in the Android developer guide as follows:

“A state list drawable is a drawable resource defined in XML that changes its image based on the current state of the button. Once you’ve defined a state list drawable in XML, you can apply it to your Button with the android:background attribute.”

So keeping in mind these concepts let’s proceed with our tutorial!

Step 1: Create a new Android project named AndroidCustomizeButtons with package name com.example, Activity name MainActivity and with target platform as Android 2.3.3

Step 2: Declare three buttons inside MainActivity

package com.example;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;

public class MainActivity extends Activity 
{	
    Button b1,b2,b3;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        b1=(Button)findViewById(R.id.button1); //normal button
        b2=(Button)findViewById(R.id.button2); //customized button
        b3=(Button)findViewById(R.id.button3); //customized button with image
        
       
    }
    
}

As you can see from the above code we have added 3 buttons to our class. The 1st button will be the normal system default button for Android 2.3.3 platform and the other two buttons are customized.

Step 3: Create a new XML file named button_customize.xml which contains the selector.

button_customize.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- default -->
    <item android:state_pressed="false" android:state_focused="false">
        <shape >
            <solid
                android:color="#444444" />
            <stroke 
                android:width="1dp"
                android:color="#444444" />
            <corners
               	android:bottomLeftRadius="8dip"
                android:topRightRadius="8dip"
                android:topLeftRadius="8dip"
                android:bottomRightRadius="8dip"/>
            <padding
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
  
    <!-- button focused -->
    <item android:state_pressed="false" android:state_focused="true">
        <shape >
            <solid
                android:color="#00ffff" />
            <stroke 
                android:width="1dp"
                android:color="#00ffff" />
            <corners
               	android:bottomLeftRadius="8dip"
                android:topRightRadius="8dip"
                android:topLeftRadius="8dip"
                android:bottomRightRadius="8dip"/>
            <padding
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
  
   <!-- button pressed -->
    <item android:state_pressed="true" android:state_focused="false">
        <shape >
            <solid
                android:color="#00ff00" />
            <stroke 
                android:width="1dp"
                android:color="#00ff00" />
            <corners
               	android:bottomLeftRadius="12dip"
                android:topRightRadius="12dip"
                android:topLeftRadius="12dip"
                android:bottomRightRadius="12dip"/>
            <padding
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"
                android:bottom="10dp" />
        </shape>
    </item> 
</selector>

Here it is important to note that each item uses various attributes to describe the state in which the object is and what should be used as the graphic for the drawable. We have used a few attributes in our XML such as android:state_pressed and android:state_focused.

There are many more attributes that you can use depending upon your needs. Here, we have customized our second button.

Step 4: Add an image to a button. In this case I will be using another attribute android:drawableTop to place the image above the text inside the button.

Such a button will be defined in the main XML file as follows:

<Button android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:drawableTop="@drawable/ic_launcher"
            android:text="Customized Button with Image"
            android:layout_below="@+id/button2"
            android:padding="5dip"
            android:layout_gravity="center"
           />       

Step 5: activity_main.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
              
    <Button android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Normal Button"
            android:padding="5dip"
            android:layout_gravity="center"
            />
	
	 <Button android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Customized Button"
            android:layout_below="@+id/button1"
            android:background="@drawable/button_customize"
            android:padding="5dip"
            android:layout_gravity="center"
            />
            
     <Button android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:drawableTop="@drawable/ic_launcher"
            android:text="Customized Button with Image"
            android:layout_below="@+id/button2"
            android:padding="5dip"
            android:layout_gravity="center"
            />       
</RelativeLayout>

Make sure you have the ic_launcher.png image inside your drawable folder.There is no change in the AndroidManifest.xml. Try running the project and you should see a screen as follows:

default state of button

button when pressed

Note: Adding an image to a button is usually not done in the way I have explained. It’s best to use an ImageButton. I will try and talk about it in my further tutorials. Till then enjoy! πŸ™‚

Source code for this tutorial can be found over here.

Getting started with OpenCV for Android

Hello everyone!

Today I would like to talk about a popular computer vision library called OpenCV (Open Source Computer Vision library) and how one should go about installing it for Android to start developing applications. The OpenCV library includes many algorithms that help to track camera movements, identify static and moving objects and also extract 3D models of objects. In addition it also helps in face recognition and focuses mainly on creating real time applications. At present it has C, C++, Python and Java interfaces and supports Windows, Linux, Android and the Mac OS platforms.

To start using OpenCV, first you need to download the latest version of OpenCV for the desired platform from here. In this post I would be focussing on installing OpenCV for Android.

Step 1: Once you have downloaded the .zip file, extract it in a folder. I extracted mine to C:\android-opencv\OpenCV-2.4.2-android-sdk. Once you have extracted the file you should get apk, samples, doc and the sdk folders as shown below.

OpenCV folder contents

Step 2: If you have the Android SDK, NDK and the ADT plugin installed and configured in Eclipse you can skip the following steps and proceed to step 6.

Step 3: In case you don’t have the Android SDK setup, you can do so by installing the Android SDK from over here. You can follow a detailed tutorial for this step. Make sure that you tick the Android NDK development tools while you are installing the ADT plugin for Eclipse.

Step 4: You need to install the Android NDK as well if you are planning to reuse your C++ code. You can download the current version from over here.

Step 5: Once all the installation is complete, open up Eclipse. Go to Window–>Preferences–>Android. Add the SDK and NDK locations properly and make sure you have no errors.

Step 6: In Eclipse, go to File–>Import–>Existing Android projects into workspace. Give the path to your samples folder inside the OpenCV installation directory. Import all the projects selected into your workspace.

Step 7: At this point, you may see that there are errors present. To remove these errors, again go to File–>Import–>Existing Android projects into workspace, but this time give the path to your sdk\java folder instead. Now right click on any project, go to Properties–>Android. Add the reference to your sdk\java folder. Click on Apply and then Ok and you will see that the errors have disappeared for the selected project. Repeat this for other projects also.

Add reference to sdk\java library

Connect your phone via USB and make sure it is connected to the Internet (just for now). Finally, now run any sample as an Android application. For the first time, OpenCV will ask you to install the the OpenCV Manager from the Google Play store. Install it, restart your application and now your OpenCV ready! πŸ™‚

Here are some screenshots I took while running the preloaded samples provided by OpenCV:

OpenCV: Android Camera

OpenCV: Canny Edge Detector

OpenCV: Gray scale

OpenCV: RGBA along with other options

Do read about: Android release notes, user guide and tutorials.

Tutorial #9: Working with Images in Android

Hello everyone!

In today’s tutorial we will talk about using Images in Android. To display any Image in Android we need to use the ImageView class. This class can load images from various sources and can be used with any layout manager in Android. Android supports 3 common image formats namely PNG, JPG, GIF, along with 9 patch PNG images and are stored in the directory res/layout/drawable. It is important to note that all image file names should be lowercase and should only contain letters, numbers, and underscores.

In this tutorial we would be learning how to display,download, upload, save and crop an Image in Android.

Let’s start coding then!

Step 1: Create a new Android project named WorkingWithImagesAndroid with package name com.example and Activity name MainImageActivity.

Step 2: Writing the code to display the Image. I have added two sample Images namely sample1.jpg and sample2.png to my drawable folder. I will display one of them using the following code,

package com.example;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainImageActivity extends Activity 
{
   private ImageView iv;  
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.imageactivity_main);
    
        //get the ImageView
        iv=(ImageView)findViewById(R.id.myimage);
        
        //display the image
        iv.setBackgroundDrawable(getResources().getDrawable(R.drawable.sample1));
        
        iv.setOnClickListener(new OnClickListener() 
        {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
                   //move to next Activity that will do the downloading task
				Intent i= new Intent(MainImageActivity.this,DownloadAndSaveImage.class);
				startActivity(i);
			}
		});
        
    }
} //end class

imageactivity_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">

    <TextView
        android:id="@+id/mytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_gravity="center_vertical"
        android:text="Click on Image to move to next screen"
        tools:context=".MainImageActivity" />
        
    <ImageView
         android:id="@+id/myimage"
 	     android:scaleType="center"
 	     android:layout_below="@+id/mytext"
 	     android:layout_width="fill_parent"
 	     android:layout_height="fill_parent"/>    

</RelativeLayout>

display image in ImageView

Moving on, create a new class named DownloadAndSaveImage inside the same package com.example

Step 3: Downloading an Image from the Internet and saving it in the SD card. When you click on the Image that is displayed using the code in the 2nd step, the download activity will start.

Now here it is important to note that since we would be downloading an image from the web, it is advised to carry out the operation in the background thread. Hence I would be using an AsyncTask for the same.

public class DownloadAndSaveImage extends Activity
{
         
	 private Button b1; //button to save image
	 private String url;
	 
   //path to the SD card, where we will save our image
	 private String PATH = Environment.getExternalStorageDirectory().toString();
	 	  
	 @Override
	    public void onCreate(Bundle savedInstanceState)
	    {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.downloadactivity);
	        
	        b1=(Button)findViewById(R.id.button2);		       
	        b1.setClickable(false);
	        new DownloadAndSaveTask().execute("https://karanbalkar.com/wp-content/uploads/2012/09/jellybean2.jpg");         
	    }
	 
	 
	    private class DownloadAndSaveTask extends AsyncTask<String, Void, Bitmap> 
	     {	   
		    private final ProgressDialog d=new ProgressDialog(DownloadAndSaveImage.this);   
		    @Override
		    protected void onPreExecute() 
		    {
		      super.onPreExecute();
		      d.setMessage("Downloading image...Please wait!!");
		      d.setCancelable(false);
		      d.show();
		      
		   }

		   @Override
		   protected Bitmap doInBackground(String... params) 
		   {
		       url = params[0];  
		     	 try 
		    	 	{            
		    		 return BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
		    	 	} 
		     	 catch (MalformedURLException e) 
		     	 	{
		    		 e.printStackTrace();
		    		 return null;
		    		} 
		     	 catch (IOException e) 
		     	    {
		    		 e.printStackTrace();
		    		 return null;
		     	    }
		      					     	
	         }
		   
		    @Override
		    protected void onPostExecute(final Bitmap result) 
		     {
		        super.onPostExecute(result); 
		        if(result!=null)
		        {	  			
				d.dismiss();
		        	b1.setClickable(true);
		        	b1.setOnClickListener(new OnClickListener() 
		        	{
			           @Override
		                   public void onClick(View v)
		        	       {
					           // TODO Auto-generated method stub
						     OutputStream outStream = null;
					   	   //sampleimage4 is the name given to the image saved. You can give any name
						     File file = new File(PATH, "sampleimage4.jpg");
                                try 
				                  {
					             outStream = new FileOutputStream(file);
					             //saving as a JPEG image
						         result.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
						         outStream.flush();
						         outStream.close();   
						         Toast.makeText(DownloadAndSaveImage.this, "Saved", Toast.LENGTH_LONG).show();
					               }    
                                 catch(FileNotFoundException e)
                                  {
					             //TODO Auto-generated catch block
					              e.printStackTrace();
				                  }  	       
                                 catch(IOException e)
			                     {
						        //TODO Auto-generated catch block
					             e.printStackTrace();
					               }	
				
	                           }			
		                 });			
                    }	     
             } //end postexecute method 
     } //end asynctask class		
} //end main class

downloadactivity.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">

    <TextView
        android:id="@+id/mytext2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="DownloadAndSaveImage"
        tools:context=".DownloadAndSaveImage" />
        
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/mytext2"
        android:text="Save Image to Sd card" />
            
     <Button
         android:id="@+id/button3"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_below="@+id/button2"
         android:text="Upload Image" />
            
      <Button
         android:id="@+id/crop"
         android:layout_below="@+id/button3"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="Crop Image"/>	 
        
      <ImageView
 	    android:id="@+id/uploadimage"
 	    android:scaleType="center"
 	    android:layout_below="@+id/button3"
 	    android:layout_width="match_parent"
 	    android:layout_height="fill_parent"/>  
 	    
</RelativeLayout>

Here I would pause and like to tell you that it is not mandatory to save an image in the SD card. You can use the built-in SQL lite DB as well. Refer this link for more information.

If your download is successful and your image is saved properly you should get a Toast message confirming the same.

toast message confirming image is saved

Step 4: Upload and crop the image. To upload and crop the image we would be adding two buttons to do the respective task to our existing DownloadAndSaveImage class. Also we need an ImageView to show our uploaded image.

      private Button upload,crop;
      private ImageView myImage;
      private Bitmap myBitmap;

       //upload an image from sdcard
	upload.setOnClickListener(new OnClickListener() 
	      {
		@Override
		public void onClick(View v) 
		   {
			// TODO Auto-generated method stub		
			File imgFile = new  File(PATH,"sampleimage4.jpg");
                        //check if image exists
	        if(imgFile.exists())
	           {
                          //get image
			   myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
			   myImage = (ImageView) findViewById(R.id.uploadimage);
			   myImage.setImageBitmap(myBitmap); //add image to ImageView
	           }			
		   
            } 
      });
	        
	        
	 //crop the image uploaded
	  crop.setOnClickListener(new OnClickListener() 
	    {	
		   @Override
		   public void onClick(View v) 
				{
					// TODO Auto-generated method stub
					//remove 30 pixels 
					 Bitmap croppedBmp = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight()-30);
					 myImage.setImageBitmap(croppedBmp);

				}
	   });

Step 5: AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/> 
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name=".MainImageActivity"
            android:label="@string/title_activity_main_image" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
    <activity android:name="com.example.DownloadAndSaveImage" android:label="DownloadAndSaveImage">
    </activity>   
   </application>
</manifest>

upload image

crop image

Topics for reference from Android developer guide: Bitmap , File , InputStream

This completes the tutorial. You can download the entire source code for this tutorial from here.

Tutorial #8: Creating an animation using Processing

Hello everyone,

In one of my earlier posts I had talked about Processing and the features it offers to developers using two sample programs. At the end I had promised to bring out certain more features. This post of mine tells you how to create your own animation using Processing!

For creating an animation we would require a model. I will be using custom wavefront object (.obj) models. These models can be created using any of the popular 3D modelling software out there, say Blender or 3ds Max. For this tutorial I will be using a Superman model made by the developer of AndAR which happens to be a popular augmented reality project for Android.

The Superman model can be downloaded from here. The material file (.mtl) for the same can be downloaded from over here.

Let’s proceed with the tutorial now!

First start the Processing application. By default a Sketch will be created and you can begin writing your code in the Editor. Make sure you have Java mode selected (seen at the right hand side of the toolbar).

Step 1: Add the model, background image and a float variable

PShape superman;
PImage bg;
float ry;

Step 2: Setup your screen


public void setup() 
{
  size(800, 600, P3D);
  frameRate(30);
  bg = loadImage("background.jpg");
  superman = loadShape("superman3.obj");
 
}

Note: The files background.jpg ; .obj file and the .mtl file of your model should be present inside the data folder of your project.

Step 3: Once the screen is setup, add the draw method

public void draw() 
{
  
   background(bg);  //add the background image
   lights();        
   translate(width/2, height/2, -200);  //keep the model at the center of the screen or window
   rotateZ(PI);
   rotateY(ry);
   shape(superman);  //add the model
   ry+=0.2; 
  
   if(mousePressed) 
   {
    scale(2.0);    //increase size of model
    ry=0;
    translate(mouseX,mouseY, -200);
    shape(superman);
   } 
    
}

So that doest it! Here is the entire code:

PShape superman;
PImage bg;
float ry;
  
public void setup() 
{
  size(800, 600, P3D);
  frameRate(30);
  bg = loadImage("background.jpg");
  superman = loadShape("superman3.obj");
 
}

public void draw() 
{
  
   background(bg); 
   lights();  
   translate(width/2, height/2, -200);
   rotateZ(PI);
   rotateY(ry);
   shape(superman);
   ry+=0.2;
   
   if(mousePressed) 
   {
    scale(2.0);
    ry=0;
    translate(mouseX,mouseY, -200);
    shape(superman);
   } 
    
}

Run the application and you should see a rotating Superman model:

Screenshot

Now try pressing and moving your mouse. You should see an enlarged version of the superman model inside the screen. Hence, Processing is a tool that allows you create such animations and even more complex ones. Use your creativity and then there is no stopping you! πŸ™‚

Introducing CodeName One!

Ever since I started developing for the Android platform, I wish I had a tool that could help me run my application on a different platform say, an iOS or a Windows phone.

When I did a quick Google search back then I got to know about Bluestacks which provides a framework to run the Android applications on your Windows PC and recently has come up with an App Player for the Mac OSX announced at Google I/O. Just a couple of weeks back when my friend Ajit told me about a new open source project, I knew for a fact that this could just be the thing I always wanted.

CodeName One is an open source cross platform Java tool that helps you target devices such as IPhone/IPad, Windows Phone, Blackberry and also Android. CodeName One clearly emphasizes the Write Once Run Everywhere principle combined with a SaaS approach allowing developers to use the cloud to build native applications. Moreover, you can use either Netbeans or Eclipse to start developing your apps using CodeName One.

Through this post, I will tell you how to setup CodeName One for Eclipse IDE in Windows and start developing your applications!

Step 1: If you don’t have Eclipse installed, go to the Eclipse Download’s page and download the latest version of Eclipse. I recommend you download the Jave EE Developer edition.

Step 2: Open Eclipse. Click on Help –> Install new software

Step 3: Click on the Add button. Type Codename One for the name and https://codenameone.googlecode.com/svn/trunk/CodenameOne/repo/eclipse/site.xml for the location. Select the entries and click on Next. It should now start installing the necessary files.

Installing CodeName One

Step 4: Restart the Eclipse IDE after the installation is complete.

Once Eclipse has been restarted, go to File –> New –> Project –> CodeName One Project

Creating new CodeName One project

Give the project name as HelloWorld and try running the application. You should see the default emulator. You can now trying changing the Skins and start building your own applications! Cheers! πŸ™‚

Output

Tutorial #7: How to create a CountDownTimer within Dialog in Android

Hey everyone, here is another fun tutorial that explains how to create CountDownTimer inside a Dialog in Android.

Before I proceed with the explanation, you must spend some time reading about CountDownTimer and Dialog given on the Android developer’s page.

Ok, if you are done reading, let’s begin with our demo:

Step 1: Create a new Android project named AndroidDialogWithTimer and package name com.example , change Activity name to DemoActivity and layout to main.xml instead of the default activity_main.xml

Step 2: DemoActivity.java

package com.example;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class DemoActivity extends Activity
{
	View viewLoad;
	Button start,stop;
	Dialog dialog;
	TextView tv; 

	 @Override
	 public void onCreate(Bundle savedInstanceState) 
	 {
		  super.onCreate(savedInstanceState);
		  viewLoad = LayoutInflater.from(DemoActivity.this).inflate(R.layout.main, null); //inflate the view
		  setContentView(viewLoad);
	 	  Button b = (Button) findViewById(R.id.button1);  
	   	  final MyCounter timer = new MyCounter(600000, 1000); 
	 
		  b.setOnClickListener(new OnClickListener() 
		  {
		      public void onClick(View v)
			 {
			        dialog = new Dialog(viewLoad.getContext());
			        View vLoad = LayoutInflater.from(DemoActivity.this).inflate(R.layout.timer, null);		
				    dialog.setContentView(vLoad);
					 
			        tv=(TextView)dialog.findViewById(R.id.tv);
           			start=(Button)dialog.findViewById(R.id.start);
		    	    stop=(Button)dialog.findViewById(R.id.stop);
					 
		            dialog.setTitle("Dialog with CountDownTimer");
		            dialog.setCancelable(false);
		             
		            tv.setText("Countdown begins from : 10 minutes");
		            tv.setTextColor(Color.RED);
		            start.setOnClickListener(new OnClickListener()
		    		      {
		 	                public void onClick(View v) 
		 	                      {
		 	        	  	timer.start();  //will start the timer	 	                		 	                	
		 	                       }
		    		      });
		    		 
		    		 stop.setOnClickListener(new OnClickListener() 
		                      {
		                        public void onClick(View v)
		                              {
		                                 timer.cancel();
		                                 dialog.dismiss();
		                              }
		                      });
		    		 
		            dialog.show();      
                }
        }); 

  } //end oncreate
	 
	 public class MyCounter extends CountDownTimer
	 {
		 
	        public MyCounter(long millisInFuture, long countDownInterval)
	        {
	            super(millisInFuture, countDownInterval);
	        }
	 
	        @Override
	        public void onFinish()
	        {
	            Log.i("Main","Timer Completed");
	            tv.setText("Timer Completed.");
	        }
	 
	        @Override
	        public void onTick(long millisUntilFinished)
	        {
	        	tv.setText("Timer : " + (millisUntilFinished/60000) + " " + "minutes remaining.");
	        }
	     
	 }

} //end class

If you look closely, you will see that I have used LayoutInflater in order to create my view. This is done because in this case we need to set a Custom View to our Dialog. There are various ways to do it and you can try it yourselves.

This blog post explains LayoutInflater very nicely.

Step 3: Layout XML files

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" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Click Me" />
            
    </LinearLayout>
</RelativeLayout>

timer.xml

<?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"
       android:id="@+id/layouttimer">
	
      <Button
       android:id="@+id/start"
	   android:layout_width="wrap_content"
	   android:layout_height="wrap_content"
	   android:layout_gravity="center_horizontal"
	   android:text="Start Timer" >
      </Button>

	<Button
	    android:id="@+id/stop"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_gravity="center_horizontal"
	    android:text="Stop Timer" >
	</Button>
	
	<TextView
	    android:id="@+id/tv"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_gravity="center"
	    android:gravity="center"
	    android:text=""/>
    
</LinearLayout>

On running the entire application, you should get a screen as follows:

CountDownTimer within Dialog in Android

Source code of project can be found over here.