In this tutorial we will see how to send mail from one mobile to another mobile. Android supports email service. The Gmail/Email application on Android enables you to configure an email account using POP3 or IMAP, You can also send  email messages programmatically from within your android application. The following Try It Out show you how...


TRY IT OUT Sending E‑ mail Programmatically


1. Using Eclipse, create a new Android project and name it EmailSendExample.

2. Add the following statements to the main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <Button android:id="@+id/clickBtn" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_gravity="center" />
</LinearLayout>

3. Add the following statements in bold to the Main.java file:


package com.thedevelopersinfo.tutorial.android.emailsendexample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
    private Button clickBtn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        clickBtn = (Button) findViewById(R.id.clickBtn);
        clickBtn.setText("Send email");
        clickBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                String[] recipients = new String[]{"server.mumbai@gmail.com"};
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Test");
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hello Friend");
                emailIntent.setType("text/plain");
                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                finish();
            }
        });
    }
}
4.   Press F11 to test the application on a real Android device. Click the Send Email button and you should see the Email application launched in your device.



How It Works


In this tutorial, you are launching the built-in Email application to send an e‑mail message. To do so, you use an Intent object and set the various parameters using the setData(), putExtra(), and setType() methods:

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String[] recipients = new String[]{"server.mumbai@gmail.com"};
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Test");
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hello Friend");
                emailIntent.setType("text/plain");           
startActivity(Intent.createChooser(emailIntent, "Send mail...")); 
finish();
Download Code

In this tutorial we will see how it shows a list of completion suggestions automatically while the user is typing. The AutoCompleteTextView is a view that is similar to EditText(in fact it is a subclass of EditText). Try  It Out shows how to uses the AutoCompleteTextView to automatically help users complete the text entry.

TRY IT OUT Using the AutoCompeteTextView


1.    Using Eclipse, Create an Android project and name it AutoCompleteTextView.

2.    Modify the main.xml file located in the res/layout folder as shown here:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<AutoCompleteTextView
android:id="@+id/AndroidBooks"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</AutoCompleteTextView>
</LinearLayout>

3.    Add the following statements to AutoCompleteText.java file:

package com.sai.samples.views;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class AutoCompleteText extends Activity
{
String[] androidBooks =
{
"Hello, Android - Ed Burnette",
"Professional Android 2 App Dev - Reto Meier",
"Unlocking Android - Frank Ableson",
"Android App Development - Blake Meike",
"Pro Android 2 - Dave MacLean",
"Beginning Android 2 - Mark Murphy",
"Android Programming Tutorials - Mark Murphy",
"Android Wireless App Development - Lauren Darcey",
"Pro Android Games - Vladimir Silva",
};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,androidBooks);
AutoCompleteTextView acTextView = (AutoCompleteTextView)findViewById(R.id.AndroidBooks);
acTextView.setThreshold(1);
acTextView.setAdapter(adapter);
}
}
4.    Press F11 to debug the application on the Android Emulator. The below screen shown a list of matching names appears as you type into the AutoCompleteTextView.


How it Works:


In the MainActivity class, you first create a String array containing a list of presidents’ names:

String[] androidBooks =
{
"Hello, Android - Ed Burnette",
"Professional Android 2 App Dev - Reto Meier",
"Unlocking Android - Frank Ableson",
"Android App Development - Blake Meike",
"Pro Android 2 - Dave MacLean",
"Beginning Android 2 - Mark Murphy",
"Android Programming Tutorials - Mark Murphy",
"Android Wireless App Development - Lauren Darcey",
"Pro Android Games - Vladimir Silva",
};

The ArrayAdapter object manages the array of strings that will be displayed by the AutoCompleteTextView. In the preceding example, you set the AutoCompleteTextView to display in the simple_dropdown_item_ 1line mode:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,androidBooks);

The setThreshold() method sets the minimum number of characters the user must type before the suggestions
appear as a drop-down menu:

textView.setThreshold(3);

The list of suggestions to display for the AutoCompleteTextView is obtained from the ArrayAdapter object:

textView.setAdapter(adapter);
Download Code

In android user interface is displayed through an activity. Before you are going to develope android application you must understand about activity. This fuction helps to makes connection between two activity. Now we will discuss briefly about this activity...


1.Opening new Activity


To open new activity following startActivity method will be used.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);


2.Sending parameters


To send parameter to newly created activity putExtra() method will be used.

i.putExtra("key", "value");
// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");


3.Receiving parameters


To receive parameters on newly created activity getStringExtra() method will be used.
Intent i = getIntent();
i.getStringExtra("key");
// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");


4.Opening new Activity and expecting result


In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
// Function to read the result from newly created activity
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100)
{
// Storing result in a variable called myvar
// get("website") 'website' is the key value result data
String mywebsite = data.getExtras().get("result");
}
}


5.Sending result back to old activity when StartActivityForResult() is used


Intent i = new Intent();
// Sending param key as 'website' and value as 'innovationonandroid'
i.putExtra("website", "innovationonandroid.in");
// Setting resultCode to 100 to identify on old activity
setResult(100,in);


6.Closing Activity


To close activity call finish() method.

finish();


7.Add entry in AndroidManifest.xml


To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags.

<activity android:name=".NewActivityClassName"></activity>


Let’s Start with a simple project




