How do you rate this blog

Monday, October 24, 2011

Passing Data between Activities


In the previous post we have learnt how to navigate from one activity to other, in real time scenario you generally need to pass data between activities. In this post we will get to know how to do the same.

Scenario – Have a screen called Main where in you will have to enter your name. When you press the button you will be taken to another screen where in Hello <name> will be displayed.

Logic –
1) Create an activity with a Label having “Enter your Name”, a editable text box in which you can write your name and a button which will make the application to go to another Screen

2) Create an activity which has a label saying you are in Activity 2 ‘In Activity2’, a textview which will prefix ‘Hello’ to what ever you have entered in the textbox of the previous activity. Finally add a button which will end the flow and will return back to the main screen.

So now let us add the code to the logic mentioned above assuming you have created a new project for this, add a new java class in src à <your package name> à <your java class>.
1) Main Activity – 

a) Creation of Layout – Go to res à layout àmain.xml file. Add Linear Layout into the UI, add the Label with the text “Enter your Name”. Drag Editable Text box into the layout and place it below the Label. Below this drag a Button and edit the text to “Say Hello”. So the layout will look like in the snapshot given below.



b) Creation of the activity -Now go to the src à <package you created> à <java file>. In this add the code which will perform the activities when the button is clicked.
In this create a button as shown below
Button act1= (Button) findViewById(R.id.button1);
Then add the functionality which will instruct the app to move to other screen and pass the name to other screen as shown below.
public void onClick(View view) {
Create an intent and point it to the other activity’s class
Intent activity1=new Intent(view.getContext(),subActivity.class);
Since you have to send data of the editable text box to other screen include the code to read it in this listener
EditText ET=(EditText) findViewById(R.id.editText1);
String Name="Hello, "+ET.getText().toString();
Since we need to pass extra data into the sub activity, use the function <intent>.putextra(<keyname>,key) as show below.
activity1.putExtra("Name", Name);
Then start the new activity using the function startActivityForResult(<intent name>,<intent request code>)
startActivityForResult(activity1,1);
The activity will look like the snapshot shown below.




2) Sub Activity –
Now that we have configured the main activity, let us code the subactivity. 

a) subactivity.xml – Create a new xml file called subactivity.xml in res àlayout. Add linear layout to the UI. Add a label which has the text ‘In Activity2’. Add a TextView in which the message “Hello <message from main activity>” will be displayed. Then add a button which will finish the activity and return back to the main screen. The layout will finally look like the snapshot shown below.



b) Creation of the activity – Now go to srcà<your package name>à<your java class> and extend activity so that you can use all properties of an activity here. Create a function onCreate function which will perform the desired activities. In this function set the contentview to the layout which you have just defined as shown below.
setContentView(R.layout.subactivity);
Now you have to write a code which will accept the data from the previous activity.
//getintent is used to get the previous intent
Intent mainAct=getIntent();
//once you get the previous intent, you can access the key which holds the data and use it as shown below.
String VariableName=mainAct.getExtras().getString("Name");
TextView helloText=(TextView) findViewById(R.id.textView3);
helloText.setText(VariableName);

Then create a Button which will finish the activity and take you back to the initial screen using the following code
Intent subAct=new Intent();
setResult(RESULT_OK,subAct);
finish();
The subactivity java file will look as in the snapshot show below.



3) Modification to manifest file – In the manifest file add the new activity with the following code.
<activity android:name=".subActivity"></activity>
The manifest file will look as shown in the snapshot shown below.



Now we are done with the coding part, lets see if it actually works. Right click on the project and run it. The initial screen will be as shown in the picture below.



Enter Android in the textbox and click on the button. It should take you to the other screen where in you will have a text saying ‘Hello, Android’  as shown below. 



Once you click on the button here it should take you back to the initial screen. 

So we have learnt how to pass data between different activities. Well this is a simple one there are many complex scenarios which will be posted later :). Till then Adios!!!!!!!!

Thursday, October 20, 2011

Navigation between Activities


An Activity is nothing but a screen in an app. For example the Gmap application the screen which displayed the map is nothing but an activity. There will be situations where in you need to traverse from one screen to another. In this post we get to know the simplest way to traverse between activities.
Given below are the steps to achieve this -

1) Define the second activity in the android manifest Table.
2) Create 2 Layouts called Default_Activity and Second_Activity with button in each of them, where in you will traverse from Default_Activity screen to Second Activity.
3) Create 2 java classes for each activity where you will define the action to be done on click of button in each activity.

Now that we got the things that need to be done lets look start coding the same
First Create a new Android Project by clicking on the File and traversing to the New option in the menu. In this case you can use normal Android 2.3 instead of Google Android 2.3 since we don’t use any of the google API’s.

1) Defining Second Activity in Android Manifest Table –
Open the Android Manifest Table and add the following code which will define the second activity.
The android Manifest Table will look like below


