Getting started with Android Wear!

Hello everyone!

Android wear is a platform developed by Google for wearable devices. It was launched in the month of March 2014 as a developer preview along with partner companies such as Motorola, Samsung, LG etc. Android Wear is basically an operating system designed primarily for smartwatches and other wearables. It integrates Google Now functionality and mobile notifications into the screen of a wearable device.

Through this post, we will learn how to get started with using Android Wear. We would be creating a sample program to display wearable style notifications!

Pre-requisites: Eclipse IDE, Android SDK (Target SDK: Android 4.4W)

Step 1: Download Android Wear SDK

In order to start creating wearable applications, one needs to download and install the Wearable SDK. Launch the SDK Manager application and download the latest version of the SDK.

sdk_manager

Step 2: Create new Android Wear project

Create a new Android application project called AndroidWearHelloWorld with package name com.app.hellowear. Choose the target SDK as Android 4.4W.

Next, add the following code in your Activity class.

MainActivity.java


import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.app.NotificationManagerCompat;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);	
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);


        // Create a big text style for the notification
        NotificationCompat.BigTextStyle notificationPageStyle = new NotificationCompat.BigTextStyle();
        secondPageStyle.setBigContentTitle("Test Message!")
        .bigText("This is a really long message...");

        PendingIntent actionPendingIntent =
                PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class),
                        PendingIntent.FLAG_CANCEL_CURRENT);

        // Create the action
        NotificationCompat.Action action =
                new NotificationCompat.Action.Builder(R.drawable.ic_launcher,
                        getString(R.string.test), actionPendingIntent)
                        .build();

        // Build the notification and add the action via WearableExtender
        Notification wearableNotification =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setStyle(notificationPageStyle)
                        .extend(new WearableExtender().addAction(action))
                        .build();
        
        notificationManagerCompat.notify(2, wearableNotification);

	}
 }

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AndroidWearHelloWorld</string>
    <string name="hello_world">Go to notification screen</string>
    <string name="test">You have a new message!</string>   
</resources>

Finally, save all changes and run the application on an Android Wear compatible virtual device. If no errors occur then you should see the following output!

output_1

output_2

Lot’s more on Android Wear in my upcoming posts. Stay tuned! :)

Reference: Android Wear Notifications

Tutorial #86: Implement face detection in Android

Hey friends!

Face Detection is one of the most common image processing applications. Prior to Android 4.0 (Ice Cream Sandwich) developers would use third party libraries in order to implement the face detection functionality. Today, one can easiliy identify different faces with the help of certain pre-defined functions.

The Camera class in Android now provides the startFaceDetection method to initiate face detection on an Android phone. As mentioned on the developer’s page, once the method has been called the camera will notify Camera.FaceDetectionListener of the detected faces in the preview frame. Moreover, the startFaceDetection method is supported only if getMaxNumDetectedFaces() returns a number larger than zero.

Through this tutorial, we will learn how to implement face detection in Android. We would be displaying the number of faces detected by using a sample image.

Pre-requisites: Eclipse IDE, Android SDK (Target SDK: Android 4.0 and above)

Step 1: Create new Android project

Launch Eclipse IDE and create a new Android application project called AndroidFaceDetectionDemo with package name com.app.facedetection.

Step 2: Create new Activity class

In order to implement face detection, we need to basically access the device camera. Let’s create an Activity class called FaceDetectionActivity that implements the same.

FaceDetectionActivity.java

