New adventure

February 5th, 2011 No comments

We just wanted to give a shout out about our new adventure Prolinkd. You can read more about what it is on blog.

Even though we will be launching mobile apps for prolinkd, and hence we will keep learning new things about Android, we would like to invite all our readers to contribute to keep AndroidCompetencyCenter alive.

If you are an android developer and would like to contribute to the posts/articles/tutorials on this blog, then drop me a line on bidwai.sushrut@gmail.com.

Categories: News Tags:

PhoneGap in Android(Eclipse)

July 8th, 2010 7 comments

Prerequisites for System -

1.Java JDK 1.6
2.Eclipse
3.Android sdk package
4.ADT Plug-in for Eclipse with required Android sdk components.
5.Download and unzip Apache ANT and add it to your PATH(if eclipse doesn’t provide you).
6.Download and install Ruby(http://www.ruby-lang.org/en/downloads/), only for windows/linux user,mac OS already has an installed Ruby.

Steps for installing phone-gap-

1.download the latest framework version of PhoneGap from http://github.com/phonegap/phonegap-android.

2.After downloading ‘phonegap-phonegap-android-{dc58c67}’ zip or tar file,unzip and rename it as ‘phonegap-android’ folder.

3.Run the ruby command in ‘phonegap-android’ folder as -

  • To run the command directly in folder -ruby .\droidgap “[android_sdk_path]” [name] [package_name] “[www]” “[path]“
  • To run the command in command prompt(terminal) -ruby ./droidgap “[android_sdk_path]” [name] [package_name] “[www]” “[path]“

parameter description-

  • android_sdk_path -The path to your Android SDK install.
  • name -The name of your application.
  • package_name -The name of your package (For example: com.wissen.sample)
  • www -The path to your www folder. (Where is your HTML, CSS and JS files is all ready present just like copy from iphone app.)
  • path -The path to generate the application. (can not be inside any Eclipse workspace)

You should get a message in your terminal saying completed,which create complete Android application having src,assets,res and AndroidManifest.xml,including lib contain phonegap.jar file which can be use further in your application.

4.Opening the phonegap project in eclipse -
Open the ‘New Android Project’ window in eclipse and select checkbox ‘Create Project form existing source’,given the path of project which is just created by using ruby command and fill up the all necessary information as we fill up for normal android project,press finish to open the application in eclipse.

5.Right click on phonegap.jar under the libs folder and go to Buildpath-> Add to build path.

6.Select proper minimum sdk version in AndroidManifest.xml file.

7.Click on run button in eclipse or using right click on project in package explorer,select Run As Android Application, after successful run,you will see the html content on your android emulator.

Now Easy steps to do further phonegap applications-

1.Create new simple android project in eclipse as shown in following picture-

before

2.Under the android ‘assets‘ folder create new folder ‘www‘ from new menu or right click and new option,like shown in following picture,

before

3.Create new file ‘index.html’ in www folder(you can create html,css and js files here),you can copy phonegap.js file from phonegap framework to access natives in your application, following picture show you the whole idea,

before

4.Write html code in index file for example like this-

before

5.Now Create new folder ‘libs‘ in a project and copy the ‘phonegap.jar‘ file from downloaded phonegap framework or copy from the project which is created using command ‘ruby ./droidgap’ and paste the ‘phonegap.jar’ file under the ‘libs’ folder,like this

before

6.Right click on phonegap.jar under the libs folder and go to Buildpath-> Add to the build path.

7.Open the main activity java class and main class will extends DroidGap instead of extends Activity ,import package com.phonegap.DroidGap from phonegap.jar,                                       like this-import com.phonegap.DroidGap;

8.Also instead of setContentView(R.layout.main);,used super.loadUrl(“file:///android_asset/www/index.html”); , now your activity file must look like this-

before

9.Run the application from the play like image of tool bar or right click on project select Run as Android Application.

before

10.After successful run, project output will look like this-

before

JSON Parsing in android

October 29th, 2009 39 comments

Let’s look at how to parse JSON objects in android

1> First we’ll need an example :

Lets look at a standard example from the json site http://json.org/example.html

     {"menu": {
				  "id": "file",
				  "value": "File",
				  "popup": {
				    "menuitem": [
				      {"value": "New", "onclick": "CreateNewDoc()"},
				      {"value": "Open", "onclick": "OpenDoc()"},
				      {"value": "Close", "onclick": "CloseDoc()"}
				    ]
				  }
				}}

you could either save this in a file or save it in a string…..like I’ve done

2> Android already contains the required JSON libraries

Lets create a JSON Object;

private JSONObject jObject;

and lets our example be a String ,

private String jString = "{\"menu\":	{\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": 	[ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, 	{\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, 	 	{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";

now we have to convert jString to the jObject ,

jObject = new JSONObject(jString); 

Now we have to start extracting the content from jObject ,

Lets extract the menu object by creating a new menu object,

JSONObject menuObject = jObject.getJSONObject("menu");

Now lets extract its atrtibutes ,

String attributeId = menuObject.getString("id");
String attributeValue = menuObject.getString("value");
JSONObject popupObject = menuObject.getJSONObject("popup");

since “popup” is not plainly a String lets extract it to an object ,

3> Now popup contains an array of “menuitem”

So, we’ll have to extract it to a JSONArray,

 JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); 

Since it contains 3 items lets put it in a for loop.

for (int i = 0; i < 3; i++) {
			System.out.println(menuitemArray.getJSONObject(i)
					.getString("value").toString());
			System.out.println(menuitemArray.getJSONObject(i).getString(
					"onclick").toString());
		}

Basically thats it , u should see the output in the DDMS

4> The full code is as below,

import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;

public class JsonParser extends Activity {
	private JSONObject jObject;
	private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\",   \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse() throws Exception {
		jObject = new JSONObject(jString);

		JSONObject menuObject = jObject.getJSONObject("menu");
		String attributeId = menuObject.getString("id");
		System.out.println(attributeId);

		String attributeValue = menuObject.getString("value");
		System.out.println(attributeValue);

		JSONObject popupObject = menuObject.getJSONObject("popup");
		JSONArray menuitemArray = popupObject.getJSONArray("menuitem");

		for (int i = 0; i < 3; i++) {
			System.out.println(menuitemArray.getJSONObject(i)
					.getString("value").toString());
			System.out.println(menuitemArray.getJSONObject(i).getString(
					"onclick").toString());
		}
	}
}

Styles and Themes

October 27th, 2009 No comments

Hello coders,

Lets look at a fairly simple example of creating a transparent theme and how to apply it to a Dialog……

Step 1> Create a colors.xml file in the ‘values’ folder under ‘res’ and add the following line..

<drawable name="transparent">#00000000</drawable>

Step 2> Create a styles.xml file in the ‘values’ folder under ‘res’ and the following lines…

<style name="Transparent">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">
@android:style/Animation.Translucent
</item>
<item name="android:windowBackground">@drawable/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:colorForeground">#fff</item>
</style>

( I guess the tags and attributes are self explanatory …. )

Step 3> Actually thats it……………………

Let’s add this to a dialog…..

Step 4> Create a class with the following lines……

public class DialogBox extends Dialog {

    public DialogBox(Context context, int theme) {
        super(context, theme);
        setContentView(R.layout.dialog);
        okButton = (Button) findViewById(R.id.dialog_OkButton);
        setListeners();
    }
}

(Make sure you create a layout for the dialog )

Step 5> Next create an activity class as follows….

public class T_Temp extends Activity {

    private DialogBox dialog;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dialog = new DialogBox(this, R.style.Transparent);
        dialog.show();
    }
}

When creating the dialog just add the transparent theme ……

Step 6> That’s it …

( don’t forget to add the activity in the android manifest file..)

When you add the widgets and background it will look something like this..

before

Before

after

After

Step 7> Another trick is you can make the background blurred ….

just add the following line in the dialog box…

   getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

Output looks somthing like this…….

blurred

So the final code is:

public class DialogBox extends Dialog {

    public DialogBox(Context context, int theme) {
        super(context, theme);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
        setContentView(R.layout.dialog);
        okButton = (Button) findViewById(R.id.dialog_OkButton);
        setListeners();
    }
}

Play Video

August 18th, 2009 23 comments

Hello,

Here we are going to play a 3gp video in our Android application.

The important point we have to note is that video doesn’t plays when placed in the raw folder.Hence it has to be placed in the SDCARD itself.

So lets begin this interesting topic.

Ok, let us first insert our video:

  • You can get a short 3gp video from net (I got it from http://www.free-3gp-video.com).

  • In eclipse open perspective DDMS(Window –> Open Perspective –> DDMS) .

  • In DDMS perspective open view File Explorer(Window –> Show View –> File Explorer).

  • Also open Device view (Window –> Show View –> Device) and click the emulator you want to use(if emulator is not running then run a emulator with a sdcard option).

  • Then in File Explorer view navigate the tree shown and click sdcard node.

  • There are two buttons on the top right hand side of File Explorer as shown below

push a video onto the sdcard

push a video onto the sdcard

  • Click the button “Push a file onto the device” and in the file chooser navigate and choose the 3gp video.It should appear in the list of sdcard.(If not able to insert, check whether SDCARD is emulated in the emulator , in 1.5 sdk while creating a new Emulator there is a option of sdcard , insert 128M in the textbox next to it).

  • Ok, back to our code, open java perspective(Window –>Show View –> Java) and open layout file Main.xml.

  • Replace the its content with following contents:

<?xml version=”1.0″ encoding=”utf-8″?>
<FrameLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<VideoView
android:id=”@+id/myvideo”
android:layout_gravity=”center”>
</VideoView>
</FrameLayout>

  • Now open your main activity and insert the following in the onCreate method as:

super.onCreate(savedInstanceState);

// set the view to our layout file

setContentView(R.layout.main);
// Video view: to view our video
VideoView video = (VideoView) findViewById(R.id.myvideo);

//set video path to our video(in this case man-cheetah-gazalle.3gp)
video.setVideoPath("/sdcard/man-cheetah-gazelle.3gp");
video.start();

  • Run the application and the video runs as shown below:

Video snapshot

Video snapshot

View site in a new Window(Browser)

August 12th, 2009 2 comments

Hello ,

Ever thought to include a feature in your application where user clicks a link of certain site or your personal website in the about section of the application and it opens the site in a window and when user finished viewing your achievement and clicks back button your application again gets displayed.

We are going to perform this in just two lines.

  • So first we have to create a intent.

As we already know intent is an abstract description of an operation to be performed.

So we are going to use another version of intent which has following format.

public Intent(String action,Uri uri)

Here:

action is the action we intent(i.e the action we want to perform).

uri is the URL on which the above action is to be performed.

create and intent as

Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.wissen.co.in"));

The above intents means that we want the system to perform a View Action on uri “http://www.wissen.co.in” (i.e. To view it).

  • Next start this activity as:

startActivity(viewIntent);

  • The site will open in browser as

Site opens in a new window(browser)
Site opens in a new window(browser)

Creating custom Views

August 12th, 2009 6 comments

Hi All ,

Today we’ll discuss on how to create a canvas using views.

Step 1>

We’ll start off by extending our class by the android.view.View

example:

public class DrawView extends View {
		/**
		 * Constructor
		 */
		public DrawView(Context context) {
			super(context);
		}
	}

Step 2>

Next we’ll use the onDraw() function provided by the View class.

( Tip: In Eclipse Ganymede 3.4.1 ,

use Ctrl+space to see the available methods and select onDraw(…) )

It will look something like this…

public class DrawView extends View {

		/**
		 * Constructor
		 */
		public DrawView(Context context) {
			super(context);
		}

		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
		}
	}

Step 3 >

Lets draw some Text in it..

For that we’ll need the paint class.

Let’s create an object of Paint..

private Paint paint = new Paint();

( Android javadoc :

The Paint class holds the style and color information about how to

draw geometries, text and bitmaps. )

Let’s set its properties..

// set's the paint's colour
paint.setColor(Color.WHITE);
// set's paint's text size
paint.setTextSize(25);
// smooth's out the edges of what is being drawn
paint.setAntiAlias(true);

Step 4>

Let’s draw the actual text…

 canvas.drawText("Hello World", 5 , 30 ,paint); 

The final code will look some thing like this…

public class DrawView extends View {

		private Paint paint;

		/**
		 * Constructor
		 */
		public DrawView(Context context) {
			super(context);

			paint = new Paint();
			// set's the paint's colour
			paint.setColor(Color.GREEN);
			// set's paint's text size
			paint.setTextSize(25);
			// smooth's out the edges of what is being drawn
			paint.setAntiAlias(true);
		}

		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			canvas.drawText("Hello World", 5, 30, paint);
			// if the view is visible onDraw will be called at some point
			// in the future
			invalidate();
		}
	}

Step 5>

Now we need to display this View ….

For that we need to create an activity and set its content view as this DrawView.

One way is to suclass DrawView or create a new class file of DrawView..

The final code looks something like this…

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class temp extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new DrawView(this));
	}

	private class DrawView extends View {

		private Paint paint;
		/**
		 * Constructor
		 */
		public DrawView(Context context) {
			super(context);

			paint = new Paint();
			// set's the paint's colour
			paint.setColor(Color.GREEN);
			// set's paint's text size
			paint.setTextSize(25);
			// smooth's out the edges of what is being drawn
			paint.setAntiAlias(true);
		}

		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			canvas.drawText("Hello World", 5, 30, paint);
			// if the view is visible onDraw will be called at some point in the
			// future
			invalidate();
		}
	}
}

