Tuesday, 23 August 2016

SIMPLE LOGIN APPS EXAMPLE WITH PHP WEBSRVICE


Write code for   “loginpost .php”    file  for  webservice  :

<?php

$username = $_POST['username'];
$password = $_POST['password'];

if($username=="om" && $password=="admin")
{
echo "true";
}
else
{
echo " false";
}

?>


and  upload  it to the server  and copy link:

http://funmoviemasti.com/om/loginpost.php



(1)Write code for   MainActivity.java   login:
package com.guru.login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

   
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds

   
public static final int CONNECTION_TIMEOUT=10000;
   
public static final int READ_TIMEOUT=15000;
   
private EditText etEmail;
   
private EditText etPassword;

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

       
// Get Reference to variables
       
etEmail = (EditText) findViewById(R.id.email);
       
etPassword = (EditText) findViewById(R.id.password);

    }

   
// Triggers when LOGIN Button clicked
   
public void checkLogin(View arg0) {

       
// Get text from email and passord field
       
final String email = etEmail.getText().toString();
       
final String password = etPassword.getText().toString();

           
// Initialize  AsyncLogin() class with email and password
           
new AsyncLogin().execute(email,password);

    }

   
private class AsyncLogin extends AsyncTask<String, String, String>
    {
        ProgressDialog
pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection
conn;
        URL
url = null;

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

           
//this method will be running on UI thread
           
pdLoading.setMessage("\tLoading...");
           
pdLoading.setCancelable(false);
           
pdLoading.show();

        }
       
@Override
       
protected String doInBackground(String... params) {
           
try {

               
// Enter URL address where your php file resides
               
url = new URL("http://funmoviemasti.com/om/loginpost.php");

            }
catch (MalformedURLException e) {
               
// TODO Auto-generated catch block
               
e.printStackTrace();
               
return "exception";
            }
           
try {
                
// Setup HttpURLConnection class to send and receive data from php and mysql
               
conn = (HttpURLConnection)url.openConnection();
               
conn.setReadTimeout(READ_TIMEOUT);
               
conn.setConnectTimeout(CONNECTION_TIMEOUT);
               
conn.setRequestMethod("POST");

               
// setDoInput and setDoOutput method depict handling of both send and receive
               
conn.setDoInput(true);
               
conn.setDoOutput(true);

               
// Append parameters to URL
               
Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter(
"username", params[0])
                        .appendQueryParameter(
"password", params[1]);
                String query = builder.build().getEncodedQuery();

               
// Open connection for sending data
               
OutputStream os = conn.getOutputStream();
                BufferedWriter writer =
new BufferedWriter(
                       
new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
               
conn.connect();

            }
catch (IOException e1) {
               
// TODO Auto-generated catch block
                
e1.printStackTrace();
               
return "exception";
            }

           
try {

               
int response_code = conn.getResponseCode();

               
// Check if successful connection made
               
if (response_code == HttpURLConnection.HTTP_OK) {

                   
// Read data sent from server
                   
InputStream input = conn.getInputStream();
                    BufferedReader reader =
new BufferedReader(new InputStreamReader(input));
                    StringBuilder result =
new StringBuilder();
                    String line;

                   
while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                   
// Pass data to onPostExecute method
                   
return(result.toString());

                }
else{

                   
return("unsuccessful");
                }

            }
catch (IOException e) {
                e.printStackTrace();
               
return "exception";
            }
finally {
               
conn.disconnect();
            }


        }

       
@Override
       
protected void onPostExecute(String result) {

           
//this method will be running on UI thread

           
pdLoading.dismiss();

            
if(result.equalsIgnoreCase("true"))
            {
               
/* Here launching another activity when login successful. If you persist login state
                use sharedPreferences of Android. and logout button to clear sharedPreferences.
                 */

               
Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
                startActivity(intent);
                MainActivity.
this.finish();

            }
else if (result.equalsIgnoreCase("false")){

                
// If username and password does not match display a error message
               
Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            }
else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.
this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

            }
        }

    }
}

(2)write  code  for activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">



    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:inputType="textEmailAddress"

        android:ems="10"

        android:id="@+id/email"

        android:layout_alignParentTop="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:hint="Email"

        android:layout_marginTop="10dp"/>



    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:inputType="textPassword"

        android:ems="10"

        android:id="@+id/password"

        android:layout_below="@+id/email"

        android:hint="Password"

        android:layout_marginTop="10dp"/>



    <Button

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="LOGIN"

        android:id="@+id/button"

        android:layout_below="@+id/password"

        android:layout_marginTop="10dp"

        android:onClick="checkLogin"/>