package com.app.facedetection;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("InflateParams")
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class FaceDetectionActivity extends Activity implements SurfaceHolder.Callback{

	private Camera camera;
	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHolder;
	boolean preview = false;
	private LayoutInflater layoutInflater = null;
	private Button btnTakePicture;
	private TextView txtFaceCount;
	private TextView txtImagePath;

	final int RESULT_SAVEIMAGE = 0;

	/** Called when the activity is first created. */
	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_facedetection);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		getWindow().setFormat(PixelFormat.UNKNOWN);
		surfaceView = (SurfaceView)findViewById(R.id.camPreview);
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		txtFaceCount = (TextView)findViewById(R.id.tvFaceCount);
		txtImagePath = (TextView)findViewById(R.id.tvImagePath);
		
		layoutInflater = LayoutInflater.from(getBaseContext());
		View viewControl = layoutInflater.inflate(R.layout.picture_control, null);
		LayoutParams layoutParamsControl
		= new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		this.addContentView(viewControl, layoutParamsControl);

		btnTakePicture = (Button)findViewById(R.id.takepicture);
		btnTakePicture.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				camera.takePicture(mShutterCallback,
						mRawPictureCallback, mJPGPictureCallback);
			}});

		LinearLayout layoutBackground = (LinearLayout)findViewById(R.id.linearLayout);
		layoutBackground.setOnClickListener(new LinearLayout.OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				btnTakePicture.setEnabled(false);
				camera.autoFocus(mAutoFocusCallback);
			}});


	}

	@SuppressLint("NewApi")
	FaceDetectionListener faceDetectionListener
	= new FaceDetectionListener(){

		@Override
		public void onFaceDetection(Face[] faces, Camera camera) {

			if (faces.length == 0){
				Toast.makeText(getApplicationContext(), "No face detected..!", Toast.LENGTH_SHORT).show();
			}else{

				txtFaceCount.setText("Number of Faces Detected:" + " " +String.valueOf(faces.length));
			}


		}};

	AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(){

		@Override
		public void onAutoFocus(boolean arg0, Camera arg1) {
				// TODO Auto-generated method stub
				btnTakePicture.setEnabled(true);
		}};

		ShutterCallback mShutterCallback = new ShutterCallback(){
			@Override
			public void onShutter() {
					// TODO Auto-generated method stub

		}};

		PictureCallback mRawPictureCallback = new PictureCallback(){

		@Override
		public void onPictureTaken(byte[] arg0, Camera arg1) {
						// TODO Auto-generated method stub

		}};

		PictureCallback mJPGPictureCallback = new PictureCallback(){

		@Override
		public void onPictureTaken(byte[] arg0, Camera arg1) {
			// TODO Auto-generated method stub	
			
				try {
								
						int imageNum = 0;
		      
						Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					    File imagesFolder = new File(Environment.getExternalStorageDirectory(), "FaceDetection");
					    if (!imagesFolder.exists()) {
					        imagesFolder.mkdirs();
					    }
				        
					    String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
					    File output = new File(imagesFolder, fileName);
					        
						   while (output.exists()){
						       imageNum++;
						       fileName = "image_" + String.valueOf(imageNum) + ".jpg";
						       output = new File(imagesFolder, fileName);
						   }
				       
					    Uri uriSavedImage = Uri.fromFile(output);
					    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
	
					    OutputStream imageFileOS;
					       
					    imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
					    imageFileOS.write(arg0);
					    imageFileOS.flush();
					    imageFileOS.close();
	
						txtImagePath.setText("Image saved to:" + " " +uriSavedImage.toString());
					
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					camera.startPreview();
					camera.startFaceDetection();
			}};

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
			  // TODO Auto-generated method stub
			 if(preview){
					camera.stopFaceDetection();
					camera.stopPreview();
					preview = false;
			  }

			if (camera != null){
					try {
					camera.setPreviewDisplay(surfaceHolder);
					camera.startPreview();	
					camera.startFaceDetection();
					preview = true;
					} catch (IOException e) {
						// TODO Auto-generated catch block
					   e.printStackTrace();
					}
				}
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				camera = Camera.open();
				camera.setFaceDetectionListener(faceDetectionListener);
			}

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				camera.stopFaceDetection();
				camera.stopPreview();
				camera.release();
				camera = null;
				preview = false;
			}
}

picture_control.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="bottom"
    android:orientation="vertical" >

    <Button
        android:id="@+id/takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="@string/click_picture" />

</LinearLayout>

activity_facedetection.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/app_name" />

    <TextView
        android:id="@+id/tvFaceCount"
        android:textSize="15sp"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
    <TextView
        android:id="@+id/tvImagePath"
        android:textSize="15sp"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <SurfaceView
        android:id="@+id/camPreview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AndroidFaceDetection</string>
    <string name="click_picture">*Take Picture</string>
</resources>

Note: Make sure you add the below permissions in your project’s AndroidManifest.xml file.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 3: Run on device