The output looks like..

output

Start Service at boot

June 29th, 2009 34 comments

Hello,

Now we are going to learn how to start a service at boot time, i.e. to start our service when device starts up.

First we have to create a BroadcastReceiver which will be started when boot completes as

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyStartupIntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
}
}

onRecieve will be first called when the BroadcastReceiver MyStartupIntentReceiver starts.

Next make an entry of this receiver in AndroidManifest.xml as

<receiver android:name="MyStartupIntentReceiver">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>

Here in intent filter we have declared the action as android.intent.action.BOOT_COMPLETED , so that this receiver and intent with action android.intent.action.BOOT_COMPLETED

Now this receiver will be intimated when boot completes

Next if we want to start a service then the procedure is as follows

Create a Service as


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {

		return null;

	}

	@Override
	public void onCreate() {
		super.onCreate();

		Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

	}

	@Override
	public void onStart(Intent intent, int startId) {

		super.onStart(intent, startId);

		Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

	}
}

Make an entry of this service in AndroidManifest.xml as

<service android:name="MyService">
<intent-filter>
<action
android:name="com.wissen.startatboot.MyService" />
</intent-filter>
</service>

Now start this service in the BroadcastReceiver MyStartupIntentReceiver’s onReceive method as

	public void onReceive(Context context, Intent intent) {
		Intent serviceIntent = new Intent();
		serviceIntent.setAction("com.wissen.startatboot.MyService");
		context.startService(serviceIntent);

	}

