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 :P 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.

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

Using ViewSwitcher in Android

Hello friends!

A ViewSwitcher as the name suggests is used to switch between two views. It is used to change the layout of your Android application within the same Activity. You can create views for a ViewSwitcher widget either using a factory or by adding them on your own. As mentioned on the Android developer’s page, a ViewSwitcher can only have two child views, of which only one is shown at a time.

Through this post, we will learn how to use the ViewSwitcher widget in Android. It is important note that both ViewSwitcher and ViewFlipper inherit the ViewAnimator class but the difference is that the former has two views while the latter can have any number of views.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

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

Step 2: Create layout for ViewSwitcher

Next, create a new XML file under the res/layout folder named activity_switcher and add the following code. This will represent the layout for the ViewSwitcher.

activity_switcher.xml

<LinearLayout 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:orientation="vertical"
    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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="@string/app_name"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/prev"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/previous" />

        <Button
            android:id="@+id/next"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/next" />
        
    </LinearLayout>

    <ViewSwitcher
        android:id="@+id/viewswitcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >

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

</LinearLayout>

Step 3: Add code to Activity class

Finally, add the following code to your Activity class.

MainActivity.java

package com.example;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.app.Activity;

public class MainActivity extends Activity {

	Button buttonPrevious, buttonNext;
	ViewSwitcher viewSwitcher;

	Animation slide_in_left, slide_out_right;

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

		buttonPrevious = (Button) findViewById(R.id.prev);
		buttonNext = (Button) findViewById(R.id.next);
		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewswitcher);

		slide_in_left = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right);

		viewSwitcher.setInAnimation(slide_in_left);
		viewSwitcher.setOutAnimation(slide_out_right);

		buttonPrevious.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				Toast.makeText(getApplicationContext(), "Showing previous view..", Toast.LENGTH_SHORT).show();
				viewSwitcher.showPrevious();
			}
		});

		buttonNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				Toast.makeText(getApplicationContext(), "Showing next view..", Toast.LENGTH_SHORT).show();
				viewSwitcher.showNext();
			}
		});
	}
}

Save all changes and run the application on an emulator or Android device. If no errors occur then you should see the following output!

android_viewswitcher_1

android_viewswitcher_2

Reference: ViewAnimator in Android

Tutorial #77: Getting started with Google Dart!

Dart is an open source web programming language developed by Google. Like any web programming language, Dart too relies mainly on its cross-compilation to JavaScript feature in order to run on current browsers. It is a class based, object oriented language used to create client side web applications. The Dart project was founded by Lars Bak and Kasper Lund. Some of the key features of the Dart programming language include:

1. Classes – Dart’s classes and interfaces give developers what they need to effectively understand how to define APIs, and the constructs allow the encapsulation and reuse of data and methods.

2. Libraries – The libraries used by Dart will not change during run-time. Pieces of Dart code that are independently developed are thus able to rely upon those shared libraries.

In this tutorial, we will learn how to get started with Dart on Windows!

Pre-requisites: Windows OS (64 bit)

Step 1: Download Dart editor

Google released Dart Editor, an open-source editor based on Eclipse components for Windows, Mac OSX and Linux-based operating systems. You can download the bundle containing both the Dart SDK and the editor from over here.

Step 2: Write a Hello World program

Once you have downloaded Dart editor, launch it and create a New Application called HelloWorld as follows!

dart_1

First, you need to modify the HelloWorld.html file to include a button above the already existing script tags.

<button id="myButton">Click Me!</button>
<div id="myResult"></div>

Next, open the HellowWorld.dart file and add the following code!

import 'dart:html';

void main() {
  var button = query("#myButton");
  button.onClick.listen(addResult);
}
 
void addResult(Event e) {
  var resultDiv = query("#myResult");
  resultDiv.text = "You clicked the button";
}

Finally, save all changes and run the application. A new instance of the chromium browser should launch displaying the HTML content. Click on the button to view the result!

dart_2

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

Source: What Google Dart means for web developers

#Event: Get ready for DroidSync 2014

Hello everyone!

If you are Android developer or someone eager to step into the world of mobile technology then this summer could just be the ideal time to kick-start things. The Androcid team is organising a 1 day conference at Ramada Plaza Juhu, Mumbai, on 5th April, 2014. The event plans to showcase the entire Android ecosystem and promises to be an ideal place for developers, business professionals and start-up owners to come together and share information that could help strengthen the Android community.

If you feel you have an expertise, then here’s your chance to showcase your application or submit a 30 minute talk proposal. Looking forward to meet like-minded people? DroidSync plans to provide the ideal platform for you to interact with industry experts, business and management professionals or just anyone who loves to work with Android.

The registrations have already began. Grab your early bird tickets soon! To register and know more about the event please visit the website. Hope to see you at the conference! :)

droidsync_2014

Displaying images using Android GridView

Hello everyone!

A GridView is basically used to display items in a two dimensional pattern. The items could be represented as either text or image or a combination of both. In the case of an image gridview we would need to use the BaseAdapter class that helps create a custom adapter source for holding all the items to be displayed in the grid.

Through this post, we would learn how to create a GridView consisting of sample images in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Activity class

Create a new Activity class called ImageGridView in any of your existing Android projects. Add the following code to the class.

ImageGridView.java

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageGridView extends Activity {
	
	GridView gv1;
	GridViewAdapter madapter;
	int arr[] = new int[20];
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_grid);

		gv1=(GridView)findViewById(R.id.grid_view);
		madapter=new GridViewAdapter();
		gv1.setAdapter(madapter);
	}

	public class GridViewAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return arr.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			LayoutInflater infla=getLayoutInflater();
			View v=infla.inflate(R.layout.main,null);
			ImageView iv1=(ImageView)v.findViewById(R.id.imageView1);
			
			for(int i=0;i<arr.length;i++) {
				arr[i] = R.drawable.android;
			}
			
			iv1.setBackgroundResource(arr[position]);
			return v;
		}
	}
}

Step 2: Create layout for GridView

In order to display the images in a two dimensional grid, we need to create the corresponding layout as follows!

activity_grid.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/grid_view"
  android:orientation="vertical"
  android:paddingTop="80px"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:numColumns="4"
  android:columnWidth="60dp"
  android:layout_gravity="center"
  android:horizontalSpacing="5dp"
  android:stretchMode="columnWidth"/>

main.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:gravity="center">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true" />

</RelativeLayout>

Finally, save all changes. Run the application on an emulator or Android device and you should see the following output!

image_gridview

Reference: BaseAdapter in Android