Create custom EditText in Android

Hello everyone!

In the past, we have seen how customizing existing Android layout widgets can help improve the overall look-and-feel of the application. There exists many applications where in input text boxes are customized to suit user requirements. Android allows developers to modify an EditText widget and use the same while designing login forms, custom controls. Developers can use a drawable as the background. This can be either a reference to a full drawable resource (such as a PNG image, 9-patch, XML state list description, etc), or a solid color such as black.

Through this post, we will learn how to customize an EditText in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create a new Activity class called CustomEditTextActivity in any of your existing Android projects and write the following code.

CustomEditTextActivity.java

package com.example;

import android.app.Activity;
import android.os.Bundle;

public class CustomEditTextActivity extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_custom_edittext);
	}
}

Step 2: Create custom EditText

Let’s create a new layout called activity_custom_edittext.xml in the res/layout folder of our existing Android project and add the following code.

activity_custom_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
       <EditText
           android:id="@+id/et1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:background="@drawable/rounded_edittext"
           android:drawableLeft="@drawable/sample_image"
           android:drawablePadding="20dp"
           android:gravity="center_vertical"
           android:hint="@string/customized_text"
           android:imeOptions="actionNext"
           android:inputType="text"
           android:singleLine="true"
           android:textColor="#D00000"
           android:textColorHint="#D00000"
           android:textSize="15sp" />

</LinearLayout>

In order to customize the EditText widget, we need to define another XML that can be applied as a background attribute. Create a new XML file called rounded_edittext.xml and place it inside the res/drawable folder. The XML file will contain the below code.

res/drawable/rounded_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#F8F8F8"/>

    <corners
        android:bottomLeftRadius="4dp"
        android:bottomRightRadius="4dp"
        android:topLeftRadius="4dp"
        android:topRightRadius="4dp"/>

</shape>

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

output

Reference: Android EditText

Load custom HTML using WebView in Android

Hey friends!

In Android, a WebView is a view used to display web pages. Developers can also create their own HTML content and use the existing methods provided by the WebView widget to load custom HTML pages. As mentioned on the developer’s page, the loadDataWithBaseURL method is used to load the given data into a WebView, using baseUrl as the base URL for the content. The base URL is used both to resolve relative URLs and when applying JavaScript’s same origin policy.

Through this post, we will learn how to load our custom HTML content using WebView in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create a new Activity class called WebViewActivity in any of your existing Android projects and write the following code.

WebViewActivity.java

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebViewActivity extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web_view);
		
		WebView webView = (WebView)findViewById(R.id.webview);
		StringBuilder html = new StringBuilder();

		html.append("<html>");
		html.append("<head>");

		html.append("<link rel=stylesheet href='css/style.css'>");
		html.append("</head>");
		html.append("<body>");
		html.append("<h1>Android WebView Example</h1>");
		html.append("<p>Sample text</p>");
		html.append("<p><img style='width: 100%;' src='earth.png' /></p>");
		html.append("</body></html>");

		webView.loadDataWithBaseURL("file:///android_asset/", html.toString(), "text/html", "UTF-8", ""); 
	}
}

activity_web_view.xml

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

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>

Note: In order to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file.

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

Step 2: Create a new folder called css under the assets directory of your project and copy a sample style.css file inside the folder as shown below.

assets_folder_location

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

output

So then, that’s it for this Android tip. Keep visiting for more! :)

Reference: Android WebView

Android Tools: ProGuard

Hey friends!

The Android SDK comes shipped with a bunch of tools that allow developers to create even better mobile applications. It is seldom that we use these tools, mainly due to the lack of understanding or awareness. ProGuard, for instance, is one such tool that is integrated into the Android build system, so you do not have to invoke it manually.

Today, it is quite easy to reverse engineer Android applications. If one wants to prevent this from happening, one should use ProGuard for its main function i.e code obfuscation. As mentioned on the developer’s page, the ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. Through this post, we will learn how to use ProGuard in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Launch Eclipse IDE and open any of your existing Android projects.