Finally, save all changes and run the application on an Android device. If no errors occur then you should see the following output! :)

output_1

output_2

Reference: Android Camera

Using command line shell for SQLite in Android

Hello everyone!

The SQLite library is a crucial part of the Android environment. It is a light weight database that allows storage of user and application data. Moreover, SQLite is ACID-compliant and implements most of the SQL standard, using a dynamically and weakly typed SQL syntax.

The SQLite project provides a simple command-line utility named sqlite3 (or sqlite3.exe on windows) that allows a user to manually enter and execute SQL statements against an SQLite database. Through this post, we will learn how to use the sqlite3 program to create a new database.

Pre-requisites: Android SDK, Windows 7 (64 bit)

Open an instance of the command prompt and navigate to the platform-tools folder present within the Android SDK bundle.

Step 1: Create a new database

create_database

In order to create a new SQLite database, we need to execute the following command.

sqlite3 Employee.db

Step 2: Create new table and insert records

We can use the standard CREATE TABLE SQL statement in order to create a new table as follows!

create table Employee(EmpId int primary key, EmpName varchar(50));

Now, let’s insert a few records in the above table.

insert into Employee values('101','ashish');
insert into Employee values('102','ajay');

create_table_insert_rows

Step 3: Dump/Print contents of table

As mentioned on the Android developer’s page, the sqlite3 tool includes many useful commands, such as .dump to print out the contents of a table and .schema to print the SQL CREATE statement for an existing table.

Finally, let’s look at the .dump command that will generate a .sql file as follows!

sqlite3 Employee.db .dump > Employee.sql

Employee.sql

PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE Employee(EmpId int primary key, EmpName varchar(50));
INSERT INTO "Employee" VALUES(101,'ashish');
INSERT INTO "Employee" VALUES(102,'ajay');
COMMIT;

That’s it for this Android tip. Hope it helps! :)

Reference: Command Line Shell for SQLite

Implement spell checker in Android

Hi everyone!

Spell check is of the most common programs used to identify words in a document that may not be spelled correctly. Today, one need not carry a dictionary to self spell check. The age of mobile technology has given rise to a number of applications that incorporate the spell checking functionality.

Android offers developers a spelling checker framework. In order to implement the spell checking feature, developers need to make use of the SpellCheckerSessionListener interface. The interface provides callbacks for getting results from text services. Through this post, we will learn how to implement a spell checker application in Android.

Pre-requisites: Android SDK, Eclipse IDE

Create a new Activity class called TestSpellCheckerActivity in any of your existing Android projects and add the following code!

TestSpellCheckerActivity.java

package com.app.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.textservice.SentenceSuggestionsInfo;
import android.view.textservice.SpellCheckerSession;
import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
import android.view.textservice.SuggestionsInfo;
import android.view.textservice.TextInfo;
import android.view.textservice.TextServicesManager;
import android.widget.EditText;
import android.widget.TextView;

public class TestSpellCheckerActivity extends Activity implements SpellCheckerSessionListener {
	
	private TextView txtSpellCheck;
	private SpellCheckerSession btnChecker;
	private EditText etWord;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_spellcheck);
		txtSpellCheck = (TextView)findViewById(R.id.txtLabel);
		etWord = (EditText)findViewById(R.id.etWord);
	}

	@Override
	public void onResume() {
		super.onResume();
		final TextServicesManager tsm = (TextServicesManager) getSystemService(
				Context.TEXT_SERVICES_MANAGER_SERVICE);
		btnChecker = tsm.newSpellCheckerSession(null, null, this, true);         
	}

	@Override
	public void onPause() {
		super.onPause();
		if (btnChecker != null) {
			btnChecker.close();
		}
	}

	@SuppressWarnings("deprecation")
	public void getSuggestions(View view){
		btnChecker.getSuggestions(new TextInfo(etWord.getText().toString()), 3);
	}
	
	@Override
	public void onGetSuggestions(final SuggestionsInfo[] arg0) {
		final StringBuilder sb = new StringBuilder();

		for (int i = 0; i < arg0.length; ++i) {
			
			final int len = arg0[i].getSuggestionsCount();
			sb.append('\n');
			for (int j = 0; j < len; ++j) {
				sb.append("," + arg0[i].getSuggestionAt(j));
			}
			
		}
		runOnUiThread(new Runnable() {

			public void run() {
				txtSpellCheck.append(sb.toString());
			}
		});

	}
	
	@Override
	public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
		// TODO Auto-generated method stub

	}
}

