Archive

Posts Tagged ‘Android’

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 , , , , ,

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 , ,

T-Mobile G1 Accounting for 20% of UK Contract Sales? | Android Central

March 10th, 2009

AndroidCentral reports that T-Mobile G1 is accounting for 20% sales in UK for T-Mobile. Read the complete report here. So good news for Androiders is that the market is picking up for Android based smart phones in Europe. With rise in sales for Android, we should see more and more cool applications developed on the platform.

By the way, we have been completely busy with few client projects and hence blog took a backseat for almost a month. But good news is we are back!

Mobile Market, News ,

Android Audio Support

February 13th, 2009

Android support Media API as optional APIs. The media APIs provide functionality of playing and recording audio files and video files. In today’s post we will see how to play and record audio files.

Playing Audio File:
Android has defined a MediaPlayer class for playing media file. This class can be used to play the audio files. The class provides static methods to create the instance of the media player. Here is how the MediaPlayer object can be obtained using create methods

MediaPlayer.create(context, Uri.parse("file:///sdcard/audio_file.mp3");

and

MediaPlayer.create(context, R.raw.song_file);

The first create methods gets the Uri for the audio file and can be used to play files present on the phone sdcard. The second create method use the application resource file song_file.mp3. The song_file.mp3 file is added as a raw resource under res/raw directory.
Note that if the MediaPlayer object does not get created successfully, the create methods will return null so it will be better to check for the return object for null value to avoid NullPointer exception.

The MediaPlayer object can also be obtained by instantiating using MediaPlayer constructor. The object created like this has to be initialized with the file that needs to be played. setDataSource() method can be used to initialize the object with the audio file.

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

If you want to send the media player object with one of the files from application raw resources or from application assets files you can do that as follows:

try {
AssetFileDescriptor fd = getResources().openRawResouceFd(R.raw.song_file);
mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
fd.close();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

The MediaPlayer object has to be prepared before the player can start playing the song. The prepare() method is the blocking method and blocks until the media player is ready to play the song. One non blocking method prepareAsync() is also provided. The non blocking prepare method should be used in case media player is used to play a song from a stream and need to buffer data before song can be played. The create methods that we saw earlier call the prepare() method and application must not call it again. To start file playback use start() method. This is how you play a file:

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

mediaPlayer.start();

The file playback can be pause with pause() method, and can be resumes with start method. The file playback can be stopped with stop() method. The media player object has to reset before it can be setup for some other song file. The media player object has to be released after its use.

Android Media API defines some listeners like OnCompletionListener, OnPrepareListener, OnErrorListener, OnBufferingUpdateListener
OnCompletionListener event gets fired when media player complete the playing of the current audio file. You can use this listener event for playing next song from the list or releasing the media player object.

OnPrepareListener is needed when prepareAsync method is used. Since the prepareAsync method does not block for the call duration, the application can not start playing the song. The onPrepared() event function will be called once the media player is ready. You can start playing the song in the onPrepared() method.

OnErrorListener is also used in case of asynchronous operations. If any error occurs in asynchronous operation, onError() method of this listener will be called.

Recording Audio Files:

The Media API also provides functionality to record audio files. The MediaRecorder class can be used for media recording. The MediaRecorder has to be initialized with the Audio Encoder, output format (codec to be used for recorded file), Audio Source (like Microphone) and output file path where the recorded file will be stored. Here is how recording can be done:

MediaRecorder recorder = new MediaRecorder();

recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

recorder.setOutputFile(filePath); // complete file path

recorder.prepare(); recorder.start();

This will start the recording the recording can be stored with stop() method. The MediaRecorder object also needs to be release after its use.
That all for today’s post. We will see Media APIs Video support in some other post.

Android, Android API , , , , ,