2) Creating the 2 layouts –
Go to res folder and click on the Layout folder and a new xml file which will be your second activity.
Create the 2 activity using the graphical layout as shown in the images below.

3) Defining Java classes –

a)  Default_Activity class –
Instantiate the Button class as shown below
Button Act1=(Button) findViewById(R.id.button1);
Then write the code to move to the second activity by using the OnClick function wherein  you create an Intent which instructs the application to go to the second activity.
public void onClick(View view) {
Intent def_intent=new Intent(view.getContext(),Second_Activity.class);
startActivityForResult(def_intent,0); }
Finally your Default_Activity class will look like this.



b) Second_Activity –
Create the onCreate function and set the view to Second2activity as shown below
setContentView(R.layout.second2activity);
Create a new Button which will end the app and return to the default activity screen and in the onClick function use the code below
public void onClick(View v) {
//creating a new intent                                                        
Intent sec_intent=new Intent();                                      
//set the result and return to the default_activity Screen
setResult(RESULT_OK,sec_intent);
//End the Activity
finish();
The Second_Activity will look like the screen shot shown below.



Now that we are done with the coding, lets see if it really works as desired. Right Click on the project and say Run as Android Application.
The initial screen will be the one as shown below, click on the ‘Move to other Activity Button’


On clicking the button you should come to screen 2 as shown below. 



If you again click on the button ‘Congrats you have come to the Second Activity’ it should take you back to the Default Activity Screen.

Woohoooooo you have learnt how to create an activity, in the next post I will let you know how to pass parameters / data between activities. Till then Adios!!!!!!

Monday, October 10, 2011

Creation of Overlays in Google Maps

An overlay is nothing but an object which can be drawn over a map. On this overlay we place various overlay items.
                So now that we got to know what an overlay means, lets get on with the app in which we will display the overlay. The logic to add the overlay is given below.
1) Create a class which will extend the ItemizedOverlay class which extends Overlay.
a) So create a new class which extends ItemizedOverlay.  In this class initialize mapOverlays which will hold all the overlay items as shown below.

b) Private ArrayList<OverlayItem> markerOverlay=new ArrayList<OverlayItem>();
Then create a constructor which will initialize the class as shown below.
                public Marker_Class(Drawable defaultMarker) {
                                super(boundCenterBottom(defaultMarker));
                                // TODO Auto-generated constructor stub
                }

c) Next create another constructor which accepts one more parameter called as Context.c) Next create another constructor which accepts one more parameter called as Context.
public Marker_Class(Drawable defaultMarker,Context context) {
                                this(defaultMarker);
                                this.context=context;
                }

d) Override the function CreateItem and include the following code to get the particular item.
return markerOverlay.get(i);

e) To add a functionality, where in on tap of an item you get a screen which shows all the details is given below

                                       OverlayItem item=markerOverlay.get(i);
                                       AlertDialog.Builder dialog=new AlertDialog.Builder(context);
                                       dialog.setTitle(item.getTitle());
                                       dialog.setMessage(item.getSnippet());
                                       dialog.show();
                                        return true;

f) Finally override the function addOverlay,  which will populate your gmap with the items
                                                             markerOverlay.add(overlay);
                                                                this.populate();

The marker class will look as shown in the image below.



2) Now that will have an overlay class, we need to make changes to our MainActivity.

 a) Make variables which will store latitude and longitude information
public static final int longitude=12971600;
public static final int lattitude=77594560;

b) Create a list of overlays and Drawable variable as show in the code below and instantiate the overlay class which have created above.
        List<Overlay> mapOverlay=mapV.getOverlays();
        Drawable drawable=this.getResources().getDrawable(R.drawable.icon);
        Marker_Class MC=new Marker_Class(drawable,this);

c) Then create a geo point on which the marker will be shown with the title name and text as shown below.
       GeoPoint point=new GeoPoint(longitude, lattitude);
        OverlayItem overlayItem=new OverlayItem(point,"hello I am in Bangalore","Its an awesome place");
        MC.addOverlay(overlayItem);
        mapOverlay.add(MC);


The main mapactivity class will look as shown in the image below.


Then run the project and the final result is as shown below.

Tadaaaaaaaa it workeddddddddd :) ! Hope you all got it and please let me know if the post was helpful.

Wednesday, October 5, 2011

Grey Tiles in Android Gmaps


Well I was trying out my first map app on android when I encountered a problem where in the map was not at all displayed, instead only grey tiles was being displayed. Well this can be really annoying as you really don’t know what has gone wrong even if you have written the code properly and it gets even worse if you are newbie like me. The following are the steps I used to solve this problem.

1) Check if the internet connection is working properly in your emulator, this can be done if you open the default maps application app in your emulator or doing a google search in the emulator. If your internet is not working properly then the google maps will not load, so you have to enable internet on your emulator using the following command
   "Emulator.exe  -avd <avd name> –dns-server http:\\<ipaddress>:8060  "
