Android Utility class - Activity navigation.
ActivityHelper
In this article helps to create and use the utility class for activity navigation.
1. Create a normal class
public class ActivityHelper { }
2. Define the utility method using the static factory method
1. public static Intent createActivityIntent(Activity activity,Class preconditionActivityClazz) { } -used to create a intent
2. public static void startOriginalActivityAndFinish(Activity preconditionActivity) { } - Return to the old activity
3. public static void startNewActivityAndFinish(Activity activity,Intent intent) { } - Finish the current Activty and start a new activity.
3. Implementation
Intent intent = ActivityHelper.createActivityIntent(MainActivity.this,TargetActivity.class);
Using this intent we can navigate the screen
startNewActivityAndFinish(intent); -> now the Activity moves to the TargetActivity and close the current activty.
startOriginalActivityAndFinish(TargetActivity.this); - Return back to orginal activity.
Sample Code
public class ActivityHelper {
static private final String EXTRA_WRAPPED_INTENT = "ActivityHelper_wrappedIntent";
/**
* Create a precondition activity intent.
* @param activity the original activity
* @param preconditionActivityClazz the precondition activity's class
* @return an intent which will launch the precondition activity.
*/
public static Intent createActivityIntent(Activity activity,
Class preconditionActivityClazz) {
Intent newIntent = new Intent();
newIntent.setClass(activity, preconditionActivityClazz);
newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent());
return newIntent;
}
/**
* Start the original activity, and finish the precondition activity.
* @param preconditionActivity
*/
public static void startOriginalActivityAndFinish(
Activity preconditionActivity) {
preconditionActivity.startActivity((Intent) preconditionActivity.getIntent().getParcelableExtra(EXTRA_WRAPPED_INTENT));
preconditionActivity.finish();
}
/**
* Start the precondition activity using a given intent, which should have
* been created by calling createPreconditionIntent.
* @param activity
* @param intent
*/
public static void startNewActivityAndFinish(Activity activity,
Intent intent) {
activity.startActivity(intent);
activity.finish();
}
}

In this article helps to create and use the utility class for activity navigation.
1. Create a normal class
public class ActivityHelper { }
2. Define the utility method using the static factory method
1. public static Intent createActivityIntent(Activity activity,Class preconditionActivityClazz) { } -used to create a intent
2. public static void startOriginalActivityAndFinish(Activity preconditionActivity) { } - Return to the old activity
3. public static void startNewActivityAndFinish(Activity activity,Intent intent) { } - Finish the current Activty and start a new activity.
3. Implementation
Intent intent = ActivityHelper.createActivityIntent(MainActivity.this,TargetActivity.class);
Using this intent we can navigate the screen
startNewActivityAndFinish(intent); -> now the Activity moves to the TargetActivity and close the current activty.
startOriginalActivityAndFinish(TargetActivity.this); - Return back to orginal activity.
Sample Code
public class ActivityHelper {
static private final String EXTRA_WRAPPED_INTENT = "ActivityHelper_wrappedIntent";
/**
* Create a precondition activity intent.
* @param activity the original activity
* @param preconditionActivityClazz the precondition activity's class
* @return an intent which will launch the precondition activity.
*/
public static Intent createActivityIntent(Activity activity,
Class preconditionActivityClazz) {
Intent newIntent = new Intent();
newIntent.setClass(activity, preconditionActivityClazz);
newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent());
return newIntent;
}
/**
* Start the original activity, and finish the precondition activity.
* @param preconditionActivity
*/
public static void startOriginalActivityAndFinish(
Activity preconditionActivity) {
preconditionActivity.startActivity((Intent) preconditionActivity.getIntent().getParcelableExtra(EXTRA_WRAPPED_INTENT));
preconditionActivity.finish();
}
/**
* Start the precondition activity using a given intent, which should have
* been created by calling createPreconditionIntent.
* @param activity
* @param intent
*/
public static void startNewActivityAndFinish(Activity activity,
Intent intent) {
activity.startActivity(intent);
activity.finish();
}
}
Wednesday, March 24, 2010
JUnit Setup For Android
Here we are discuss about the JUnit implementation in android application
1. Overview of JUnit in Android
2. Create a Junit Enables Android Application
3. Create a Sample Testcase.
Oveview
The popular JUnit test framework is integrated into Android.
JUnit, if used properly, brings two major benefits to the test implementation.
* JUnit enforces the hierarchical organization of the test cases
* The pattern JUnit is based on guarantees the independence of the test cases and minimizes their interference.
Android test cases classes should inherit from android.test.AndroidTestCase instead of junit.framework.TestCase.
The main difference between the two is that AndroidTestCase knows about the Context object and provides method to obtain the current Context.
As many Android API methods need the Context object, this makes coding of Android test cases much easier.
Make a seperate folder for Junit test Class. Because it should be remove while move to production.
Steps to Implement the JUnit.
1. Create a project
2. Add uses-library and instrumentation in AndroidManifeast.xml
3. Create a StartupTestSuite
4. Create a Testcase class
5. Run the Apps
Create a Project
Create an android project using your IDE and create a basic component for the application. In this blog i have created a MainActivity which get the text based input from the user.
Requirement : User enter the His/Her name and password and submit the form.
I have created the following Layout.

1. Overview of JUnit in Android
2. Create a Junit Enables Android Application
3. Create a Sample Testcase.
Oveview
The popular JUnit test framework is integrated into Android.
JUnit, if used properly, brings two major benefits to the test implementation.
* JUnit enforces the hierarchical organization of the test cases
* The pattern JUnit is based on guarantees the independence of the test cases and minimizes their interference.
Android test cases classes should inherit from android.test.AndroidTestCase instead of junit.framework.TestCase.
The main difference between the two is that AndroidTestCase knows about the Context object and provides method to obtain the current Context.
As many Android API methods need the Context object, this makes coding of Android test cases much easier.
Make a seperate folder for Junit test Class. Because it should be remove while move to production.
Steps to Implement the JUnit.
1. Create a project
2. Add uses-library and instrumentation in AndroidManifeast.xml
3. Create a StartupTestSuite
4. Create a Testcase class
5. Run the Apps
Create a Project
Create an android project using your IDE and create a basic component for the application. In this blog i have created a MainActivity which get the text based input from the user.
Requirement : User enter the His/Her name and password and submit the form.
I have created the following Layout.
Android CodeReview Tool Setup - PMD
In this article help us to setup the Code Review tool for android.
Installing PMD
First, we need to install the PMD Eclipse plugin by following the instructions on the plugin page. Goto Help> Install New Software > Click Add

Add the link : http://pmd.sf.net/eclipse

Install the PMD for Eclipse 3

Configure PMD your project
1. In the project properties, select the PMD page. Enable PMD needs to be checked to run PMD automatically. Otherwise, you will need to manually start PMD each time you want to check your code using the PMD submenu and older violations will not be removed automatically once you fix your code, you will need to use the clear violations in the PMD submenu.

2. The “Handle high priority violations as errors” property needs to be unchecked. This is a new property in the 3.2.6 version of the PMD eclipse plugin. When that option is checked, the Android plugin will refuse to deploy your application if the project contains high level violations. So unless you have a development rule stating that there should be no high level violations in your project at any time, this option should be disabled.
3. With that setup, PMD will be enabled but it will be using the default ruleset shared by all projects in the workspace and that is not really adequate for Android development. To define a specific set of rules for your project, check the last box on the PMD page to create a file named “.ruleset” at the top level of your project. The configuration is now complete, press “OK” and then select “Yes” on the next popup.
4. Ensure the .ruleset and .pmd files has been created successfully.

5. Check the Code using the PMD
Select the Project and rightclick and select PMD > Check Code With PMD

6. check the Result in the Violations Overview.


Installing PMD
First, we need to install the PMD Eclipse plugin by following the instructions on the plugin page. Goto Help> Install New Software > Click Add
Add the link : http://pmd.sf.net/eclipse
Install the PMD for Eclipse 3
Configure PMD your project
1. In the project properties, select the PMD page. Enable PMD needs to be checked to run PMD automatically. Otherwise, you will need to manually start PMD each time you want to check your code using the PMD submenu and older violations will not be removed automatically once you fix your code, you will need to use the clear violations in the PMD submenu.
2. The “Handle high priority violations as errors” property needs to be unchecked. This is a new property in the 3.2.6 version of the PMD eclipse plugin. When that option is checked, the Android plugin will refuse to deploy your application if the project contains high level violations. So unless you have a development rule stating that there should be no high level violations in your project at any time, this option should be disabled.
3. With that setup, PMD will be enabled but it will be using the default ruleset shared by all projects in the workspace and that is not really adequate for Android development. To define a specific set of rules for your project, check the last box on the PMD page to create a file named “.ruleset” at the top level of your project. The configuration is now complete, press “OK” and then select “Yes” on the next popup.
4. Ensure the .ruleset and .pmd files has been created successfully.
5. Check the Code using the PMD
Select the Project and rightclick and select PMD > Check Code With PMD
6. check the Result in the Violations Overview.
My Setup for Google Android Development Environment
Here we discussed my android environment. I have setup my android environment for various proces.
I belive the following items are esstential for project development and make easy our development.
Source Code Management Setup
A managment process to record the data.
What benefits do Source Code Management tools provide?
SCM tools help development teams in many ways:
* Collaboration: SCM tools prevent one user from accidentally overwriting the changes of another, allowing many developers to work on the same code without stepping one each other's toes.
* History: SCM tools track the complete development history of the software, including the exact changes which have occurred between releases and who made those changes.
* Release notes generation: Given the tracking of each change, the SCM can be used to generate notes for their software releases which accurately capture all of the changes included in the new release.
* Documentation and test management: SCM tools can be used to manage not just software source code, but also test suites and documentation for their software.
* Change notifications: To keep interested members of the team informed when changes occur to the source code.
Who uses SCM tools?
SCM tools are used by:
* Project developers who are writing source code.
* Project testers who need to download the very latest changes.
* Advanced users who want to try out code that is not yet stable, mature or released.
What SCM tools does SourceForge.net support?
* Subversion
* Git
* Mercurial
* Bazaar
* CVS
Subversion
A tool for software developers which supports collaborative development of software within a team, and the tracking of changes to software source code over time. Subversion is used by developers, and advanced users who need the very latest changes to the software (before releases occur).
Developers should familiarize themselves with Subversion by reading Version Control with Subversion.
Reference :
http://sourceforge.net/apps/trac/sourceforge/wiki/What%20is%20Source%20Code%20Management
http://sourceforge.net/apps/trac/sourceforge/wiki/Subversion
Click here[Setup SVN Environment] you can get more information.
Project Management Tool - Not Yet Done [As of now i am tracking milestone in a excel sheet]
Android Setup
Check the Following blog to setup the android setup
Reference : http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html
Integrated Development EnvironmentMOTODEV Studio is Motorola's robust IDE for developing exceptional mobile device applications for a wide range of Motorola products
You can download from : http://developer.motorola.com/docstools/motodevstudio/
Code Review With PMD
Code review is systematic examination (often as peer review) of computer source code intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers' skills.
Reference : http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html
Testing - JUnit configuration.
In computer programming, unit testing is a software verification and validation method in which a programmer tests if individual units of source code are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure.
Here we are using the Instrumentation Framework to write test cases.
Reference : http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html
Build Tool.
In software engineering, continuous integration (CI) implements continuous processes of applying quality control - small pieces of effort, applied frequently. Continuous integration aims to improve the quality of software, and to reduce the time taken to deliver it, by replacing the traditional practice of applying quality control after completing all development.
Here we are discussing Hudson for continuous integration build
Reference :
http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html

