Anas Shahid Android Development

Sunday, July 14, 2013

Date and Time picker dialog in Android

Android Provides us with the option of picking date and time using built-in date and time pickers. In this post I will explain how to use these dialogs and how to set them with current date and time on default view.
First let me clear that it is NOT the date and time picker that is in the xml layout, instead we will work on the java code to display the dialog. So lets start with the date.
First off create a new project, with one layout having two buttons and two textviews. Get the reference to these views and name them bttn_date, bttn_time, text_date and text_time respectively. The xml goes something like this:
After setting the xml get references to these buttons and labels in JAVA file(as shown above).
Now for Date:
First we will override the onclick() event of the bttn_date.As we want to set the current date on default when the dialog shows up, we need to get instance of the calander class.
Calander class returns the instance of the time and date and we can extract each separately'
following is the code:
First you will have to declare some global variables
        private int myYear, myMonth, myDay; 
static final int ID_DATEPICKER = 0;
String myDate;

Now in the onclick() event of date button:

bttn_date.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final Calendar c = Calendar.getInstance();
myYear = c.get(Calendar.YEAR);
   myMonth = c.get(Calendar.MONTH);
   myDay = c.get(Calendar.DAY_OF_MONTH);
   showDialog(ID_DATEPICKER);
}
});
Plus we will have to define a function of datepickerdialog that defines ondateset() function, in this we will set the date to the text_date textbox . it looks something like this:


private DatePickerDialog.OnDateSetListener myDateSetListener
 = new DatePickerDialog.OnDateSetListener(){
  @Override
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
  {
    //get date in text form
   myDate =  String.valueOf(monthOfYear+1) +"/"+  String.valueOf(dayOfMonth)+"/"+String.valueOf(year);
   text_date.setText(myDate);
  
    }

};

Now for time picker dialog:
we will follow similar steps, first, declare some global variables:

private int myhour, myminute; 
static final int ID_TIMEPICKER = 1;
String myTime;

In the onclick() event of bttn_time:

bttn_time.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {

final Calendar c = Calendar.getInstance();
myhour = c.get(Calendar.HOUR_OF_DAY);
   myminute = c.get(Calendar.MINUTE);
   showDialog(ID_TIMEPICKER);

}

});

Define the settime() finction of the time picker:
 private TimePickerDialog.OnTimeSetListener TimePickerListener =
           new TimePickerDialog.OnTimeSetListener() {
               // while dialog box is closed, below method is called.
               public void onTimeSet(TimePicker view, int hour, int minute)
                        {
                myTime =  String.valueOf(myhour) +" : "+ String.valueOf(myminute);
                text_time.setText(myTime);
               }
           };


We are done with the dialogs.. But it wont show up until we override onCreate() function of the dialog box which identifies the dialog to show up on respective clicks(remember we initialized and called ID_TIMEPICKER and ID_DATEPICKER).
here's the code
@Override
protected Dialog onCreateDialog(int id) 
{
 
 switch(id)
 {
 case ID_DATEPICKER:
   return new DatePickerDialog(this, myDateSetListener,myYear, myMonth, myDay);
  //returns datepicker dialog
 case ID_TIMEPICKER:
 return new TimePickerDialog(this, TimePickerListener,myhour, myminute, true);
                      //returns new time picker dialog
                      //true in the end specifies we are using 24hour clock(for 12-hour set it to false)
default:
   return null;
 }
}
We are done this will give the following output:








View Anas Shahid's profile on LinkedIn

Wednesday, July 3, 2013

Displaying mulitiple markers on Map

So after I had configured maps in my application by using Android Map Integration I came accross a problem. How to show multiple markers on the map? I searched on the net but was'nt quite able to find the answer. I had a number of places to point on but in the tutorials they would mark a single place. Then I came across to the solution that for displaying markers one have to extend a class named ItemizedOverlay.

Now name the new class as you want (I named it MyItemizedOverlay). Set the Superclass be ItemizedOverlay

Now put the following functions into the class.

//Create Array list of overlays. Since we are trying to mark as many places as we want
private ArrayList<OverlayItem>mOverlays = new ArrayList<OverlayItem>();

//constructor of the class.called by passing a drawable as argument.you can use any drawable by placing it in //drawable-hdpi folder.
public MyItemizedOverlay(Drawable defaultMarker) 
{ super(boundCenterBottom(defaultMarker)); }

//Creates an ovelay item
@Override
protected OverlayItem createItem(int i) 
{ return mOverlays.get(i); }
 //returns the size of array list
@Override
public int size() 
{ return mOverlays.size();}
 //if you want a dialog or toast when the user touches the marker, you can override onTap function.
//Here's the sample.I am showing a dialog
@Override
protected boolean onTap(int index)
{ OverlayItem item= mOverlays.get(index);
String title=item.getTitle();
String snippet=item.getSnippet();
AlertDialog.Builder builder= new AlertDialog.Builder(MyItemizedOverlay.this);
builder.setTitle(title);
builder.setMessage("abcdef");
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();

}
});
AlertDialog alert=builder.create();
alert.show();
return true;
}
 //and the most important function to add a marker
public void addOverlay(OverlayItem over)
{
mOverlays.add(over);
populate();
}

It will give you some errors you will have to do the necessary imports.

Now in our MainActivity Class where we import the map(See the previous post)