More options for emulator are mentioned in the following link - Android Emulator*

2) In androidmanifest.xml make sure you have used the following 
<uses-permission android:name="android.permission.INTERNET" />
because this tag provides the app rights to access internet on your  mobile.

3) If you have your own private key then see if you have a proper API key using your private key, if you want to generate a new private key use the following command
   keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000.
 If you are using eclipse you can create a new key using the create new option in Android Tools -> Sign application option.

4) If debug.keystore has expired, generally the validity of this will be 1 year. So if this debug.keystore has expired then delete this file located in the <home directory on your machine>/.android for windows. Eclipse will replace this new debug.keystore application. Now generate new MD5 key and use that to generate the new api key and use the new key in main.xml file.
Hopefully this post would have helped you fix the grey tile problem in your app.

Tuesday, October 4, 2011

Creating a Simple Google Map Application - Part 2

Logic of Developing a Gmap Application –
1) First we need to include the google libraries since it is not part of Android libraries.
2) We need to enable internet access to this application inorder to retrieve the google map.
3) Create a View file which will create the map view using your API key.
4) Then create a java code which will extend the Mapactvity.
As you see the logic is simple :).

Now create a new project in Eclipse by clicking on New option in the File and click on Others.
Once you do the above, you can see a selection called Android, expand the selection and click on Android Project as shown below


After the above step click on the Next, then provide the Project Name, in the Build Target select Google API s as shown in the Image below. Provide the package name and click on Finish.



Once these are done your folder structure will look like in the image shown below.




Now that we have created the project, we can build upon the logic which we have mentioned above.
1) Including Google libraries:
We need to first make the app use google libraries, inorder to do that open AndroidManifest.xml 
and add <uses-library android:name="com.google.android.maps" />  inside the application tag of 
the xml.
 
2) Enabling Internet access:
To make the app able to access internet to download the map tiles, you need to add the following 
code outside the application tag.
 
<uses-permission android:name="android.permission.INTERNET" />
 
Once done the AndroidManifest.xml looks like the image shown below.
 
 

3) Creation of Map View:
We need to create a View which will display the map, so go to res and replace the existing code with the code below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:apiKey="<Your API Key>"
    />
</RelativeLayout>

In the above code we have made the layout as relative and we have set the rootnode as MapView. Make sure you add your api key in the code.
4) To define the Activity :
Go to the folder “src” and click on the package name  and then open the java file under this package.
a) As you can see there will be a default code present in it. The class will extend Activity by default, but since we are dealing with maps it should be changed to MapActivity.
b) Then set the content to Main setContentView(R.Layout.Main) which will load the layout with the mapview.
c) After we have set the layout, we will have to instantiate the mapview class after which we can set the zoom controls. The code for which is given below.
mapV=(MapView) findViewById(R.id.mapview)
mapv.builtInZoomControls(true);

d) Then we will set a GeoPoint so that when the app starts it points to some location at zoom level 12 using the mapcontroller.
GeoPoint=new GeoPoint(<your choice>, <your choice>);
mController=mapV.getController();
mController.animateTo(GeoPoint);
mController.setZoom(12);
So the final code will look the image shown below.



Phew we have completed the coding of the app, well it was easy :) to be frank. Now we would like to run the app and see how it works. Before you do that we wil need to have an emulator.  AVD Creation will show how to create an AVD.

Once you are done with it, right click on the project and click on Run As and then click on Android Application and it will start the AVD and install the apk on the emulator. The result in the emulator is shown below.


Well congrats your first app has started ;). Some of you might get grey tiles problem which we will be debugging in the next part. Untill then Adios!

Saturday, October 1, 2011

Creating a Simple Google Map Application - Part 1

Finally we are all set to get started with a development of a simple app. All of us usually start off with hello world which is kind of boring and also helps you a little apart from giving you the happiness of creating your simple app.  So this app is all about displaying the Google maps on your mobile, although you have a Google map application in your mobiles which has more options its gives you the happiness of creating your own Google map app ;).
                So the pre requisites are –
1) Google API’s – These contain all the libraries which you will be using in this app. In order to obtain this,
                a) click on the” Windows “in Eclipse and click on Android SDK and AVD manager.
                b) Click on Available Packages and click on Third Party Add-Ons. As show below.
               
                c) Select Google API’s Android API 8 Version 2.Once it is done your installed packages should look like the following.

2) Obtaining Google Map API Key – This is a key for developers to register with the service.
To obtain this you need to have your own private key or you can use can use the debug.keystore. We will use the debug.keystore for now.  This is usually located in
Then in command prompt go to the java folder and go to /JDK<version>/bin and execute the following command “keytool -list -alias androiddebugkey -keystore <path_to_debug_keystore>.keystore -storepass android -keypass android
Once you do this you will get a MD5 finger print as shown below.


Once you have got the MD5 finger print, go to the following link Google API Signup to get the API key.
In the next part we will learn about the logic and also start coding our app.