Archive

Archive for the ‘Android’ Category

JSON Parsing in android

October 29th, 2009

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());
		}
	}
}

Android, Android API, Mobile Market , , , , , , ,

Styles and Themes

October 27th, 2009

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();
    }
}

Android, Mobile Market , , , , , , , , , , , ,

Play Video

August 18th, 2009

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

Android , , , , , , , , , , ,

View site in a new Window(Browser)

August 12th, 2009

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)

Android , , , , , , , , ,

Creating custom Views

August 12th, 2009

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

Android , , , , , , , ,

Start Service at boot

June 29th, 2009

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

Android , , , ,

Accessing device Sensor’s

June 27th, 2009

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);
}

Android , , , , ,

Hello Android! – Presentation from talk at Pune GTUG

June 7th, 2009

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.

Android

Book – Inviting suggestions and contributions

May 20th, 2009

Thanks to all our readers and the overwhelming response we have got for the blog.
We have decided to take things to the next level and publish a book which can get a newbie Android developer started. The book will contain all the tutorials for basic stuff. IT will also contain lot of advance tutorials, introduction to various tools, goodies and source code for lot of sample applications.
If you have specific suggestions or want us to talk about any particular API/Tool in this book, then give us a shout.
If you want to contribute to the book by coming up with tutorials, then give us shout too!
Looking for support for all of our readers!
Also suggest us some good name for the book!

Android , ,

Activate android mobile without activation key

April 21st, 2009

You can activate Android mobile without activation key. After that you can easily access Internet or can
insert your sim card. Just follow the steps given:

1. You need android SDK first. You can get android SDK zip easily: http://developer.android.com/sdk/1.1_r1/index.html

2. Connect your android mobile phone to PC.

3. Get a driver for android mobile from site: http://modmygphone.com/wiki/index.php/Setting_up_ADB. Install this driver.

4. Open DOS prompt, goto android mobile SDK’s tool folder.

5. Enter a command: adb -d shell

6. In the shell, become root and modify settings.db to remove the “no sim card found” screen lock:
$ su
$ sqlite3 /data/data/com.android.providers.settings/databases/settings.db
sqlite> INSERT INTO system (name, value) VALUES (‘device_provisioned’, 1);
sqlite> .quit
#

7. Reboot the phone.

8. Reconnect with the adb shell and launch the settings activity (does not require root):
$ adb shell
$ am start -a android.intent.action.MAIN -n com.android.settings/.Settings

9. Using the settings activity that you’ve launched on the phone’s screen, enable wifi.

10. Activate the phone with a gmail account. You can insert your SIM card now.

Join the forum discussion on this post - (1) Posts

Android