Next you can write the code that you want to execute when device boots up in the BroadcastReceiver or in the Service

Accessing device Sensor’s

June 27th, 2009 1 comment

Hello,

Today we are going to learn how to access  sensor and retrieve data from it.

First, to access device’s sensors we have to use  Class SensorManager(android.hardware.SensorManager). that lets you access the device’s sensors

http://developer.android.com/reference/android/hardware/SensorManager.html

To get SensorManager we have to use getSystemService(ServiceName)

It returns handle to a system level service.Hence we get handle to SensorManager as below

//Declare Sensor Manager class object

private SensorManager mSensorManager;

//Next get the handle to the Sensor service

mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);

Next declare a listener  for receiving notifications from the SensorManager when sensor values have changed as.

private final SensorListener sensorListener = new SensorListener(){
public void onSensorChanged(int sensor, float[] values)
{

//Retrieve the values from the float array values which contains sensor data
Float dataX = values[SensorManager.DATA_X];

Float dataY = values[SensorManager.DATA_Y];

Float dataZ = values[SensorManager.DATA_Z];

//Now we got the values and we can use it as we want

Log.i("X - Value",""+dataX);

Log.i("Y - Value",""+dataY);

Log.i("Z - Value",""+dataZ);

}

public void onAccuracyChanged(int sensor, int accuracy) {}

};

For above listener to be notified of changed value we have to register it . We can register it in onResume as

protected void onResume() {

super.onResume();

mSensorManager.registerListener(sensorListener,
SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_GAME);
}

The syntax of register listener is as

SensorManager.registerListener(SensorListener listener, int sensors, int rate)

We can unregister the sensorlistener in onStop as

protected void onStop() {

super.onStop();

mSensorManager.unregisterListener(sensorListener);
}

Hello Android! – Presentation from talk at Pune GTUG

June 7th, 2009 No comments

We were invited by Pune Google Technology User Group (GTUG) to introduce developers to Android platform for application development. Our presentation went well and developers present liked it. Here is the presentation.

Categories: Android Tags: