All posts by prativa

About prativa

I am Software Engineer .

No menu bar shown on the top panel after upgrading to 13.10

 sudo aptitude upgrade -y;
sudo aptitude dist-upgrade -y;
sudo aptitude install ubuntu-desktop -y;

Using MonkeyTalk in AndroidStudio

Let me first introduce what MonkeyTalk is?
Monkey talk is a mobile app testing tool. MonkeyTalk automates real, functional interactive tests for iOS and Android apps – everything from simple “smoke tests” to sophisticated data-driven test suites. Native, mobile, and hybrid app, real devices or simulators. Moreover, automation saves time, it is re-usable, repeatable and so on. Monkey talk is an open source automation tool. It supports both Android and iPhone. It is very easy to learn and its a powerful functional testing tool.

Everything is in the web. So, why am I writing this blog?
Its because recently I have switched to android studio for android development. There are loads of tutorial based in Eclipse but very few based in Android Studio. So, I thought maybe this will be useful for everyone out there who is struggling to use MonkeyTalk in Android Studio.

Requirements for MonkeyTalk are….
1. Android Studio
2. MonkeyTalk IDE which you can download from this link

Procedure :
Before you proceed with this blog, I presume you know how to use android studio and gradle build system.
So, here we start.

There are two important steps to be followed:

Step 1: We build an instrumented apk using Android Studio

Step 2: We perform automation on instrumented apk using MonkeyTalk IDE