Declare some variables like

MapView stopmap=(MapView) findViewById(R.id.stopsmap);//My map view
MapController smcontroller; //map controller to control map operations
Drawable marker=this.getResources().getDrawable(R.drawable.pushpin); 
//get the drawable(marker)from drawble folder
List<Overlay> stopmapoverlays=stopmap.getOverlays();
MyItemizedOverlay itemizedoverlay= new MyItemizedOverlay(marker); //instance of our custom class

now define some points to show on maps
you can get the latitude and longitude of a perticular point on net easily
GeoPoint londonbridge= getpoint(24.867203, 67.082713);
GeoPoint timessquare= getpoint(24.85742,67.083174);
GeoPoint whitehouse= getpoint(24.884977,67.057178);
GeoPoint chinawall=getpoint(24.917849,67.097025);

GeoPoint sportscity=getpoint(24.9368959, 67.0759951);

getpoint(latitude,longitude) is our custom functuion that converts the latitude and longitude into location
private GeoPoint getpoint (double lat, double lon)
{
return (new GeoPoint((int)(lat*1E6), (int)(lon*1E6)));
}


We have defined the points we want to define overlayitems coresponding to these points
OverlayItem londonbridgeoverlay=new OverlayItem(londonbridge, "LondonBridge", ""));
OverlayItem chinawalloverlay=new OverlayItem(chinawall, "ChinaWall", ''));
OverlayItem whitehouseoverlay=new OverlayItem(whitehous, "WhiteHouse", ""));
OverlayItem sportscityoverlay=new OverlayItem(sportscity, "SportsCity", "");
OverlayItem timessquareoverlay=new OverlayItem(timessquare, "TimesSquare", "");

a new overlayitem constructor has 3 arguments OverlayItem(GeoPoint,title,snippet)
Geopoint is the variable we declared earlier defines the location of marker,other two are strings and can be used on tap to display the title of the point etc(if you dont wanna use these fields put an empty double quotes in each)

Now add these overlays to the itemized overlay arraylist
itemizedoverlay.addOverlay( londonbridgeoverlay);
itemizedoverlay.addOverlay(timessquareoverlay);
itemizedoverlay.addOverlay(whitehouseoverlay);
itemizedoverlay.addOverlay(sportscityoverlay);
itemizedoverlay.addOverlay(chinawalloverlay); 

Finally add these Overlays to the map and you are done:
stopmapoverlays.add(itemizedoverlay);

I have displayed many markers (around 200) on a single map using this technique, here's the snapshot of the result that i get:

View Anas Shahid's profile on LinkedIn

Tuesday, July 2, 2013

Integrating Google Maps in Android application

So often time in your mobile application you will need to work with location and maps. Here is a simple example how to integrate Google Maps in your android application.

To set up for using maps you will need to first register for google maps Api Key. When I worked on mapsit was quite complicated to create Api key using MD5 fingerprint but now its quite easy.

To register Go to https://code.google.com/apis/console/, and log in with your Google Account.
The following will appear:
Click on the "Create Project" button.
In the list of services, find Google Maps API v3, and click on "off" to turn it on.
In the next screen, check "I Agree..." and the click the "Accept" button. You will now see that the button next to Google Maps API v3 has changed to "on".
Then click "API Access" in the menu to the left. It will ask you to "Create an OAuth 2.0 client id...".
In the next screen, provide a product name (e.g. "demo"), upload an image (if you want to) as a logo of your project, and click the "Next" button.
In the next screen, choose Application type ("Web application"), and type in your web address, and then click the "Create Client Id" button.
In the next screen, you have got an API key.

Remark Note: Save your API key! (You will need it for all Google Maps applications you develop for the particular URL.
Another thing that you will have to do is setting up the build environment. Google maps doesnt work on the normal APIs , it requires to have Google API installed on your emulator. for this go to your SDK manager , check the Google API checkbox and Install the package after you agree the terms of service.

Now create an Emulator having the installed google api. At this point you are done with the hard part of the project.

Create a new project in ADT and set Target SDK Version to the currently installed API.
Copy the following code in XML to access a map. Replace the key with the one you generated from the process above

<com.google.android.maps.MapView
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:id="@+id/routesmap"
                 android:clickable="true"
                 android:apiKey="0L42deK321zB1HWl4KMymkm80kI-bsm0Sy_5chQ"
                 />

In the Java file set the class to extend MapActivity, set the contentview to the xml file having the map and you are done. You can get the id of the map to perform functionalities like setCenter(), setBuiltinZoomControls and displaying markers(which I will show in the next post). Here's some code to help.

public class MainActivity extends MapActivity 
{ private MapView map= null;
private MyLocationOverlay me=null;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map= (MapView) findViewById(R.id.map);
map.getController().setCenter(getpoint(24.860117, 67.026837));
map.setBuiltInZoomControls(true);
map.getController().setZoom(19);
}

private GeoPoint getpoint (double lat, double lon)
{
return (new GeoPoint((int)(lat*1E6), (int)(lon*1E6)));
}
}

PS:Dont forget to put internet permission in your application from manifest file.

Hope now you are able to configure maps correctly.




After you have configured maps correctly you can see How to display Multiple markers on map


View Anas Shahid's LinkedIn profileView Anas Shahid's profile