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