activity_spellcheck.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/etWord"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/instruction">
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnSuggest"
        android:layout_width="150dip"
        android:layout_height="50dip"
        android:onClick="getSuggestions"
        android:text="@string/spell_check"/>

    <TextView
        android:id="@+id/txtLabel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/suggestions"/>

</LinearLayout>

strings.xml

 <string name="spell_check">Spell Check</string>
 <string name="suggestions">Suggestions</string>
 <string name="instruction">Enter any text</string>

Save all changes. Make sure no errors are present. Run the application on an Android device and you should see the following output!

output_1

output_2

Reference: Android SuggestionsInfo

The way of life!

Sometimes when you feel you are at your best; everything is falling right into place, life hits you hard and puts you back in the race! :)

At 24, I might be the best person for the job, the most loving son or the most helpful person but when I encounter reality, the feeling just nullifies. As a person, I always want to excel, success is what I crave for, passion is what drives me; even then I could never learn the way of life.

Back then, personal hygiene is something I never paid attention too. You often hear your parents tell you to wipe your body clean after a shower, cut your nails on time, wash your hands before a meal, tighten your shoelaces and so on. Trust me these small things have a big impact on life. Cooking is something I could never learn but criticizing the cook brought a smile to my face. Household chores? Who does that anyway? The fact is that I never learnt things – the hard way.

Was there anything that could have brought about a change in me? Perhaps yes and one such incident indeed did. I was travelling home via the CST-bound local, glued to my headphones seated near the window. It was pouring heavily and in order to avoid water from entering the compartment, people would normally shut the windows by pulling down the glass case. Suddenly, an old man, who sat in front of me asked me to pull down the window. As usual, I responded late and when I tried pulling it down, I couldn’t. I just didn’t know how to do it. At the end, the old man had to get up and pull the window down himself. Till the time I reached home my eyes were filled with tears. Something had hit me hard – mentally. Life had just taught me the best lesson. Today, even after several years the old man’s words echo in my mind. I remember he said, “Look at this guy wearing headphones. He doesn’t even know how to close a window!!”

Times have changed. For a person who never knew how to use a pen to a person who is on the verge of completing his second book, life has always challenged every move of mine. All I do is try and live up to those. Remember, no matter who you are, rich or poor, near or far, never neglect the basic things of life. Learn to respect life and it will respect you!

Hello World using OpenCV and Qt

Hello everyone!

Qt is one of the popular cross-platform application and UI frameworks allowing developers to incorporate both GUI and Non-GUI based features within their applications. The Qt SDK also helps in developing cross-platform OpenCV applications. The Qt Creator IDE is a tool that can be used to write, debug and execute programs. On the other hand, OpenCV as you might be aware is a well known image processing library. The combination of Qt and OpenCV is something that has attracted the attention of developers worldwide.

Through this post, we will learn how to write a simple Hello World application using OpenCV and Qt.

Pre-requisites: Windows 7 (64 bit), Qt Creator based on Qt 5.2.0, OpenCV

Step 1: Configure Qt for using OpenCV

In case you have not configured Qt for using OpenCV, I would recommend reading this presentation for setting up your Qt environment. Once you have configured your environment, you can proceed to the next step.

Step 2: Create a new Qt Project

Launch the Qt Creator IDE and create a new Qt console Application with the name OpenCV_HelloWorld. Choose the compiler (MinGW or Visual Studio) of your choice and proceed. Now, write the following code in your main.cpp file.

main.cpp

#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;

int main(int argc, char** argv){

    namedWindow("output",1);
    Mat output = Mat::zeros(120,350,CV_8UC3);
    putText(output,"Hello world :)", cvPoint(15,70), FONT_HERSHEY_PLAIN,3,cvScalar(0,255,0),4);
    imshow("Output",output);
    waitKey(0);
    return 0;

}