Step 2: Enable ProGuard

Open up the file project.properties in the Eclipse text editor and uncomment the following line by removing the # symbol in the first column,

#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

Thus, ProGuard is now enabled. However, if there are any classes that you do not want to obfuscate, then the class must be added to the proguard-project.txt file as follows,

-keepclassmembers class com.app.test.TestArrowActivity {
public *;
}

Now, go ahead and create a signed APK of your Android project and use dex2jar to reverse engineer the executable APK. Here is the screenshot of a decompiled obfuscated Android APK followed by the image of a class that we chose not to obfuscate.

output_1

output_2

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

Reference: Android ProGuard

Tutorial #88: Using JUnit framework in Android

Hello everyone!

In one of my previous tutorials, we had seen how to use the robotium framework for writing black-box tests for Android applications. Apart from Robotium, there are many tools that can be used for testing Android applications. JUnit is a unit testing framework for Java useful in test-driven development. It can also be used to test Android applications.

As mentioned on the developer’s page, Android test suites are based on JUnit. Developers can use plain JUnit to test a class that doesn’t call the Android API, or Android’s JUnit extensions to test Android components. Through this tutorial, we will learn how to use JUnit to test Android applications.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create a new Android application project called AndroidJUnitExample with package name com.app.junit. Choose the target SDK as Android 4.4.

Step 2: Create Activity class

Let’s create an Activity class called MainActivity to display a sample text along with a button.

MainActivity.java

package com.app.jnuit;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private Button m_btnSubmit;
	private TextView m_tvSample;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		m_btnSubmit = (Button)findViewById(R.id.btnSubmit);
		m_tvSample = (TextView)findViewById(R.id.txtView1);
		
		m_btnSubmit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				m_tvSample.setText("button clicked");
				finish();
			}
		});
	}
}

activity_main.xml

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

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

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

</RelativeLayout>

Step 3: Create Android test project

Right click your existing Android project, select Android Tools -> New Test Project. Let the test project name be AndroidJUnitTest with package name com.app.junit.test.

Using the JUnit framework, we would be creating a test case to detect the change in text once a button is clicked. The test case is successful if the text of the TextView has changed to “button clicked”. In order to implement let’s create our test case class as follows.

MyTestCase.java

package com.app.jnuit.test;

import android.content.Intent;
import android.test.suitebuilder.annotation.MediumTest;
import android.widget.Button;
import android.widget.TextView;

import com.app.jnuit.MainActivity;

public class MyTestCase extends android.test.ActivityUnitTestCase<MainActivity> {


	private Intent mStartIntent;