</RelativeLayout>

(3)write code for   SuccessActivity.java file:
package com.guru.login;



import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;



public class SuccessActivity extends AppCompatActivity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_success);

    }

}

(4)write   code for  activity_success.xml file:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin">



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceLarge"

        android:text="WELCOME"

        android:id="@+id/textView"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="62dp" />



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceMedium"

        android:text="Successfully LoggedIn"

        android:id="@+id/textView2"

        android:layout_marginTop="46dp"

        android:layout_below="@+id/textView"

        android:layout_centerHorizontal="true" />



</RelativeLayout>


 OUTPUT:




Monday, 22 August 2016

Android Registration and Login Code example with WEB SERVICE USING PHP & MYSQL

Web Service  Code  using PHP :

(1)write code for  dbconnect.php file :
<?php
               define('HOST','localhost');
               define('USER','vasaital_volley');
               define('PASS','rscoe@1234');
               define('DB','vasaital_volley');
              
               $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
(2)write  code for register.php file:
<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){
 $username = $_POST['username'];
 $email = $_POST['email'];
 $password = $_POST['password'];

 require_once('dbconnect.php');

 $sql = "INSERT INTO volley (username,password,email) VALUES ('$username','$email','$password')";


 if(mysqli_query($con,$sql))
 {
 echo "Successfully Registered";

 }
 else
 {
 echo "Could not register";

 }
 }
else
{
echo  'error';
}

?>

(3)write  code for loginpost.php file:
<?php

$con=mysql_connect("Localhost","vasaital_volley","rscoe@1234");

mysql_select_db("vasaital_volley",$con);

$username=$_POST['username'];

$password=$_POST['password'];

$sql="select  username , password from  volley where username='$username' AND password='$password'";

$result=mysql_query($sql);

$num=mysql_num_rows($result);

if($num>0)
{
echo "success";
}
else
{
echo " failure";
}
?>




now  write code for LoginActivity.java   file:

package net.simplifiedcoding.volleyinsertdata;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    public static final String LOGIN_URL = "http://vasaitaluka.com/mytesting/loginpost1.php";

    public static final String KEY_USERNAME="username";
    public static final String KEY_PASSWORD="password";

    private EditText editTextUsername;
    private EditText editTextPassword;
    private Button buttonLogin;

    private String username;
    private String password;

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

        editTextUsername = (EditText) findViewById(R.id.editTextUsername);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonLogin = (Button) findViewById(R.id.buttonLogin);

        buttonLogin.setOnClickListener(this);
    }


    private void userLogin() {
        username = editTextUsername.getText().toString().trim();
        password = editTextPassword.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if(response.trim().equals("success")){
                            openProfile();
                        }else{
                            Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG ).show();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<String,String>();
                map.put(KEY_USERNAME,username);
                map.put(KEY_PASSWORD,password);
                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    private void openProfile(){
        Intent intent = new Intent(this, ActivityUserProfile.class);
        intent.putExtra(KEY_USERNAME, username);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        userLogin();
    }
}

(2)write code for  MainActivity.java file:

package net.simplifiedcoding.volleyinsertdata;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String REGISTER_URL = "http://vasaitaluka.com/mytesting/register.php";

    public static final String KEY_USERNAME = "username";
    public static final String KEY_PASSWORD = "password";
    public static final String KEY_EMAIL = "email";


    private EditText editTextUsername;
    private EditText editTextEmail;
    private EditText editTextPassword;

    private Button buttonRegister;
    private Button buttonLogin;


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

        editTextUsername = (EditText) findViewById(R.id.editTextUsername);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);
        editTextEmail= (EditText) findViewById(R.id.editTextEmail);

        buttonRegister = (Button) findViewById(R.id.buttonRegister);
        buttonLogin = (Button) findViewById(R.id.buttonLogin);

        buttonRegister.setOnClickListener(this);
        buttonLogin.setOnClickListener(this);
    }

    private void registerUser(){
        final String username = editTextUsername.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();
        final String email = editTextEmail.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {
        if(v == buttonRegister){
            registerUser();
        }
        if(v == buttonLogin){
            startActivity(new Intent(this,LoginActivity.class));
        }
    }
}


(3)now write code for  ActivityUserProfile.java file:

package net.simplifiedcoding.volleyinsertdata;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class ActivityUserProfile extends AppCompatActivity {
    private TextView textView;

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

        textView = (TextView) findViewById(R.id.textViewUsername);

        Intent intent = getIntent();

        textView.setText("Welcome User " + intent.getStringExtra(LoginActivity.KEY_USERNAME));
    }


}

