Until we meet again…!

Saying goodbye isn’t really the easiest thing to do. Life is a journey and you learn it when your through. Today, marks the completion of the 200th post on Threads Of Life finally ending this two year long journey. As all good things come to an end, it’s time for me to discontinue this amazing blogging period.

I would like to express my heartfelt thanks to all TOL followers on Facebook and the thousands of visitors who have spent time over here. I wish I could solve your queries a little earlier but none the less keep sending them to me and will try my best to get them resolved.

Until we meet again..! πŸ™‚

goodbye

Tutorial #79: Implement ListView with search functionality in Android

Hello everyone!

Android allows users to search any data that is available to them irrespective of whether the content is located on the device or the Internet. Post Android 3.0 (Honeycomb), a SearchView widget provides an interface for the user to enter a search query and submit a request to a search provider. It also shows a list of query suggestions or results, if available.

While implement search functionality in your Android application it is important to note that the search framework does not provide APIs to search your data. To perform a search, you need to use APIs appropriate for your data. For example, if your data is stored in an SQLite database, you should use the android.database.sqlite APIs to perform searches. In this tutorial, we will learn how to add the search functionality to our existing Android ListView.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Launch Eclipse IDE and create a new Android application project called AndroidListViewWithSearch with package name com.example

Step 2: Create Helper class for SQLite database

In this example, we will be storing our listview data inside a table of the SQLite database. We would be using a virtual table for faster and efficient access of data.

DbHelper.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 
public class DbHelper {
   
    public static final String COLUMN_NAME = "fruits"; 
    private static final String TAG = "App";
    private DatabaseHelper myDbHelper;
    private SQLiteDatabase myDb;
 
    private static final String DATABASE_NAME = "Data";
    private static final String FTS_VIRTUAL_TABLE = "Info";
    private static final int DATABASE_VERSION = 1;
 
    //Create a Virtual Table for fast searches
    private static final String DATABASE_CREATE =
            "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3("
                    + COLUMN_NAME
                    + " UNIQUE (" + COLUMN_NAME + "));";
 
 
    private final Context context;
 
    private static class DatabaseHelper extends SQLiteOpenHelper {
 
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
 
 
        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.w(TAG, DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE);
        }
 
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
            onCreate(db);
        }
    }
 
    public DbHelper(Context ctx) {
        this.context = ctx;
    }
 
    public DbHelper open() throws SQLException {
        myDbHelper = new DatabaseHelper(context);
        myDb = myDbHelper.getWritableDatabase();
        return this;
    }
 
    public void close() {
        if (myDbHelper != null) {
            myDbHelper.close();
        }
    }
 
 
    public long createList(String name) {
 
        ContentValues initialValues = new ContentValues();
 
        initialValues.put(COLUMN_NAME, name);

        return myDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
 
    }
 
 
    public Cursor searchByInputText(String inputText) throws SQLException {
 
        String query = "SELECT docid as _id," +
                COLUMN_NAME +  " from " + FTS_VIRTUAL_TABLE +
                " where " + COLUMN_NAME + " MATCH '" + inputText + "';";
 
        Cursor mCursor = myDb.rawQuery(query,null);
 
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
 
    }
 
 
    public boolean deleteAllNames() {
 
        int doneDelete = myDb.delete(FTS_VIRTUAL_TABLE, null , null);
        return doneDelete > 0;
 
    }
}

Step 3: Create customized list view

The BaseAdapter is the common base class of implementation for an Adapter that can be used in both ListView (by implementing the specialized ListAdapter interface). Let’s create our own Adapter as follows,

MyAdapter.java

package com.example;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;

public class MyAdapter extends BaseAdapter {

	private ArrayList myListItems;
	private LayoutInflater myLayoutInflater;

	public MyAdapter(Context context, ArrayList arrayList){

		myListItems = arrayList;
		myLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return myListItems.size();
	}

	@Override

	public Object getItem(int i) {
		return null;
	}

	@Override
	public long getItemId(int i) {
		return 0;
	}

	@Override

	public View getView(int position, View view, ViewGroup viewGroup) {


		ViewHolder holder;


		if (view == null) {
			holder = new ViewHolder();

			view = myLayoutInflater.inflate(R.layout.list_item, null);
			holder.itemName = (TextView) view.findViewById(R.id.list_item);


			view.setTag(holder);
		} else {

			holder = (ViewHolder)view.getTag();
		}


		String stringItem = myListItems.get(position).toString();
		if (stringItem != null) {
			if (holder.itemName != null) {
				//set the item name on the TextView
				holder.itemName.setText(stringItem);
			}
		}


		return view;

	}


	private static class ViewHolder {

		protected TextView itemName;
	}
}

Step 4: Make Activity searchable

In order to make our Android activity implement the search functionality, we need to add an IntentFilter in our AndroidManifest.xml file as follows,

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name" >
           
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>

</manifest>

Once this is done, create a new folder called xml inside res. Add the following searchable.xml file to that folder.

searchable.xml

<?xml version="1.0" encoding="utf-8"?>
 
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
            android:label="@string/search_label"
            android:hint="@string/search_hint"/>

res/values/strings.xml

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

    <string name="app_name">AndroidListViewWithSearch</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Android ListView with Search Demo</string>
    <string name="search_label">Search</string>
    <string name="search_hint">Search items from ListView</string>

</resources>

Step 5: Create Activity class

Add the following code to the MainActivity class!

MainActivity.java

package com.example;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.database.Cursor;
import android.os.Handler;
import android.view.View;
import android.widget.*;
import java.util.ArrayList;


public class MainActivity extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {

	private ListView myList;
	private SearchView searchView;
	private DbHelper mDbHelper;
	private MyAdapter defaultAdapter;
	@SuppressWarnings("rawtypes")
	private ArrayList<String> nameList;

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

		setContentView(R.layout.activity_main);

		nameList = new ArrayList();

		
		//populate list
		nameList.add("Apples");
		nameList.add("Oranges");
		nameList.add("Grapes");
		nameList.add("Pineapples");
		nameList.add("Mangoes");
		nameList.add("Watermelons");
		nameList.add("Strawberries");
		nameList.add("Bananas");
		nameList.add("Apricots");
		nameList.add("Olives");
		nameList.add("Peaches");
		nameList.add("Jackfruits");
		
		myList = (ListView) findViewById(R.id.list);

		defaultAdapter = new MyAdapter(MainActivity.this, nameList);
		myList.setAdapter(defaultAdapter);
		
		searchView = (SearchView) findViewById(R.id.search);
		searchView.setIconifiedByDefault(false);

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);

		mDbHelper = new DbHelper(this);
		mDbHelper.open();

		//Clear all names
		mDbHelper.deleteAllNames();

		// Create the list of names which will be displayed on search
		for (String name : nameList) {
			mDbHelper.createList(name);
		}
	}

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

		if (mDbHelper  != null) {
			mDbHelper.close();
		}
	}

	@Override
	public boolean onClose() {
		myList.setAdapter(defaultAdapter);
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		displayResults(query + "*");
		return false;
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		if (!newText.isEmpty()){
			displayResults(newText + "*");
		} else {
			myList.setAdapter(defaultAdapter);
		}

		return false;
	}

	private void displayResults(String query) {

		Cursor cursor = mDbHelper.searchByInputText((query != null ? query : "@@@@"));

		if (cursor != null) {

			String[] from = new String[] {DbHelper.COLUMN_NAME};

			int[] to = new int[] {R.id.search_text_view};

			SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.search_item, cursor, from, to);
			myList.setAdapter(cursorAdapter);

			//listview Click listener
			myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

					Cursor cursor = (Cursor) myList.getItemAtPosition(position);

					String selectedName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
					Toast.makeText(MainActivity.this, selectedName, 0).show();

					myList.setAdapter(defaultAdapter);

					for (int pos = 0; pos < nameList.size(); pos++) {
						if (nameList.get(pos).equals(selectedName)){
							position = pos;
							break;
						}
					}

					Handler handler = new Handler();
					final int finalPosition = position;
					handler.post(new Runnable() {
						@Override
						public void run() {

							myList.setSelection(finalPosition);
						}
					});

					searchView.setQuery("",true);
				}
			});

		}
	}
}

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

Reference: Android Search

Inside an Android developer’s toolkit!

[This is a long overdue post.]

Many a times, people ask me about how to get started with Android programming, make applications, earn money etc. Before even thinking about developing applications, one needs to know what exactly an Android developer uses to create such applications. What are the resources at his/her disposal? From creating intuitive user interfaces to finally publishing an application onto the Play Store, a developer has to ensure that the resources he/she chooses are good enough for the application to be released into the public domain.

In my opinion, the Internet today is filled with a plethora of resources. To cut short this boring post πŸ˜› I have listed down four of the most common applications/utilities/links that one can use to create better quality mobile applications.

1. Android Asset Studio

The Android Asset Studio allows developers to quickly and easily generate icons from existing source images, clipart, or text. It is useful to generate application icons in no time! πŸ™‚

2. Android Custom UI Views

Are you trying to develop a custom view in Android? Perhaps, you should then try using any of these Android views. The developers have done a great job by creating cool, intuitive and ready to use Android user interfaces. You can even send in your recommendations in case you have one.

3. Kendo UI

If you want to develop user interfaces using HTML5, CSS and Javascript then Kendo is the best out there. With Kendo UI, you can easily create serious HTML5/JavaScript products without worrying about cross-browser compatibility, standards compliance or touch-device support. Kendo UI Complete widgets can easily be themed and styled via CSS. Moreover, the framework includes 12 out-of-the-box themes.

4. Android Studio

Google’s latest Android developer IDE certainly tops my list of developer tools. Android Studio is a new Android development environment based on IntelliJ IDEA. Similar to Eclipse with the ADT Plugin, Android Studio provides integrated Android developer tools for development and debugging.

5. PDF SDK for Android

The PDF SDK enables developers to create applications with an integrated PDF reader. Though I have not tried using it personally, I would suggest you check out the beta and if possible support the development of the library.

If anyone would like to add to this list then please feel free to drop in a comment. Stay tuned for more Android tips and tricks. Thanks for visiting! πŸ™‚

Get screenshot of device screen in Android

Hey everyone!

At present, there are many applications on the Google Play Store that help you take a screenshot of the Android device screen. As a matter of fact, if you are running Ice Cream Sandwich (4.0) and above, taking a screenshot is a lot easier. You just need to press the Volume Down and Power buttons at the same time, hold them for a second, and your phone will take a screenshot. However, this functionality is not built in for Gingerbread (Android 2.3) and below. Some devices (like many Samsung phones) do have these features, but it varies from phone to phone.

As a developer, one needs to develop an application that could run across multiple devices supporting different Android versions. Through this post, we will learn how to take programmatically take a screenshot in Android.

Pre-requisites: Eclipse IDE, Android SDK

Launch Eclipse IDE and create a new Android application project called AndroidScreenShotDemo with package name com.example

Add the following code in the Activity class!

MainActivity.java

package com.example;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class ScreenShotActivity extends Activity{

	private RelativeLayout relativeLayout;
	private Bitmap myBitmap;

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

		relativeLayout = (RelativeLayout)findViewById(R.id.relative1);
		relativeLayout.post(new Runnable() {
			public void run() {

				//take screenshot
				myBitmap = captureScreen(relativeLayout);

				Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();

				try {
					if(myBitmap!=null){
						//save image to SD card
						saveImage(myBitmap);
					}
					Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

	}

	public static Bitmap captureScreen(View v) {

		Bitmap screenshot = null;
		try {

			if(v!=null) {

				screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Config.ARGB_8888);
				Canvas canvas = new Canvas(screenshot);
				v.draw(canvas);
			}

		}catch (Exception e){
			Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
		}

		return screenshot;
	}

	public static void saveImage(Bitmap bitmap) throws IOException{

		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
		File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
		f.createNewFile();
		FileOutputStream fo = new FileOutputStream(f);
		fo.write(bytes.toByteArray());
		fo.close();
	}

}

res/layout/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:id="@+id/relative1"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    
    <ImageView
        android:id="@+id/img1"
        android:src="@drawable/android"
        android:contentDescription="sample image"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
        
</RelativeLayout>

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
	
    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.ScreenShotActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
             
    </application>
</manifest>

Save all changes. Make sure no errors are present. Run the application on an Android device and the screenshot will be stored inside the SD card of your phone.

output_1

output_2

Reference: Bitmap in Android

Add event to calendar in Android

Hello everyone!

A calendar provides a systematic way of organizing events by giving names to periods of time, typically days, weeks, months, and years. Android provides developers an abstract Calendar class to maintain a list of planned events. As mentioned on the developer’s page, a Calendar object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). Calendar defines the range of values returned by certain fields, as well as their meaning.

Through this post, we will learn how to add an event to the default calendar application in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Launch Eclipse IDE and create a new Android application project called AndroidCalendarExample with package name com.example

Step 2: Add code to Activity class

MainActivity.java

package com.example;

import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

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

			@Override
			public void onClick(View arg0) {

				//add event to calendar
				addCalendarEvent();
			}

		});

	}

	public void addCalendarEvent(){

		Calendar cal = Calendar.getInstance();     
		Intent intent = new Intent(Intent.ACTION_EDIT);
		intent.setType("vnd.android.cursor.item/event");
		intent.putExtra("beginTime", cal.getTimeInMillis());
		intent.putExtra("allDay", true);
		intent.putExtra("rrule", "FREQ=YEARLY");
		intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
		intent.putExtra("title", "Test Event");
		intent.putExtra("description", "This is a sample description");
		startActivity(intent);
	}
}

The Calendar class is used for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. A Date object represents a specific instant in time with millisecond precision.

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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <Button
        android:id="@+id/btn1"
        android:layout_below="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/event" />

</RelativeLayout>

Next, we also need to make changes in the AndroidManifest.xml file in order to include the necessary READ and WRITE permissions.

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            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>

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

android_calendar_1

android_calendar_2

Tutorial #78: Using Ksoap2 in Android

SOAP (Simple Object Access Protocol) is a lightweight protocol used for the exchange of information in a de-centralized environment. It was developed by Microsoft and has been proposed as a standard interface to the Internet Engineering Task Force (IETF). A SOAP request mainly consists of three parts:

1. Envelope – It defines a framework for describing what is in a message and how to process it.

2. Rules – It includes a set of encoding rules for expressing instances of application-defined datatypes.

3. Convention – Used for representing remote procedure calls and responses.

In this tutorial, we will learn how to send SOAP requests using Android. To implement SOAP requests using Android, we can use the Ksoap2 library. It is a lightweight SOAP client library for the Android platform.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Create an Android application project called AndroidKSoapExample with package name com.example

Step 2: Download Ksoap2 for Android

Next, you need to download the latest version of ksoap2 from over here. Add the ksoap2.jar in the libs folder of your Android project.

Step 3: Add Java code to Activity class

Now, let’s add the ksoap2 Java code in order to send the SOAP request. We would be connecting to a public webservice available on the Internet. It is important to note that all network related requests need to be executed on a non-UI thread post Android 3.0. Here’s what our Activity class looks like,

MainActivity.java

package com.example;

import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.app.Activity;


public class MainActivity extends Activity {


	private static final String SOAP_ACTION = "http://footballpool.dataaccess.eu/TopGoalScorers";
	private static final String METHOD_NAME = "TopGoalScorers";
	private static final String NAMESPACE = "http://footballpool.dataaccess.eu";
	private static final String URL = "http://footballpool.dataaccess.eu/data/info.wso?WSDL";
	private TextView tv;
	private String response;

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

		tv= (TextView)findViewById(R.id.txt2);

		myAsyncTask myRequest = new myAsyncTask();
		myRequest.execute();

	}

	private class myAsyncTask extends AsyncTask<Void, Void, Void>    {


		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			tv.setText(response);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();       
		}

		@Override
		protected Void doInBackground(Void... arg0) {

			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			request.addProperty("iTopN", "5"); 

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
			envelope.setOutputSoapObject(request);  

			HttpTransportSE httpTransport = new HttpTransportSE(URL);

			httpTransport.debug = true;  
			try {
				httpTransport.call(SOAP_ACTION, envelope);
			} catch (HttpResponseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} //send request
			SoapObject result = null;
			try {
				result = (SoapObject)envelope.getResponse();
			} catch (SoapFault e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 

			Log.d("App",""+result.getProperty(1).toString());
			response = result.getProperty(1).toString();
			return null;
		}   
	}   
}

Step 4: Add permissions in manifest file

Before you run the application, you need to add the network and Internet permissions in the AndroidManifest.xml file as follows,

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
          
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            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>

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

output

Reference: W3C SOAP Specifications