	public MyTestCase() {
		super(MainActivity.class);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void setUp() throws Exception {
		// TODO Auto-generated method stub
		super.setUp();
		mStartIntent = new Intent(Intent.ACTION_MAIN);
	}

	@Override
	protected void tearDown() throws Exception {
		// TODO Auto-generated method stub
		super.tearDown();

	}

	@MediumTest
	public void testButtonClick() {

		startActivity(mStartIntent, null, null);
		TextView mTestMessage = (TextView)getActivity().findViewById(com.app.jnuit.R.id.txtView1);
		Button mTestButton = (Button) getActivity().findViewById(com.app.jnuit.R.id.btnSubmit);
		
		assertNotNull(getActivity());
		assertNotNull(mTestButton);
		assertNotNull(mTestMessage);

		//perform button click
		mTestButton.performClick();
		final String msg = mTestMessage.getText().toString();
		
		//check if text of TextView has changed
		if(msg.equalsIgnoreCase("button clicked")){

			assertTrue("text changed", true);
			
			//check if activity is finish or finish() is called
			assertTrue(isFinishCalled());
		}
				
	}

}

Finally, save all changes and run the test project. If the test cases are successful then you should see the following output!

testcase_output

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

Reference: Android Testing

Using Menus in Android

Hey everyone!

[This is a long overdue post]

The Android mobile user interface has been constantly evolving. Beginning with Android 3.0, devices no longer provide a dedicated Menu button. However, in order to provide a consistent user experience, developers need to use the Menu API’s to present common user actions on devices running Gingerbread (2.3.3) and below.

Android provides three different types of menus. The options menu is the primary collection of menu items for an activity. Users can open the options menu panel by pressing the Menu button. A context menu is a floating menu that appears when the user performs a long-click on an element. For example, long press an item of a ListView to obtain the corresponding menu. Finally, a popup menu displays a list of items in a vertical list that’s anchored to the view that invoked the menu.

Through this post, we will learn how to implement an options and a context menu in Android.

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

Step 1: Create options menu

In order to create an options menu, we need to first define it using XML as follows. Create a new XML file called menu_option.xml in the res/menu directory of any of your existing Android projects.

menu_option.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_apple"
        android:title="Apple"/>
    <item
        android:id="@+id/menu_orange"
        android:title="Orange"/>
    <item
        android:id="@+id/menu_mango"
        android:title="Mango"/>
    <item
        android:id="@+id/menu_image"
        android:icon="@drawable/ic_launcher"
        android:title="Image"/>

</menu>

Step 2: Now let’s create an Activity class called MyMenuActivity and add the following code!

MyMenuActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MyMenuActivity extends Activity{

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_option, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()){
		case R.id.menu_apple:
			Toast.makeText(MyMenuActivity.this, "You selected apple", Toast.LENGTH_SHORT).show();
			return true;

		case R.id.menu_orange:
			Toast.makeText(MyMenuActivity.this, "You selected orange", Toast.LENGTH_SHORT).show();
			return true;

		case R.id.menu_mango:
			Toast.makeText(MyMenuActivity.this, "You selected mango", Toast.LENGTH_SHORT).show();
			return true;

		case R.id.menu_image:
			Toast.makeText(MyMenuActivity.this, "You selected an image", Toast.LENGTH_SHORT).show();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}
}

activity_menu_option.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">

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

</RelativeLayout>

Step 3: Create context menu

In order to implement a context menu, we need to create a ListView as follows!

activity_menu_context.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">  
  
    <ListView  
        android:id="@+id/listView1"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true">  
    </ListView>  
  
</RelativeLayout>  

We then need to modify our MyMenuActivity class to now display a context menu instead of an option menu.

MyMenuActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MyMenuActivity extends Activity{

	private ListView m_listView;
	private String countries[]={"India","Spain","Portugal","Germany","France"};  

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

		m_listView=(ListView)findViewById(R.id.listView1);  

		ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,countries);  
		m_listView.setAdapter(adapter);  

		registerForContextMenu(m_listView);  

	}


	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);  
		menu.setHeaderTitle("Select the option");    
		menu.add(0, v.getId(), 0, "Population");  
		menu.add(0, v.getId(), 0, "States");   
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getTitle()=="Population"){  
			Toast.makeText(getApplicationContext(),"this will fetch the population",Toast.LENGTH_LONG).show();  
		}    
		else if(item.getTitle()=="States"){  
			Toast.makeText(getApplicationContext(),"this will fetch the number of states",Toast.LENGTH_LONG).show();  
		}else{  
			return false;  
		}    
		return true;    
	}  

}

Finally, save all changes. Make sure no errors are present. Run the application on an Android device/emulator and you should see the respective menus in Android.

option_menu_1

option_menu_2

context_menu_1

context_menu_2

context_menu_3

Reference: Android Menus

Tutorial #87: Implement ContentProvider in Android

Hey everyone!

As developers, we often need to create applications that can share data with other applications residing on the Android device. A content provider is similar to a database where one can query it, edit its content, as well as add or delete content using insert, update, delete, and query methods.