(4)write code activity_login.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.volleyinsertdata.LoginActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Username"
        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextUsername" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Password"
        />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextPassword" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/buttonLogin" />

</LinearLayout>

(5)write code for  activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Username" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextUsername" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="email" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextEmail" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:password="true"
        android:id="@+id/editTextPassword" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:id="@+id/buttonRegister" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/buttonLogin" />


</LinearLayout>

(6)write code for  activity_user_profile.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.volleyinsertdata.ActivityUserProfile">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textViewUsername"
        android:layout_gravity="center_horizontal" />

</LinearLayout>


Download  source code from :




Friday, 5 August 2016

Android -send email -code example-in Android studio

see directory structure given below and THEN  start coding:





(1)write  code  for SendEmailActivity.java    file:

package testing.om.com.sendemail;

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;
import android.widget.EditText;

public class SendEmailActivity extends Activity {

    Button
buttonSend;
    EditText
textTo;
    EditText
textSubject;
    EditText
textMessage;

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

       
buttonSend = (Button) findViewById(R.id.buttonSend);
       
textTo = (EditText) findViewById(R.id.editTextTo);
       
textSubject = (EditText) findViewById(R.id.editTextSubject);
       
textMessage = (EditText) findViewById(R.id.editTextMessage);

       
buttonSend.setOnClickListener(new OnClickListener() {

           
@Override
           
public void onClick(View v) {

                String to =
textTo.getText().toString();
                String subject =
textSubject.getText().toString();
                String message =
textMessage.getText().toString();

                Intent email =
new Intent(Intent.ACTION_SEND);
                email.putExtra(Intent.
EXTRA_EMAIL, new String[]{ to});
               
//email.putExtra(Intent.EXTRA_CC, new String[]{ to});
                //email.putExtra(Intent.EXTRA_BCC, new String[]{to});
               
email.putExtra(Intent.EXTRA_SUBJECT, subject);
                email.putExtra(Intent.
EXTRA_TEXT, message);

               
//need this to prompts email client only
               
email.setType("message/rfc822");

                startActivity(Intent.createChooser(email,
"Choose an Email client :"));

            }
        });
    }
}







(2)write code for  activity_send_email.xml  file:

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

<android.support.design.widget.CoordinatorLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:fitsSystemWindows="true"

    tools:context=".SendEmailActivity">



    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">



        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"

            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"

            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />



    </android.support.design.widget.AppBarLayout>



    <include layout="@layout/content_send_email" />



    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"

        android:layout_width="wrap_content" android:layout_height="wrap_content"

        android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"

        android:src="@android:drawable/ic_dialog_email" />



</android.support.design.widget.CoordinatorLayout>
 
 
(3)write  code for  content_send_email.xml  file:
 
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/linearLayout1"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >



    <TextView

        android:id="@+id/textViewPhoneNo"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="To : "

        android:textAppearance="?android:attr/textAppearanceLarge" />



    <EditText

        android:id="@+id/editTextTo"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:inputType="textEmailAddress" >



        <requestFocus />

    </EditText>



    <TextView

        android:id="@+id/textViewSubject"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Subject : "

        android:textAppearance="?android:attr/textAppearanceLarge" />



    <EditText

        android:id="@+id/editTextSubject"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        >

    </EditText>



    <TextView

        android:id="@+id/textViewMessage"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Message : "

        android:textAppearance="?android:attr/textAppearanceLarge" />



    <EditText

        android:id="@+id/editTextMessage"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:gravity="top"

        android:inputType="textMultiLine"

        android:lines="5" />



    <Button

        android:id="@+id/buttonSend"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="Send" />



</LinearLayout>
 


Output :









=====================================================================
Now write code for sending email  with Attachment of image file:



Send Email with Attachment in Android | Code for send email in Android | Sample demo for sending email in android with attachment
This is a simple demo for send email in Android with attachment. For attachment I am using Intent.ACTION_GET_CONTENT.
Don't forget to add permissions in your manifest.xml-

  <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />




(1)write  code  for MainActivity.java   file  :

package testing.om.com.sendemailwithattached;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 *
 * @author om sir
 *
 */
public class MainActivity extends Activity implements OnClickListener {

    EditText
editTextEmail, editTextSubject, editTextMessage;
    Button
btnSend, btnAttachment;
    String
email, subject, message, attachmentFile;
    Uri
URI = null;
   
private static final int PICK_FROM_GALLERY = 101;
   
int columnIndex;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
editTextEmail = (EditText) findViewById(R.id.editTextTo);
       
editTextSubject = (EditText) findViewById(R.id.editTextSubject);
       
editTextMessage = (EditText) findViewById(R.id.editTextMessage);
       
btnAttachment = (Button) findViewById(R.id.buttonAttachment);
       
btnSend = (Button) findViewById(R.id.buttonSend);

        
btnSend.setOnClickListener(this);
       
btnAttachment.setOnClickListener(this);
    }

   
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
            