I belive the following items are esstential for project development and make easy our development.
- Source Code Management Setup
- Project Management Tool - Not Yet Done [As of now i am tracking milestone in a excel sheet]
- Android Setup
- Integrated development environment
- Code Review With PMD
- Testing - JUnit configuration.
- Build Tool.
Source Code Management Setup
A managment process to record the data.
What benefits do Source Code Management tools provide?
SCM tools help development teams in many ways:
* Collaboration: SCM tools prevent one user from accidentally overwriting the changes of another, allowing many developers to work on the same code without stepping one each other's toes.
* History: SCM tools track the complete development history of the software, including the exact changes which have occurred between releases and who made those changes.
* Release notes generation: Given the tracking of each change, the SCM can be used to generate notes for their software releases which accurately capture all of the changes included in the new release.
* Documentation and test management: SCM tools can be used to manage not just software source code, but also test suites and documentation for their software.
* Change notifications: To keep interested members of the team informed when changes occur to the source code.
Who uses SCM tools?
SCM tools are used by:
* Project developers who are writing source code.
* Project testers who need to download the very latest changes.
* Advanced users who want to try out code that is not yet stable, mature or released.
What SCM tools does SourceForge.net support?
* Subversion
* Git
* Mercurial
* Bazaar
* CVS
Subversion
A tool for software developers which supports collaborative development of software within a team, and the tracking of changes to software source code over time. Subversion is used by developers, and advanced users who need the very latest changes to the software (before releases occur).
Developers should familiarize themselves with Subversion by reading Version Control with Subversion.
Reference :
http://sourceforge.net/apps/trac/sourceforge/wiki/What%20is%20Source%20Code%20Management
http://sourceforge.net/apps/trac/sourceforge/wiki/Subversion
Click here[Setup SVN Environment] you can get more information.
Project Management Tool - Not Yet Done [As of now i am tracking milestone in a excel sheet]
Project management is the discipline of planning, organizing, and managing resources to bring about the successful completion of specific project goals and objectives. It is sometimes conflated with program management, however technically a program is actually a higher level construct: a group of related and somehow interdependent projects.
Android Setup
Check the Following blog to setup the android setup
Reference : http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html
Integrated Development EnvironmentMOTODEV Studio is Motorola's robust IDE for developing exceptional mobile device applications for a wide range of Motorola products
You can download from : http://developer.motorola.com/docstools/motodevstudio/
Code Review With PMD
Code review is systematic examination (often as peer review) of computer source code intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers' skills.
Reference : http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html
Testing - JUnit configuration.
In computer programming, unit testing is a software verification and validation method in which a programmer tests if individual units of source code are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure.
Here we are using the Instrumentation Framework to write test cases.
Reference : http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html
Build Tool.
In software engineering, continuous integration (CI) implements continuous processes of applying quality control - small pieces of effort, applied frequently. Continuous integration aims to improve the quality of software, and to reduce the time taken to deliver it, by replacing the traditional practice of applying quality control after completing all development.
Here we are discussing Hudson for continuous integration build
Reference :
http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html
Monday, March 22, 2010
Sample Google Map Driving Direction.
1. Create a Customized Overlay Components.
2. Create a Map View Layout.
3. Get the Direction Data using the google Service.
4. Parse the Data and Generate geopoints
5. Draw the path using the customized Overlay Components
Create a Customized Overlay Components.
This components are used to draw the rount, which extends the overlay class.
Reference : http://about-android.blogspot.com/2010/03/steps-to-place-marker-in-map-overlay.html
Create a Map View Layout
Create a Map View and add create a mainactivity.
Reference :http://about-android.blogspot.com/2010/02/map-implementation.html
Get the Direction Data using the google Service
Google provides the varity of service to access the google map. In this blog we are using the following service to get the direction data.
http://maps.google.com/maps?f=d&hl=en&saddr=XXXXXXX&daddr=XXXXXXX&ie=UTF8&0&om=0&output=kml
Reference : http://mapki.com/wiki/Google_Map_Parameters
String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="+srcPlace+"&daddr="+destPlace+"&ie=UTF8&0&om=0&output=kml";
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InoutStream is = urlConnection.getInputStream();
} catch (Exception e) {
}
Parse the Data and Generate geopoints
Here i am using the DOM Parser for parse the Content. You can use SAX parser.
Reference : http://about-android.blogspot.com/2010/02/sample-saxparser-in-android.html
Sample DOM Parser:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
The following method is used to access the Url and parse content
private String[] getDirectionData(String srcPlace, String destPlace) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
+ srcPlace + "&daddr=" + destPlace
+ "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
Draw the path using the customized Overlay Components
Using the Custom Overlay Component we can draw the line.
// STARTING POINT
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
.parseDouble(lngLat[0]) * 1E6));
myMC = myMapView.getController();
geoPoint = startGP;
myMC.setCenter(geoPoint);
myMC.setZoom(15);
myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
// NAVIGATE THE PATH
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
Log.d("xxx", "pair:" + pairs[i]);
}
// END POINT
myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));
Sample Source
Custom Overlay Component : [DirectionPathOverlay.java]
public class DirectionPathOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
public DirectionPathOverlay(GeoPoint gp1, GeoPoint gp2) {
this.gp1 = gp1;
this.gp2 = gp2;
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
paint.setColor(Color.BLUE);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(2);
canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
(float) point2.y, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
}
}
MainAcvity.java
public class MainActivity extends MapActivity {
MapView myMapView = null;
MapController myMC = null;
GeoPoint geoPoint = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MapView) findViewById(R.id.mapid);
geoPoint = null;
myMapView.setSatellite(false);
String pairs[] = getDirectionData("trichy", "thanjavur");
String[] lngLat = pairs[0].split(",");
// STARTING POINT
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
.parseDouble(lngLat[0]) * 1E6));
myMC = myMapView.getController();
geoPoint = startGP;
myMC.setCenter(geoPoint);
myMC.setZoom(15);
myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
// NAVIGATE THE PATH
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
Log.d("xxx", "pair:" + pairs[i]);
}
// END POINT
myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));
myMapView.getController().animateTo(startGP);
myMapView.setBuiltInZoomControls(true);
myMapView.displayZoomControls(true);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private String[] getDirectionData(String srcPlace, String destPlace) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
+ srcPlace + "&daddr=" + destPlace
+ "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
}

2. Create a Map View Layout.
3. Get the Direction Data using the google Service.
4. Parse the Data and Generate geopoints
5. Draw the path using the customized Overlay Components
Create a Customized Overlay Components.
This components are used to draw the rount, which extends the overlay class.
Reference : http://about-android.blogspot.com/2010/03/steps-to-place-marker-in-map-overlay.html
Create a Map View Layout
Create a Map View and add create a mainactivity.
Reference :http://about-android.blogspot.com/2010/02/map-implementation.html
Get the Direction Data using the google Service
Google provides the varity of service to access the google map. In this blog we are using the following service to get the direction data.
http://maps.google.com/maps?f=d&hl=en&saddr=XXXXXXX&daddr=XXXXXXX&ie=UTF8&0&om=0&output=kml
Reference : http://mapki.com/wiki/Google_Map_Parameters
String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="+srcPlace+"&daddr="+destPlace+"&ie=UTF8&0&om=0&output=kml";
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InoutStream is = urlConnection.getInputStream();
} catch (Exception e) {
}
Parse the Data and Generate geopoints
Here i am using the DOM Parser for parse the Content. You can use SAX parser.
Reference : http://about-android.blogspot.com/2010/02/sample-saxparser-in-android.html
Sample DOM Parser:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
The following method is used to access the Url and parse content
private String[] getDirectionData(String srcPlace, String destPlace) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
+ srcPlace + "&daddr=" + destPlace
+ "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
Draw the path using the customized Overlay Components
Using the Custom Overlay Component we can draw the line.
// STARTING POINT
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
.parseDouble(lngLat[0]) * 1E6));
myMC = myMapView.getController();
geoPoint = startGP;
myMC.setCenter(geoPoint);
myMC.setZoom(15);
myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
// NAVIGATE THE PATH
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
Log.d("xxx", "pair:" + pairs[i]);
}
// END POINT
myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));
Sample Source
Custom Overlay Component : [DirectionPathOverlay.java]
public class DirectionPathOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
public DirectionPathOverlay(GeoPoint gp1, GeoPoint gp2) {
this.gp1 = gp1;
this.gp2 = gp2;
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
paint.setColor(Color.BLUE);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(2);
canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
(float) point2.y, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
}
}
MainAcvity.java
public class MainActivity extends MapActivity {
MapView myMapView = null;
MapController myMC = null;
GeoPoint geoPoint = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MapView) findViewById(R.id.mapid);
geoPoint = null;
myMapView.setSatellite(false);
String pairs[] = getDirectionData("trichy", "thanjavur");
String[] lngLat = pairs[0].split(",");
// STARTING POINT
GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
.parseDouble(lngLat[0]) * 1E6));
myMC = myMapView.getController();
geoPoint = startGP;
myMC.setCenter(geoPoint);
myMC.setZoom(15);
myMapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));
// NAVIGATE THE PATH
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
myMapView.getOverlays().add(new DirectionPathOverlay(gp1, gp2));
Log.d("xxx", "pair:" + pairs[i]);
}
// END POINT
myMapView.getOverlays().add(new DirectionPathOverlay(gp2, gp2));
myMapView.getController().animateTo(startGP);
myMapView.setBuiltInZoomControls(true);
myMapView.displayZoomControls(true);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private String[] getDirectionData(String srcPlace, String destPlace) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&saddr="
+ srcPlace + "&daddr=" + destPlace
+ "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
}
Wednesday, March 17, 2010
Create a Custom ListView
This blog helps to create a custom list view.
Steps to create a Custom List View
1. Create Layout for your listview
2. Create a class which extend the ArrayAdapter
3. Assign the Values to View.
4. Implement the Custom Adapter in the mainactivity
Create Layout for your listview
This layout are used to show the listview as a each view. You can add the multiple view in that. In this example i have added only one textview and change the property.
Sample layout [customlistview.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#FF04FF" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
android:textColor="#FFFFFF" android:textSize="25px"
android:layout_height="fill_parent" android:layout_width="fill_parent"></TextView>
</LinearLayout>
Create a class which extend the ArrayAdapter & Assign the Values to View.
- This class should extend the ArrayAdapter.
- Create a parametrized constructor which pass the Context Object, CustomLayout ID as a integer value and Items as a arraylist.
- Override getView() and assign the values in that.
Sample Custom Array Adapter Class [as a class member of mainactivity]
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int resource, ArrayList<Order> items) {
super(context, resource, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.customlistview, null);
}
Order o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.TextView01);
if (tt != null) {
tt.setText("Name: " + o.getTitleName());
}
}
return v;
}
}
Implement the Custom Adapter in the mainactivity
- Create a Instance for the custom Adapater class and ArrayListOrderAdapter customAdapter;
ArrayList<Order> orderList;
- get the List of Items
orderList = new ArrayList<Order>();
orderList.add(new Order("first"));
orderList.add(new Order("second"));
orderList.add(new Order("third"));
customAdapter = new OrderAdapter(this, R.layout.customlistview,
orderList);
ListView l = (ListView) findViewById(R.id.ListView01);
l.setAdapter(customAdapter);
Sample Source
MainActivity.java
public class MainActivity extends Activity {
/** Called when the activity is first created. */
OrderAdapter customAdapter;
ArrayList<Order> orderList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
orderList = new ArrayList<Order>();
orderList.add(new Order("first"));
orderList.add(new Order("second"));
orderList.add(new Order("third"));
customAdapter = new OrderAdapter(this, R.layout.customlistview,
orderList);
ListView l = (ListView) findViewById(R.id.ListView01);
l.setAdapter(customAdapter);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int resource,
ArrayList<Order> items) {
super(context, resource, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.customlistview, null);
}
Order o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.TextView01);
if (tt != null) {
tt.setText("Name: " + o.getTitleName());
}
}
return v;
}
}
}
Order.java
public class Order {
public Order(String titleName) {
this.titleName = titleName;
}
private String titleName;
public String getTitleName() {
return titleName;
}
public void setTitleName(String titleName) {
this.titleName = titleName;
}
}
main.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">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<ListView android:id="@+id/ListView01" android:layout_height="fill_parent"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
customlistview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#FF04FF" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
android:textColor="#FFFFFF" android:textSize="25px"
android:layout_height="fill_parent" android:layout_width="fill_parent"></TextView>
</LinearLayout>
Tuesday, March 16, 2010
Steps to place the Marker in the Map [Overlay Example]
In this ariticle used to place the marker in the map view.
1. Create a Customize Marker Class
Class Should Extend the ItemizedOverlay
Create a parameterized Constructor. i am trying with two constructor.
The constructor must define the default marker for each of the OverlayItems. In order for the Drawable to actually get drawn, it must have its bounds defined.
Most commonly, you want the center-point at the bottom of the image to be the point at which it's attached to the map coordinates. This is handled for you with the boundCenterBottom() method. Wrap this around our defaultMarker, so the super constructor call looks like this:
public HelloItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(defaultMarker);
mContext = context;
}
2. Create the following class members
1. private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Used to put each of the OverlayItem objects we want on the map.
2. private Context mContext ;
3. In order to add new OverlayItems to the ArrayList, you need a new method:
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
Now define the HelloItemizedOverlay constructors. The constructor must define the default marker for each of the OverlayItems. In order for the Drawable to actually get drawn, it must have its bounds defined.
3. Override the following methods
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
4. Implement the Marker in the map activity
1. Get the Overlay as a list from mapview
List<Overlay> mapOverlays = myMapView.getOverlays()
2. Instantiate the following class
Drawable with marker icon
Drawable drawable = this.getResources().getDrawable(R.drawable.pinicon);
Marker with Drawable object
MyMapMarker itemizedoverlay = new MyMapMarker(drawable,this);
OverlayItem with geopoint
OverlayItem overlayitem = new OverlayItem(geoPoint, "Info",
"Selected City is" + city);
3. All that's left is to add this OverlayItem to your collection, then add the MainActivity to the MapView:
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
Sample Source
public class MyMapMarker extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public MyMapMarker(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public MyMapMarker(Drawable defaultMarker, Context context) {
this(defaultMarker);
mContext = context;
}
public void addOverlay(OverlayItem item) {
mOverlays.add(item);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
}

1. Create a Customize Marker Class
Class Should Extend the ItemizedOverlay
Create a parameterized Constructor. i am trying with two constructor.
The constructor must define the default marker for each of the OverlayItems. In order for the Drawable to actually get drawn, it must have its bounds defined.
Most commonly, you want the center-point at the bottom of the image to be the point at which it's attached to the map coordinates. This is handled for you with the boundCenterBottom() method. Wrap this around our defaultMarker, so the super constructor call looks like this:
public HelloItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(defaultMarker);
mContext = context;
}
2. Create the following class members
1. private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Used to put each of the OverlayItem objects we want on the map.
2. private Context mContext ;
3. In order to add new OverlayItems to the ArrayList, you need a new method:
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
Now define the HelloItemizedOverlay constructors. The constructor must define the default marker for each of the OverlayItems. In order for the Drawable to actually get drawn, it must have its bounds defined.
3. Override the following methods
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
4. Implement the Marker in the map activity
1. Get the Overlay as a list from mapview
List<Overlay> mapOverlays = myMapView.getOverlays()
2. Instantiate the following class
Drawable with marker icon
Drawable drawable = this.getResources().getDrawable(R.drawable.pinicon);
Marker with Drawable object
MyMapMarker itemizedoverlay = new MyMapMarker(drawable,this);
OverlayItem with geopoint
OverlayItem overlayitem = new OverlayItem(geoPoint, "Info",
"Selected City is" + city);
3. All that's left is to add this OverlayItem to your collection, then add the MainActivity to the MapView:
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
Sample Source
public class MyMapMarker extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public MyMapMarker(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public MyMapMarker(Drawable defaultMarker, Context context) {
this(defaultMarker);
mContext = context;
}
public void addOverlay(OverlayItem item) {
mOverlays.add(item);
populate();
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
}
Friday, March 12, 2010
Androind JSON Parser
In this blog explain the steps to parse JSON object in android. We are discuss the following items
Overview of JSON
Syntax of JSON
Android JSON Support
Steps to Parse JSON data
Sample Application
Overview of JSON [JavaScript Object Notation]
Lightweight data-interchagable format
Text format that is completely language independent
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Syntax of JSON
Object {name1 : Value1 , name2 : Value2 , name3 : Value3 } -Normal Object Collection
Object [{name1_1 : Value , name1_2 : Value1 , name1_3 : Value2 }
{name2_1 : Value , name2_2 : Value1 , name2_3 : Value2 } ] - Array Based
Example :
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Android JSON Support
Android already contains the required JSON libraries. The Following class are used to parse the JSON Object.
JSONArray A JSONArray is an ordered sequence of values.
JSONObject A JSONObject is an unordered collection of name/value pairs.
JSONStringer JSONStringer provides a quick and convenient way of producing JSON text.
JSONTokener A JSONTokener takes a source string and extracts characters and tokens from it.
Steps to Parse JSON data
1. Create a JSON Object and Convert JSONString to JSON Object
JSONObject jObject = new JSONObject(jsonString);
2. Create a Key based JSONObject.
JSONObject menuObject = jObject.getJSONObject("menu");
3. Get the Value
Log.d("ID", menuObject.getString("id"));
Log.d("Value ", menuObject.getString("value"));
Sample Application
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String myJsonContent = "{\"menu\": {\"id\": \"file\",\"value\": \"File\",\"popup\": {\"menuitem\": [{\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},{\"value\": \"Open\",\"onclick\": \"OpenDoc()\"},{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
sampleJsonParser(myJsonContent);
}
public void sampleJsonParser(String jsonString) {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONObject menuObject = jObject.getJSONObject("menu");
Log.d("ID", menuObject.getString("id"));
Log.d("Value ", menuObject.getString("value"));
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
Log.d("Name", menuitemArray.getJSONObject(i).getString("value")
.toString());
Log.d("Value", menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Overview of JSON
Syntax of JSON
Android JSON Support
Steps to Parse JSON data
Sample Application
Overview of JSON [JavaScript Object Notation]
Lightweight data-interchagable format
Text format that is completely language independent
JSON is built on two structures:
* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Syntax of JSON
Object {name1 : Value1 , name2 : Value2 , name3 : Value3 } -Normal Object Collection
Object [{name1_1 : Value , name1_2 : Value1 , name1_3 : Value2 }
{name2_1 : Value , name2_2 : Value1 , name2_3 : Value2 } ] - Array Based
Example :
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Android JSON Support
Android already contains the required JSON libraries. The Following class are used to parse the JSON Object.
JSONArray A JSONArray is an ordered sequence of values.
JSONObject A JSONObject is an unordered collection of name/value pairs.
JSONStringer JSONStringer provides a quick and convenient way of producing JSON text.
JSONTokener A JSONTokener takes a source string and extracts characters and tokens from it.
Steps to Parse JSON data
1. Create a JSON Object and Convert JSONString to JSON Object
JSONObject jObject = new JSONObject(jsonString);
2. Create a Key based JSONObject.
JSONObject menuObject = jObject.getJSONObject("menu");
3. Get the Value
Log.d("ID", menuObject.getString("id"));
Log.d("Value ", menuObject.getString("value"));
Sample Application
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String myJsonContent = "{\"menu\": {\"id\": \"file\",\"value\": \"File\",\"popup\": {\"menuitem\": [{\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},{\"value\": \"Open\",\"onclick\": \"OpenDoc()\"},{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
sampleJsonParser(myJsonContent);
}
public void sampleJsonParser(String jsonString) {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONObject menuObject = jObject.getJSONObject("menu");
Log.d("ID", menuObject.getString("id"));
Log.d("Value ", menuObject.getString("value"));
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
Log.d("Name", menuitemArray.getJSONObject(i).getString("value")
.toString());
Log.d("Value", menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Some Activity Style
In this article discuss some activity sytle
1. Create Title-less Activity
2. Create a Full Screen Activity
Create Title-less Activity
We can remove the title bar for every activity. The Following method used to remove the title. this method must be call before the setContentView().
requestWindowFeature(Window.FEATURE_NO_TITLE);
Sample SourceCode
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
}
}
Create a Full Screen Activity
We can hide the title bar and windows bar. The following lines are used to hide the title and window bar
Sample SourceCode
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
Toast.makeText(this, "Welcome to Application", Toast.LENGTH_LONG)
.show();
}
}
Android - disable landscape mode - Disable screen Orientation
the following code shows how to disable the screen orientation in android
Add android:screenOrientation="portrait" to the activity in the AndroidManifest.xml. For example:
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">

1. Create Title-less Activity
2. Create a Full Screen Activity
Create Title-less Activity
We can remove the title bar for every activity. The Following method used to remove the title. this method must be call before the setContentView().
requestWindowFeature(Window.FEATURE_NO_TITLE);
Sample SourceCode
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
}
}
Create a Full Screen Activity
We can hide the title bar and windows bar. The following lines are used to hide the title and window bar
Sample SourceCode
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
Toast.makeText(this, "Welcome to Application", Toast.LENGTH_LONG)
.show();
}
}
Android - disable landscape mode - Disable screen Orientation
the following code shows how to disable the screen orientation in android
Add android:screenOrientation="portrait" to the activity in the AndroidManifest.xml. For example:
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
Lanuch Application as Startup Application
1. Create a BroadcastReceiver Class and start your Main Activity
2. Set the User Permission for launch your application
3. Configure the Action and catgory in the intent-filter
4. Create a MainActivity
Create a BroadcastReceiver Class and start your Main Activity
This BroadcastReceiver is used to receive the action and start the your main activity
public class StartupActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
Set the User Permission for launch your application
Config the " android.permission.RECEIVE_BOOT_COMPLETED " User Permission in the androidmanifest.xml
Configure the Action and catgory in the intent-filter
Set the following values for android and category
Action : android.intent.action.BOOT_COMPLETED
Category : android.intent.category.DEFAULT
Create a MainActivity
Create a MainActivity and write your logic there
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
}
}
Sample Code
MainActivity.java
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(this, "Welcome to Application", Toast.LENGTH_LONG)
.show();
finish();
}
}
BroadcastReceiver.java
public class StartupActivity extends BroadcastReceiver {
/**
* @see android.content.BroadcastReceiver#onReceive(Context,Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
Androidmanifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest android:versionCode="1" android:versionName="1.0"
package="com.lanuchactivity" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:label="@string/app_name" android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".StartupActivity">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
</manifest>
No comments:
Post a Comment