As mentioned on the developer’s page, Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. In this tutorial, we will learn how to implement a Content provider in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Launch Eclipse IDE and create a new Android application project called AndroidContentProviderExample with package name com.app.myprovider and choose the target SDK as Android 4.4

Step 2: Create ContentProvider class

Let’s write our own ContentProvider that will enable users to add a particular name in the Student table of the College database. Create a new class called MyProvider and write the following code!

MyProvider.java

package com.app.myprovider;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class MyProvider extends ContentProvider {

	public static final String PROVIDER_NAME = "com.app.provider.Names";
	public static final String URL = "content://" + PROVIDER_NAME + "/names";
	public static final Uri CONTENT_URI = Uri.parse(URL);
	public static final String NAME = "name";
	public static final String ID = "id";
	private static HashMap<String, String> namesMap;

	//database variables
	DBHelper dbHelper;
	private SQLiteDatabase database;
	static final String DATABASE_NAME = "College";
	static final String TABLE_NAME = "Student";
	static final int DATABASE_VERSION = 1;
	static final String CREATE_TABLE = 
			" CREATE TABLE " + TABLE_NAME +
			" (id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
			" name TEXT NOT NULL);";

	// integer values used in content URI
	static final int NAMES = 1;
	static final int NAMES_ID = 2;
	static final UriMatcher uriMatcher;
	static{
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(PROVIDER_NAME, "names", NAMES);
		uriMatcher.addURI(PROVIDER_NAME, "names/#", NAMES_ID);
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		Context context = getContext();
		dbHelper = new DBHelper(context);
		// permissions to be writable
		database = dbHelper.getWritableDatabase();

		if(database == null)
			return false;
		else
			return true;	
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		queryBuilder.setTables(TABLE_NAME);

		switch (uriMatcher.match(uri)) {
		// maps all database column names
		case NAMES:
			queryBuilder.setProjectionMap(namesMap);
			break;
		case NAMES_ID:
			queryBuilder.appendWhere( ID + "=" + uri.getLastPathSegment());
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		if (sortOrder == null || sortOrder == ""){
			sortOrder = NAME;
		}
		Cursor cursor = queryBuilder.query(database, projection, selection, 
				selectionArgs, null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);

		return cursor;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		long row = database.insert(TABLE_NAME, "", values);

		// If record is added successfully
		if(row > 0) {
			Uri newUri = ContentUris.withAppendedId(CONTENT_URI, row);
			getContext().getContentResolver().notifyChange(newUri, null);
			return newUri;
		}
		throw new SQLException("Fail to add a new record into " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		int count = 0;

		switch (uriMatcher.match(uri)){
		case NAMES:
			// delete all the records of the table
			count = database.delete(TABLE_NAME, selection, selectionArgs);
			break;
		case NAMES_ID:
			//gets the id
			String id = uri.getLastPathSegment();		
			count = database.delete( TABLE_NAME, ID +  " = " + id + 
					(!TextUtils.isEmpty(selection) ? " AND (" + 
							selection + ')' : ""), selectionArgs);
			break;
		default: 
			throw new IllegalArgumentException("Unsupported URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}


	private static class DBHelper extends SQLiteOpenHelper {

		public DBHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL(CREATE_TABLE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			Log.w(DBHelper.class.getName(),
					"Upgrading database");
			db.execSQL("DROP TABLE IF EXISTS " +  TABLE_NAME);
			onCreate(db);
		}

	}


}

Step 3: Create Activity class

Next, let’s create our Activity class called MainActivity that will allow user to add, delete or show the respective values.

MainActivity.java

package com.app.myprovider;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

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

        //delete all the records and the table of the database provider
	public void deleteAllNames(View view) {
		String URL = "content://com.app.provider.Names/names";
		Uri friends = Uri.parse(URL);
		int count = getContentResolver().delete(
				friends, null, null);
		String countNum = "App: "+ count +" records are deleted.";
		Toast.makeText(getBaseContext(), 
				countNum, Toast.LENGTH_LONG).show();

	}

        //add a new name
	public void addName(View view) {
		ContentValues values = new ContentValues();

		values.put(MyProvider.NAME, 
				((EditText)findViewById(R.id.name)).getText().toString());

		Uri uri = getContentResolver().insert(
				MyProvider.CONTENT_URI, values);

		Toast.makeText(getBaseContext(), 
				"App:" + uri.toString() + " inserted!", Toast.LENGTH_LONG).show();
	}

        //display all names
	public void showAllNames(View view) {
		String URL = "content://com.app.provider.Names/names";
		Uri friends = Uri.parse(URL);
		Cursor c = getContentResolver().query(friends, null, null, null, "name");
		String result = "App Results:";

		if (!c.moveToFirst()) {
			Toast.makeText(this, result+" no content yet!", Toast.LENGTH_LONG).show();
		}else{
			do{
				result = result + "\n" + c.getString(c.getColumnIndex(MyProvider.NAME)); 
			} while (c.moveToNext());
			Toast.makeText(this, result, Toast.LENGTH_LONG).show();
		}

	}

}

activity_main.xml

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

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/name" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:layout_marginTop="30dp"
        android:onClick="addName"
        android:text="@string/add" />

    <Button
        android:id="@+id/btnShow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnAdd"
        android:layout_below="@+id/btnAdd"
        android:layout_marginTop="20dp"
        android:onClick="showAllNames"
        android:text="@string/show" />

    <Button
        android:id="@+id/btnDelete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnShow"
        android:layout_below="@+id/btnShow"
        android:layout_marginTop="20dp"
        android:onClick="deleteAllNames"
        android:text="@string/delete" />

</RelativeLayout>

strings.xml

    <string name="name">Name</string>
    <string name="add">Add a new name</string>
    <string name="show">Show all names</string>
    <string name="delete">Delete all names</string>

Step 4: Register Provider in Manifest file

Further, for Android to use our provider it is important to register the same in the AndroidManifest.xml as follows!

AndroidManifest.xml

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

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

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

        <provider
            android:name=".MyProvider"
            android:authorities="com.app.provider.Names" >
        </provider>

    </application>
</manifest>

Finally, make sure no errors are present. Run the application on an Android device and you should be able to insert, delete and display the list of names as follows! :)

output_1

output_2

output_3

output_4

Reference: Android Content Providers

Display incoming SMS messages in Android

Hi guys,

In the past, we have seen how a Broadcast Receiver can be used to listen to certain events and in turn notify the user when the particular event occurs. In general, a broadcast originates from the system as well as applications.

It is important to register a broadcast receiver for a particular action. One of the ways of registering the same is by using the receiver tag in the AndroidManifest.xml file. Through this post, we will learn how to listen to incoming SMS text messages in Android using a broadcast receiver.

Pre-requisites: Eclipse IDE, Android SDK

Launch Eclipse IDE and in any of your existing Android application projects create a new class called MySMSApp and add the following code.

MySMSApp.java

package com.example;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class MySMSApp extends BroadcastReceiver {

	public static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if (intent.getAction().equals(ACTION)){ 
			Bundle bundle = intent.getExtras();
			if (bundle != null){
				Object[] pdus = (Object[]) bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[pdus.length];
				for (int i = 0; i < pdus.length; i++){
					messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}
				for (SmsMessage message : messages){
					
					String strMessageFrom = message.getDisplayOriginatingAddress();
					String strMessageBody = message.getDisplayMessageBody();

					Toast.makeText(context, "SMS Message received from:" +strMessageFrom, Toast.LENGTH_LONG).show();
					Toast.makeText(context, "SMS Message content" +strMessageBody, Toast.LENGTH_LONG).show();

				}
			}    
		} 
	}

}

Once we have implemented our receiver class, it is important to register the same 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.RECEIVE_SMS" />

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

        <!-- Receiver for SMS -->
        <receiver android:name=".MySMSApp">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Save all changes. Make sure no errors are present. Run the application on an Android device. The next time you get an SMS message, you should see the following output!

output

That’s it for this Android tip. Still lots more to come…! :)

Implement DialogFragment in Android

Hello everyone!

Users often need to make certain choices while using an application. A dialog resembles a small window that helps the user to make a decision or enter any additional information. If an application consists of a number of dialogs, one would possibly go ahead and create multiple “Yes/No” dialogs. However, if fragments are used within your Activity, then you need to use DialogFragment in order to present a fragment as a dialog (window). A simple Dialog won’t help in this case as it has nothing to do with the fragment’s life-cycle.

DialogFragments and Fragments are made available in the support library which makes the class usable in all currently used versions of Android. On the whole, a DialogFragment is pretty similar to a Dialog. It’s just wrapped inside a fragment. Through this post, we will learn how to implement a DialogFragment in Android.

Pre-requisites: Eclipse IDE, Android SDK

In any of your existing Android projects, creating a new Activity class called TestDialogFragmentActivity with package name com.example and add the following code.

TestDialogFragmentActivity.java

package com.example;

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TestDialogFragmentActivity extends FragmentActivity {

	private Button btnOpenFragment;
	FragmentManager fm = getSupportFragmentManager();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fragment);

		btnOpenFragment = (Button) findViewById(R.id.btnfragment);
		btnOpenFragment.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
			      MyDialogFragment dialogFragment = new MyDialogFragment();
			      dialogFragment.show(fm, "Dialog Fragment");
			}
		});

	}
}