/**
             * Get Path
             */
           
Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.
DATA };

            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn,
null, null, null);
            cursor.moveToFirst();
           
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
           
attachmentFile = cursor.getString(columnIndex);
            Log.e(
"Attachment Path:", attachmentFile);
           
URI = Uri.parse("file://" + attachmentFile);
            cursor.close();
        }
    }

   
@Override
   
public void onClick(View v) {

       
if (v == btnAttachment) {
            openGallery();

        }
       
if (v == btnSend) {
           
try {
                
email = editTextEmail.getText().toString();
               
subject = editTextSubject.getText().toString();
               
message = editTextMessage.getText().toString();

               
final Intent emailIntent = new Intent(
                        android.content.Intent.
ACTION_SEND);
                emailIntent.setType(
"plain/text");
                emailIntent.putExtra(android.content.Intent.
EXTRA_EMAIL,
                       
new String[] { email });
                emailIntent.putExtra(android.content.Intent.
EXTRA_SUBJECT,
                       
subject);
               
if (URI != null) {
                    emailIntent.putExtra(Intent.
EXTRA_STREAM, URI);
                }
                emailIntent
                        .putExtra(android.content.Intent.
EXTRA_TEXT, message);
               
this.startActivity(Intent.createChooser(emailIntent,
                       
"Sending email..."));

            }
catch (Throwable t) {
                Toast.makeText(
this,
                       
"Request failed try again: " + t.toString(),
                        Toast.
LENGTH_LONG).show();
            }
        }

    }

   
public void openGallery() {
        Intent intent =
new Intent();
        intent.setType(
"image/*");
        intent.setAction(Intent.
ACTION_GET_CONTENT);
        intent.putExtra(
"return-data", true);
        startActivityForResult(
                Intent.createChooser(intent,
"Complete action using"),
               
PICK_FROM_GALLERY);

    }

}


(2)write  code  for activity_main.xml file :

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

<android.support.design.widget.CoordinatorLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:fitsSystemWindows="true"

    tools:context=".MainActivity">



    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">



        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"

            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"

            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />



    </android.support.design.widget.AppBarLayout>



    <include layout="@layout/content_main" />



    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"

        android:layout_width="wrap_content" android:layout_height="wrap_content"

        android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"

        android:src="@android:drawable/ic_dialog_email" />



</android.support.design.widget.CoordinatorLayout>


(3)now write code for  content_main.xml file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:padding="5dp"

    tools:context=".MainActivity" >



    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_margin="5dp"

        android:layout_marginTop="20dp"

        android:orientation="vertical"

        android:padding="5dp" >



        <EditText

            android:id="@+id/editTextTo"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_alignParentLeft="true"

            android:layout_alignParentTop="true"

            android:layout_margin="5dp"

            android:layout_marginTop="200px"



            android:hint="Email Address!"

            android:inputType="textEmailAddress"

            android:singleLine="true" />



        <EditText

            android:id="@+id/editTextSubject"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_below="@id/editTextTo"

            android:layout_margin="5dp"

            android:hint="Subject"

            android:singleLine="true" />



        <EditText

            android:id="@+id/editTextMessage"

            android:layout_width="match_parent"

            android:layout_height="200dp"

            android:layout_below="@id/editTextSubject"

            android:layout_margin="5dp"

            android:gravity="top|left"

            android:hint="type message here!"

            android:inputType="textMultiLine" />



        <Button

            android:id="@+id/buttonSend"

            android:layout_width="80dp"

            android:layout_height="50dp"

            android:layout_below="@id/editTextMessage"

            android:layout_margin="5dp"

            android:text="Send" />



        <Button

            android:id="@+id/buttonAttachment"

            android:layout_width="wrap_content"

            android:layout_height="50dp"

            android:layout_alignParentRight="true"

            android:layout_alignParentTop="true"

            android:text="attachment" />

    </LinearLayout>



</ScrollView>






Output:






Recent Posts

Powered by Blogger.

Pages

About Me

My Photo
B.E.(COMPUTER ENGINEER) PHP Web developer & Provide Training for Web Development , Digital Marketing ,Android Mobile Apps Development

 

© 2013 ANDROID TRAINING IN MUMBAI BY OM SIR. All rights resevered. Designed by Templateism

Back To Top