Step 3: Add path to OpenCV libraries

In order for Qt to make use of OpenCV, we need to include the path to the libraries in the Qt project (.pro) file as follows.

QT       += core

QT       -= gui

TARGET = OpenCV_HelloWorld
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp
INCLUDEPATH += F://softwares//opencv//opencv//sources//release//install//include

Finally, run qmake and build the project. Make sure no errors occur. If everything runs fine then you should see the following output!

qt_opencv_helloworld

So that’s it for this Qt tip. A lot more still to come! :)

Tutorial #85: Fetch data from WordPress posts using JSON API

Hello everyone!

I recently helped a friend of mine setup his own blog using WordPress. It feels great to see people slowly moving towards blogging. WordPress is one of the popular content management systems out there that make blogging a lot easier. It provides the ability to not only assign multiple categories to articles but also support for tagging of posts and articles.

As a developer, one can use the JSON API to fetch the data related to a post published on WordPress. The API is basically a WordPress plugin that allows you to retrieve and manipulate WordPress content using HTTP requests. For example, one could fetch all posts tagged “java” by executing an HTTP GET request to the following URL.


http://www.example.org/?json=get_tag_posts&tag_slug=java

Through this post, we will learn how to fetch data from WordPress posts using the JSON API.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Installing JSON API plugin

Here I assume you already have a live WordPress website. Login to your WordPress account and install the JSON API plugin. Once installed, activate the plugin.

Step 2: Fetch data from WordPress post

Launch Eclipse IDE and create a new Android application project called AndroidWordPressDemo with package name com.app.wordpress. Create a new Activity class called FetchDataActivity and add the following code!

FetchDataActivity.java

package com.app.wordpress;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FetchDataActivity extends Activity {

	private Button btnSubmit;
	private final static String URL = "http://www.karanbalkar.com/api/get_tag_posts/?tag_slug=sdcard";
	private TextView tvPostCount, tvPostTitle, tvPostUrl;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tvPostCount = (TextView)findViewById(R.id.txtPostCount);
		tvPostTitle = (TextView)findViewById(R.id.txtPostTitle);
		tvPostUrl = (TextView)findViewById(R.id.txtPostUrl);


		btnSubmit = (Button)findViewById(R.id.btnSubmit);
		btnSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new FetchDataTask().execute(URL);
			}
		});

	}

	private class FetchDataTask extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			InputStream inputStream = null;
			String result= null;
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(params[0]);

			try {

				HttpResponse response = client.execute(httpGet);
				inputStream = response.getEntity().getContent();

				// convert inputstream to string
				if(inputStream != null){
					result = convertInputStreamToString(inputStream);
					Log.i("App", "Data received:" +result);

				}
				else
					result = "Failed to fetch data";

				return result;

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(String dataFetched) {
			//parse the JSON data and then display
			parseJSON(dataFetched);
		}


		private String convertInputStreamToString(InputStream inputStream) throws IOException{
			BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
			String line = "";
			String result = "";
			while((line = bufferedReader.readLine()) != null)
				result += line;

			inputStream.close();
			return result;

		}

		private void parseJSON(String data){

			try{

				JSONObject jsonResponse = new JSONObject(data);
				JSONArray jsonMainNode = jsonResponse.optJSONArray("posts");
				int postCount = Integer.parseInt(jsonResponse.getString("count"));

				int jsonArrLength = jsonMainNode.length();  

				for(int i=0; i < jsonArrLength; i++) {
		
					JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
					String postTitle = jsonChildNode.getString("slug");
					String postUrl = jsonChildNode.getString("url");
				
					tvPostCount.setText("Number of posts:" +postCount);
					tvPostTitle.setText("Page title:" +postTitle);
					tvPostUrl.setText("Page URL:" +postUrl);
				}
				
			}catch(Exception e){
				Log.i("App", "Error parsing data" +e.getMessage());

			}
		}
	}

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/txtView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtView1"
        android:text="@string/fetchData" />

    <TextView
        android:id="@+id/txtPostTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnSubmit" />

    <TextView
        android:id="@+id/txtPostCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtPostTitle" />

    <TextView
        android:id="@+id/txtPostUrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtPostCount" />

</RelativeLayout>