Now, let’s implement the DialogFragment class for the same. Create a new class called MyDialogFragment and add the following code.

MyDialogFragment.java

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyDialogFragment extends DialogFragment {


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		View rootView = inflater.inflate(R.layout.dialog_fragment, container,false);
        getDialog().setTitle("DialogFragment Example");        
       
        return rootView;
	}	
}

The layout files would be as follows,

activity_fragment.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" >
 
    <Button
        android:id="@+id/btnfragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/dialogFragment" />

</RelativeLayout>

dialog_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:text="@string/txtFragment" />

</RelativeLayout>

strings.xml

    <string name="txtFragment">Hi. This is a dialog fragment</string>
    <string name="dialogFragment">Open DialogFragment</string>

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

output_1

output_2

Reference: Android DialogFragment

The torchbearers of life!

Bob Talbert, renowned columnist at The State newspaper in Columbia once said,

“Teaching kids to count is fine but teaching them what counts is best”.

During our childhood days, we always try and seek advice from our elders, be it our parents or teachers. However, many of us forget to thank them and wait for that one calendar day. Here’s a small piece that aims to bring out the student in you. Remember it’s never too late!

Sometimes I wonder if there wasn’t a teacher,
Our lives would resemble a room without furniture,
If there wasn’t anyone who would care and share,
I would have lived but in utter despair.

If there wasn’t a teacher I would have never learn to forgive,
With her holding my hand, she taught me to give,
Something’s in life we ought to learn,
For that we need a constant source like a teacher not just candles that burn.

We all are human beings and often commit a mistake,
But a teacher is someone special, who does it all for our sake,
Then too we fail to thank her and wait for “some day”,
We try to make up for it but time passes away.

My heart goes out to all our teachers,
Whose patience and devotion matches the best of preachers,
With seventy odd disciples shouting and screaming in a pile,
There can only be a teacher who would still stand and smile! :)

teachers_day

Getting started with Android Wear!

Hello everyone!

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

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

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

Step 1: Download Android Wear SDK

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

sdk_manager

Step 2: Create new Android Wear project

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

Next, add the following code in your Activity class.

MainActivity.java


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

public class MainActivity extends Activity {

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


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

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

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

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

	}
 }

activity_main.xml

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

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

</RelativeLayout>

strings.xml

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

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

output_1

output_2

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

Reference: Android Wear Notifications