How to make an instrumented apk ?

      1. I assume you have a ready project in Android Studio which can be compiled successfully using Android Studio. You can get a test project from this github link.
      2. Now, in your app folder create a new folder named monkey-libs folder. Inside this folder place Monkey Talk Agent as shown in the github.
      3. Then, in your build.gradle file located inside app folder, add the aspectj dependency inside buildscript
         buildscript {  
           repositories {  
           dependencies {  
             classpath 'com.uphyca.gradle:gradle-android-aspectj-plugin:0.9.5'  
      4. Add aspectj plugin in dependencies of buildscript
      5. Then to activate the aspectj plugin, write the given code in build.gradle file
         apply plugin: 'android-aspectj'  
      6. Then compile the Java file with AspectJ plugin by writing the following code in build.gradle file
         dependencies {  
         compile fileTree(dir: 'libs', include: ['*.jar'])  
         monkeytalkCompile fileTree(dir: 'monkey-libs', include: ['*.jar'])  
      7. Thats all you need to do in build.gradle file.
      8. Now we need to create an instrumented apk. To get instrumented apk you need to create a folder name monkeytalk inside src folder. This monkey talk folder must contain AndroidManifest file. Just one AndroidManifest file is required. You can see the sample here .
      9. AndroidManifest file located inside monkeytalk must consist of the following permissions:
         <?xml version="1.0" encoding="utf-8"?>  
         <manifest xmlns:android=""  
           package="com.georgepapas.monkeytalkdemo" >  
           <uses-permission android:name="android.permission.GET_TASKS"/>  
           <uses-permission android:name="android.permission.INTERNET"/>  
      10. and thats all. A build instrumented with monkey talk aspects will be generated and installed in the emulator or your device by running the given code:
         ./gradlew clean installMonkeytalk  

Hence, you can find an instrumented apk in your device or emulator.

Now, how to run the automation ?

      1.  Start your monkey talk ide.
      2. Go to File > New > MonkeyTalk Project > project name (say TestMonkeyTalk)
      3. Right click on project TestMonkeyTalk > New > Script > ScriptName (say testScript)
      4. Open your device which has debugging mode enabled and start your app.
      5. Press Connect > Android Device.
      6. Then press the Record Button and start using your app. As you finish visiting all the pages of the app, press stop button.
      7. Hence, now you have a Script for automation.
      8. Now, to start the automation, press the play button.

Hence, you have successfully automated your testing procedure.

Good luck with monkey talk.

See you later in the next blog.

Until then Happy Coding 🙂

Uploading Image from Android App to Server ~ Programmatically :)

Its been such a long time ever since I have posted anything into the blog. Well not posting into it does not mean I have not learned anything new in the mean time. Well, I have learned so many different things in this month that I really have not been able to keep track of it. But, I will eventually post about all of them. Today, I am posting about the way we perform image uploading from android app to server. 

I thought uploading image to server was really hard. I researched for whole day. Different blogs were giving different types of suggestions. I was literally going through paralysis analysis. Then,after a day I finally uploaded image to the server. So, I am feeling great and happy right now.

To perform uploading, you will have to first understand the following things:

HTTP is a protocol for exchanging messages between a client and a server. An HTTP client opens a connection and sends a request message to an HTTP server; the server then returns a response message, usually containing the resource that was requested. After delivering the response, the server closes the connection. Request has three parts : a method name – GET or POST method , resources and the version of HTTP being used. Response also has three parts: the HTTP version, a response status code that gives the result of the request, and status code.

GET method : Requests data from a specified resource.

Query strings (name/value pairs) is send in the URL of a GET request. It should only be used to retrieve data

POST method : Submits data to be processed to a specified resource

Query strings (name/value pairs) is sent in the HTTP message body of a POST request.

Requests made through these methods return an instance of HTTPResponse. This instance of HTTPResponse has methods for accessing the response headers ( getHeader()), response info (getStatusCode()), response data (getData(), getInputStream()) and any trailers that might have been sent.

Although the packages provides basic functionality for accessing resources via HTTP, it doesn’t provide the full flexibility or functionality needed by many applications.

So we need following jar file which can be downloaded from here to get an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations-

  • httpcore-4.3.2.jar
  • httpmime-4.3.1.jar

Hence, we have understood how Client-Server communication is handled. Now through the following code snippet, we can upload image to the server:

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

		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String result = "";

			// Client-side HTTP transport library
			HttpClient httpClient = new DefaultHttpClient();

			// using POST method
			HttpPost httpPostRequest = new HttpPost(imagePostUrl);
			try {

				// creating a file body consisting of the file that we want to
				// send to the server
				FileBody bin = new FileBody(imageFile);

				 * An HTTP entity is the majority of an HTTP request or
				 * response, consisting of some of the headers and the body, if
				 * present. It seems to be the entire request or response
				 * without the request or status line (although only certain
				 * header fields are considered part of the entity).
				 * */
				MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
				multiPartEntityBuilder.addPart("images[1]", bin);

				// Execute POST request to the given URL
				HttpResponse httpResponse = null;
				httpResponse = httpClient.execute(httpPostRequest);

				// receive response as inputStream
				InputStream inputStream = null;
				inputStream = httpResponse.getEntity().getContent();

				if (inputStream != null)
					result = convertInputStreamToString(inputStream);
					result = "Did not work!";
				return result;
			} catch (Exception e) {

				return null;

			// return result;

		protected void onPreExecute() {
			// TODO Auto-generated method stub
			uploadStatus.setText("Uploading image to server");

		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub


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

		return result;



Relationship of Android with Thread

A thread is an execution context, which is all the information a CPU needs to execute a stream of instructions. It controls what executes in what order.

When using threads, CPU gives you the illusion that it’s doing multiple computations at the same time. It does that by spending a bit of time on each computation.

Threads are like two people using the same computer, who don’t have to share data explicitly but must carefully take turns. Conceptually, threads are just multiple worker bees buzzing around in the same address sapce. Each thread has its own stack, its own instructor pointer(aka program counter), etc. , but all threads in a process share the same memory.

You can kill one thread and others will still be running.

Android’s user interface thread

1.1 Main Thread
Android modifies the user interface and handles input events from one single user interface thread. This thread is also called the main thread.

Android collects all events in a queue and process an instance of the looper class.


Is Main Thread enough for processing large data in Android ?

No, it’s not. If only main thread is used then all code of an Android application runs in the main thread and every statement is executed after each other.
If your perform the long lasting operation, for example accessing data from the internet, the application blocks until the corresponding operation has finished.

Then, what is the solution ?
To provide a good user experience, all potentially slow running operation in an Android application should run asynchronously, e.g. via some way of concurrency constructs of the Android framework. This includes all potential slow operations, like network, file and database access and complex calculations.

Android support the usage of the Thread class to perform asynchronous processing.

How to use threads in Android to obtain concurrency ?
Android provides android.os.Handler class or the AsyncTasks classes to handle concurrency.

1. android.os.Handler:
Handler class is used to register to a thread and provide a simple channel to send data to this thread. A Handler object registers itself with the thread in which it is created.
To use a handler, you have to subclass it and override the handleMessage() method to process messages.
Your thread can post messages via the sendMessage(Message) method or via the sendEmptyMessage() method to the Handler object.

For example:
The following code demonstrates the usage of a Handler via a View.
Assume your activity uses the following layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:padding="4dip" >

        android:text="" >
        android:text="Start Progress" >


With the following the ProgressBar get updated once the users presses the Button.

public class ProgressTestActivity extends Activity {
  private ProgressBar progress;
  private TextView text;

  public void onCreate(Bundle savedInstanceState) {
    progress = (ProgressBar) findViewById(;
    text = (TextView) findViewById(;


  public void startProgress(View view) {
    // Do something long
    Runnable runnable = new Runnable() {
      public void run() {
        for (int i = 0; i <= 10; i++) {
          final int value = i;
 Runnable() {
            public void run() {
    new Thread(runnable).start();

  // Simulating something timeconsuming
  private void doFakeWork() {
    try {
    } catch (InterruptedException e) {


2. AsyncTask:
The AsyncTask class encapsulates the creation of background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.

How to use AsyncTask ?

To use AysncTask, you must subclass it. AsyncTask uses generics and varargs. The parameters are the following

 AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> 

An AsyncTask is started via the


method. This method calls the


and the


TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.

The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate thread.

The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

The following code demonstrates how to use the AsyncTask class to download the content of a webpage.

Create the following layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="Load Webpage" >

        android:text="Placeholder" >


Add the android.permission.INTERNET permission to your AndroidManifest.xml file.

Change your activity to the following:

public class ReadWebpageAsyncTask extends Activity {
  private TextView textView;

  public void onCreate(Bundle savedInstanceState) {
    textView = (TextView) findViewById(;

  private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;

        } catch (Exception e) {
      return response;

    protected void onPostExecute(String result) {

  public void onClick(View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "" });


If you run your application and press your button then the content of the defined webpage is read in the background. Once this process is done your TextView is updated.

Handler Vs AsyncTask

handler vs AsyncTask
handler vs AsyncTask

WebP – enabling faster, smaller and more beautiful images

For an average app, image account for 69% of transferred bytes for mobile sites. The size of the image is growing fast because its a HiDPI world.

Hence, use WebP image format in your app.


WebP image format uses improved data compression. It uses both lossy and lossless modes.

Never heard of webp??

– WebM video format uses VP8 video codec.

-WebP is derived from VP8, essentially a key frame..

-WeP{P,M} are open-source, royalty free formats , open-sourced by Google in 2010. It has BSD-style license.

History of WebP….

– Initial release in 2010

Lossy compression of true-color graphics

-August, 2012

Lossless compression support

Transparency(alpha channel) support

-April, 2013

Color profile, animation , metadata

Now, ready for general purpose use, on the web and elsewhere!

Why should I use webp image format in my app?

In the age of Expensive Data Plans, it saves your bandwidth. Your app will have to download fewer bytes, it completes loading much earlier compared to the JPEG page.

How do I create a WebP file?

● Download WebP converter (Linux, OSX, Windows)
○ cwebp -q 80 image.png -o image.webp
○ dwebp image.webp -o image.png
● Download WebP Codec for Windows (Photo Viewer, Explorer, Office 2010+, …)
● Download Photoshop plugin (by Telegraphics)
● Download GIMP plugin
● ImageMagick, Pixelmator, XnView, IrfanView, GDAL, JPEGView have native support for
● Java, .NET, Flash, Python, Ruby, PHP bindings available to libwebp…
● online tool

WebP on Android !

Google+ on Android

● Photos and images comprise the vast majority of bytes
● On average, got 50% byte savings with WebP!
● Saving many terabytes of bandwidth per day…
● Saving our users money each time they use the app!


Native library — all versions of Android

static {
private Bitmap webpToBitmap(byte[] encoded) {
int[] width = new int[] { 0 };
int[] height = new int[] { 0 };
byte[] decoded = libwebp.WebPDecodeARGB(encoded, encoded.length, width, height);
int[] pixels = new int[decoded.length / 4];
return Bitmap.createBitmap(pixels, width[0], height[0], Bitmap.Config.ARGB_8888);

webp-android-backport  for Android <4.0

For Novice Android Developer: Display Google Maps in Android Devices

Google Map is one of the search website of Google that allows us

  • to map out public transit directions,
  • get the map and landmark of the place that we wish to visit by creating our own maps
  • add lines and markers for more comprehensive and detailed in the Google Map box
  • get real time traffic information
  • view streets and identify locations by navigating through Google getting a street leve image of any city around the world

All we have to do is to type the places that we wish to go and visit, and the whole search will come out making it easier for us to view our search result.

There are so many advantages of embedding Google Maps into our Android Application. Google provides an easy way to integrate Google Maps into our Android Applications. To integrate Google Maps into our Android Applications, we need to work with Google Maps Android API v2

  • Download and configure the Google Play services SDK. The Google Maps Android API is distributed as part of this SDK.
  • Obtain an API key. To do this, you will need to register a project in the Google APIs Console, and get a signing certificate for your app.
  • Specify settings in the Application Manifest.
  • Add a map to a new or existing Android project.

If you dont know how the above steps need to be carried out, then this tutorial is just for you:

Step 1:

First of all, Download and configure the Google Play services SDK, we have to follow the given steps:

Install Google Play Services From : Android SDK Manager > extras > Google Play Services

Google Play services SDK_02

Step 2:

Import the library file google-play-services_lib by following the given step:
a. File > Other > Android > Android Project From Existing Code…
b. path to sdk/extras/google/google_play_services/libproject/google-play-services_lib
c. click finish


Step 3:

Create a New Android Application Project  and add the google play services as library in our project:


Step 4:

To access the Google Maps servers with the Maps API, we have to add a Maps API key to our application.
The key is free, we can use it with any of our applications that call the Maps API, and it supports an unlimited number of users.We can obtain a Maps API key from the Google APIs Console by providing your application’s signing certificate and its package name.

Obtaining a key for your application requires several steps. These steps are outlined here, and described in detail in the following sections.

Step 1
Retrieve information about your application’s certificate.This can be done by running the following command in terminal….

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey 
-storepass android -keypass android

After running this code, you will get following data in your terminal:

Alias name: androiddebugkey
Creation date: Jun 12, 2013
Entry type: PrivateKeyEntry
Certificate chain length: 1
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 51b8444f
Valid from: Wed Jun 12 15:35:07 NPT 2013 until: Fri Jun 05 15:35:07 NPT 2043
Certificate fingerprints:
     MD5:  C5:47:79:D0:8A:F7:8E:BB:A1:72:4A:8E:35:89:EB:D9
     SHA1: 8B:6F:B4:2D:0E:56:51:53:35:C3:DB:82:3C:9C:87:B9:04:33:6D:38
     Signature algorithm name: SHA1withRSA
     Version: 3

SHA-1 fingerprint: The fingerprint is a unique text string generated from the commonly-used SHA-1 hashing algorithm. Because the fingerprint is itself unique, Google Maps uses it as a way to identify your application.

SHA1: 8B:6F:B4:2D:0E:56:51:53:35:C3:DB:82:3C:9C:87:B9:04:33:6D:38

Step 2:

Create a new project in the Google APIs Console.

To create a new project for Google Maps Android API,select the project name in the upper left hand corner and then click Create.


Step 3:

Then, select Services from the left navigation bar and add the Google Maps Android API v2 as a service for the project by turning it on.


This displays the Google Maps Android API Terms of Service. If you agree to the terms of service, click the checkbox below the terms of service, then click Accept. This returns you to the list of APIs and services.

Step 4:

You’re now ready to get a Maps API key.

To get the key:

  • Navigate to your project in the Google APIs Console.
  • In the left navigation bar, click API Access.
  • In the resulting page, click Create New Android Key….
  • In the resulting dialog, enter the SHA-1 fingerprint , that we obtained from Step 1 and after semicolon ( ; ) add your package name

The Google APIs Console responds by displaying Key for Android apps (with certificates) followed by a forty-character API key, for example: AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0
Copy this key value. You will use it in the next step.

Step 6:

Finally, you can add your key to your application and begin development.

The easiest way to test that your application is configured correctly is to add a simple map. We will have to make changes in two files: main.xml,manifest.xml and Please note that the code below is only useful for testing our settings in an application targeting Android API 12 or later, This code should not be used in a production application.

To add the key to your application, your manifest should consist of the following fields:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android=""



   android:versionName="1.0" >



        android:targetSdkVersion="16" />

    <!-- Because version 2 of the Google Maps Android API requires OpenGL ES version 2
     External services can detect this notification and act accordingly.
     So, we need to add this in our manifest -->




    <!--Permissions that give the application access to
         Android system features and to the Google Maps servers.-->



        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.demomapproject.permission.MAPS_RECEIVE" />

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

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

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

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

     The following two permissions are not required to use

     Google Maps Android API v2, but are recommended.

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

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





        android:theme="@style/AppTheme" >

    From here, the Maps API reads the key value and passes it to the Google Maps server,
         which then confirms that you have access to Google Maps data.

        This element sets the key to the value API_KEY
         and makes the API key visible to any MapFragment in your application. 



            android:value="AIzaSyA5idXLlKzifjzXIO_j9tQ7CAVYEZuH-10" />



            android:label="@string/app_name" >


                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />





Your main.xml should consist of something like this

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android=""

Your MainActivity.Java should consist of something like this

package com.example.mapdemo;

import android.os.Bundle;

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {

Build and run your application. You should see a map. If you don’t see a map, confirm that you’ve completed all of the steps appearing earlier in this document.

Happy Coding