Note: Make sure you add the below INTERNET permission in your AndroidManifest.xml file.

 <uses-permission android:name="android.permission.INTERNET" />

Finally, save all changes. Make sure no errors are present and run the application on an Android device. Click on the button to view the corresponding output! :)

output

That’s it for this tutorial. Hope it helps. Stay tuned for more! :)

Record audio using MediaRecorder in Android

Hi everyone!

More often than not, you might have come across Android applications that allow users to record memos, meetings and more. The quality of audio plays an important role in such applications. Recordings can also be saved and played later. Audio capture from an Android device is a bit more complicated than audio and video playback.

The MediaRecorder class is used to record audio and video. Through this post, we will learn how to record audio from a device microphone, save the audio and play it back.

Pre-requisites: Eclipse IDE, Android SDK

Create a new Activity class called RecordAudioActivity in any of your existing Android projects and add the following code!

RecordAudioActivity.java

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class RecordAudioActivity extends Activity {

   private MediaRecorder mMediaRecorder;
   private MediaPlayer mPlayer;
   private String outputFile = null;
   private Button btnRecordStart;
   private Button btnRecordStop;
   private Button btnPlay;
   private Button btnStopPlay;
   private TextView mRecordStatus;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_audio);
      
      mRecordStatus = (TextView) findViewById(R.id.tv_recordStatus);
   
      // store it to sd card
      outputFile = Environment.getExternalStorageDirectory().
    		  getAbsolutePath() + "/sampleAudioRecord.3gpp";

      mMediaRecorder = new MediaRecorder();
      mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
      mMediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
      mMediaRecorder.setOutputFile(outputFile);
      
      btnRecordStart = (Button)findViewById(R.id.start);
      btnRecordStart.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			start(v);
		}
      });
      
      btnRecordStop = (Button)findViewById(R.id.stop);
      btnRecordStop.setOnClickListener(new OnClickListener() {
  		
  		@Override
  		public void onClick(View v) {
  			// TODO Auto-generated method stub
  			stop(v);
  		}
      });
      
      btnPlay = (Button)findViewById(R.id.play);
      btnPlay.setOnClickListener(new OnClickListener() {
  		
  		@Override
  		public void onClick(View v) {
  			// TODO Auto-generated method stub
				play(v);	
  		}
      });
      
      btnStopPlay = (Button)findViewById(R.id.stopPlay);
      btnStopPlay.setOnClickListener(new OnClickListener() {
  		
  		@Override
  		public void onClick(View v) {
  			// TODO Auto-generated method stub
  			stopPlay(v);
  		}
      });
   }

   public void start(View view){
	   try {
          mMediaRecorder.prepare();
          mMediaRecorder.start();
       } catch (IllegalStateException e) {
          e.printStackTrace();
       } catch (IOException e) {
          
           e.printStackTrace();
        }
	   
       mRecordStatus.setText("Record status: now recording");
       btnRecordStart.setEnabled(false);
       btnRecordStop.setEnabled(true);
       
     
   }

   public void stop(View view){
	   try {
	      mMediaRecorder.stop();
	      mMediaRecorder.release();
	      mMediaRecorder  = null;
	      
	      btnRecordStop.setEnabled(false);
	      btnPlay.setEnabled(true);
	      mRecordStatus.setText("Record status: Stopped recording");
	      
	     
	   } catch (IllegalStateException e) {
			e.printStackTrace();
	   } catch (RuntimeException e) {
			e.printStackTrace();
	   }
   }
  
   public void play(View view) {
	   try{
		   mPlayer = new MediaPlayer();
		   mPlayer.setDataSource(outputFile);
		   mPlayer.prepare();
		   mPlayer.start();
		   
		   btnPlay.setEnabled(false);
		   btnStopPlay.setEnabled(true);
		   mRecordStatus.setText("Record status: Playing audio");
		   
		 
	   } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
   }
   
   public void stopPlay(View view) {
	   try {
	       if (mPlayer != null) {
	    	   mPlayer.stop();
	           mPlayer.release();
	           mPlayer = null;
	           btnPlay.setEnabled(true);
	           btnStopPlay.setEnabled(false);
	           mRecordStatus.setText("Record status: stopped playing");
	           
	           
	       }
	   } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
   }

}

activity_audio.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_recordStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Record status:" />

    <ImageView
        android:id="@+id/iv_Microphone"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_below="@+id/text1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:src="@drawable/audio_record" />

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/micImage"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="start" />

        <Button
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:enabled="false"
            android:text="stop" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linear1"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:text="play" />

        <Button
            android:id="@+id/stopPlay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:enabled="false"
            android:text="stop playing" />
    </LinearLayout>

</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    
    <application
        android:allowBackup="true"
        android:configChanges="orientation|keyboardHidden"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="com.app.test.RecordAudioActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>     
        </activity>     
    </application>
</manifest>

In order to record audio, we first need to create an instance of the MediaRecorder class. We then need to set the microphone as the audio source and specify the format and name of the output file. The methods prepare(), start(), stop() and release() are called in respective order for playing/stopping of media content.

Save all changes and make sure no errors are present. Run the application on an Android device and you should see the following output!

output_1

output_2

output_3

Reference: Android audio capture

Using Proximity sensor in Android

Hello everyone!

The term proximity is basically the fact, condition or position of being near or close by in space. A proximity sensor is a device capable of detecting presence of nearby objects without any physical contact. Some of the Android phones in the market today come equipped with a proximity sensor.

Through this post, we will learn how to use a proximity sensor in Android. As mentioned in the developer’s guide, the Android platform provides a sensor that lets you determine how close the face of a device is to an object (known as the proximity sensor).

Begin by creating a new Activity called ProximityTestActivity in any of your existing Android projects and add the following code!

ProximityTestActivity.java


import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class ProximityTestActivity extends Activity {
	/** Called when the activity is first created. */

	private TextView txtProximitySensor, txtMaxProximity, txtReadingProximity;
	private SensorManager mSensorManager;
	private Sensor mProximitySensor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_proximity);
		
		txtProximitySensor = (TextView)findViewById(R.id.txtProximitySensor);
		txtMaxProximity = (TextView)findViewById(R.id.txtProximityMax);
		txtReadingProximity = (TextView)findViewById(R.id.txtProximityReading);

		mSensorManager = (SensorManager)getSystemService(
				Context.SENSOR_SERVICE);
		mProximitySensor = mSensorManager.getDefaultSensor(
				Sensor.TYPE_PROXIMITY);

		if (mProximitySensor == null){
			txtProximitySensor.setText("Proximity sensor is not present!"); 
		
		}else{
			txtProximitySensor.setText("Sensor present with name:" + " " +mProximitySensor.getName());
			txtMaxProximity.setText("Maximum Range: "
					+ String.valueOf(mProximitySensor.getMaximumRange()));
			mSensorManager.registerListener(proximitySensorEventListener,
					mProximitySensor,
					SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	SensorEventListener proximitySensorEventListener
	= new SensorEventListener(){
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			// TODO Auto-generated method stub
			if(event.sensor.getType()==Sensor.TYPE_PROXIMITY)
			{
				txtReadingProximity.setText("Proximity Sensor Reading:"
						+ String.valueOf(event.values[0]));
			}
		}
	};
}

activity_proximity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtProximitySensor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/txtProximityMax"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtProximitySensor"/>

    <TextView
        android:id="@+id/txtProximityReading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtProximityMax"/>

</RelativeLayout>

Save all changes. Make sure no errors are present. Run the application on an Android device and you should see the following output!

output_1

output_2

Reference: Position sensors

What’s seen through [Glass]

Hey everyone!

Google Glass has been creating waves in the ocean of technology even since it’s inception at Google I/O 2012. The device has it’s own pros and cons and after having used it for over a month now, here’s a glimpse of what you see through;

[Glass]

This slideshow requires JavaScript.

Developing applications for Google Glass is pretty straightforward. Both the Mirror API and the GDK enable developers to create web based and native applications respectively for the wearable device. In addition, one can also try out various features that include winking to take photos, head angle detection, real time search and language translate options.

Recently, the second generation Google Glass device was launched in the United Kingdom that works with prescription glasses and has a detachable ear piece to improve voice-activated commands. To know more check out this space later…