So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xml, screen2.xml) and two Acvities(FirstScreenActivity.java, SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this tutorial.

1. Create a new project File -> Android Project. While creating a new project give activity name as FirstScreenActivity.
2. Now you need to create user interface for the FirstScreenActivity.java
3. Create a new xml file in layout folder or rename the main.xml to screen1.xml
Right Click on Layout -> New -> Android XML file and name it as screen1.xml
4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">  
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Name: "/>
<EditText android:id="@+id/name" 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"/>          
<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Email: "/>
<EditText android:id="@+id/email" 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"/>
<Button android:id="@+id/btnNextScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click me"
android:layout_marginTop="15dip"/>
</LinearLayout>



5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.

package com.example.androidswitchviews;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class FirstScreenActivity extends Activity {
// Initializing variables
EditText inputName;
EditText inputEmail;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
//Listening to button event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), SecondScreenActivity.class);
//Sending data to another Activity
nextScreen.putExtra("name", inputName.getText().toString());
nextScreen.putExtra("email", inputEmail.getText().toString());
// starting new activity
startActivity(nextScreen);
}
});
}
}

6. Create a class called SecondScreenActivity.java. Right Click on src/yourpackagefolder -> New -> Class and name it as SecondScreenActivity.java


7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml. Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the following code in screen2.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"> 
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You Entered..."
android:textSize="25dip"
android:gravity="center"
android:layout_margin="15dip"/>
<TextView android:id="@+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:textSize="18dip"/>
<TextView android:id="@+id/txtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:textSize="18dip"/>
<Button android:id="@+id/btnClose"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:text="Close"/>
</LinearLayout>

8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen.

package com.example.androidswitchviews;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SecondScreenActivity extends Activity {
 /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
Button btnClose = (Button) findViewById(R.id.btnClose);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String email = i.getStringExtra("email");
 // Displaying Received data
txtName.setText(name);
txtEmail.setText(email);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
finish();
}
});
}
}
9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code.
10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You can see the application is running by switching between screens. The below image is output screenshots of both xml files.


Download Code

Here i explained a designing login interfaces, it has no functionality. In this tutorial i am explaining how to build login form in android using php,mysql.This tutorial covers how to build api using php and mysql.


API (Application Programming Interface)


Accepting requests by GET/POST methods
Interact with PHP classes to get data from database or store in database.


1.Creating MySQL Database and Tables


A i am writing php code for connecting mysql database to maintain users. Open your mysqlconsole or phpmyadmin and run following query to create database.
a)create database mydatabase 
b)use mydatabase 
c)create table tbl_user( username varchar(20),  password varchar(20));



2.Building PHP


Following are the files are required to build api in php. You can find description of file below.
check.php - This file contains variables to connect to datbase and and retrive value form it.



Check.php:

<?php
$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) { 
echo "No Such User Found"; 
}
else  {
echo "User Found"; 
}
?>


3.Starting Android Project


Until now we wrote a server side programming to connect database. Next thing is build android app to interact with database. In this project i am coding simple app which  will have two screen login screen, Success screen. So lets get started by creating new project in Eclipse IDE
1. Create a new project by going to File ⇒ New Android Project. Fill all the details and name your activity as Androidphpconnectiondemo. 

2. Next step is to create a new package to store all our library files. Right Click on ⇒ src ⇒ New ⇒ Package and name it as library.



4.Database Handler


In the application to retrieve user information i am using mysql datbase. So create new class in you library package folder and name it as androidphpconnectiondemo.java and fill the class with following code. This class file has function to handle database operation like retrieve user information.

public class AndroidPHPConnectionDemo extends Activity 
{
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);       
b = (Button)findViewById(R.id.Button01);  
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);      
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "", "Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();      
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/my_folder_inside_htdocs/check.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  
// $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response); 
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert()
{
AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable()
{
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")  
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id) 
{
}
});           
AlertDialog alert = builder.create();
alert.show();    
}
});
}
}


5. User Functions


Create a new class file under libray package name it as userpage.java this class will have function to handle all user event.
Android application testing localhost use http://localhost/your phpfile location with".phpfile" 
Normally localhost will run on port http://localhost/. In avd to connect to localhost you need to use url http://10.0.2.2/
if you want to deploy your api on website then use the url http://yoursite.com/api/

public class UserPage extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.userpage);
}
}


6. Designing the Screens


As of now we have developed the class file in this application. Next thing we have to build screen for useinteraction. we need two screen loginscreen and success screen.
Create 3xml file under res->layout folder and name them as userpage.xml. In main.xml i build login screen.



Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center|center_vertical"    >
<TextView 
android:id="@+id/tv0"  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Login Form"
android:textSize="20sp"
android:gravity="center"
android:textStyle="bold"    />
<TextView 
android:id="@+id/tv1"  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Username"    />
<EditText 
android:text="" 
android:id="@+id/username" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:singleLine="true">
</EditText>
<TextView 
android:id="@+id/tv2"  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Password"    />
<EditText 
android:text="" 
android:id="@+id/password" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:singleLine="true">
</EditText>
<Button 
android:text="Login" 
android:id="@+id/Button01" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</Button>
<TextView 
android:id="@+id/tv"  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text=""    />
</LinearLayout>



userpage.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView 
android:text="Login Success." 
android:id="@+id/TextView01" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</TextView>
</LinearLayout>


7.AndroidManifest


Dont forget to update you androidmanifest.xml file. Change following modifications add internet permission and add entries of each activity.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.coderzheaven"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidPHPConnectionDemo"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".UserPage"
android:label="@string/app_name" />
</application>
</manifest> 


8. Make sure the above file you have placed in following image


9.Final Output

Download Code