Sunday 15 June 2014

Android send emails | Android send emails w/t built-in mailing app | Android send emails from the background

Hello Friends,
                Today, I am sharing another important tutorial. While doing development
some times we came across to this requirement, "Sending emails to users" without
using any built-in mailing app(like: Gmail,Yahoo etc). In that time we normally depends
on web-service, we write a service in PHP or JAVA or .Net and the communicate b/w them.

But, know now no need to depends on web-service we can send the mail directly through
our java code.

This tutorial going to covers following features :

1. Sending email without using any built-in mailing app
2. Sending emails without User Intervention
3. Sending  emails to multiple users
4. Sending emails with attachment
5. Sending emails silently without any mail composer


Here are my code:

1. Download java mil.jar, activation.jar and additionnal.jar from below link :
        http://code.google.com/p/javamail-android/downloads/list          

2. Add this jar files in your project libs folder

3. MainActivity.java

package com.androiddeveloper.solutions.sendemail;

import java.io.File;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

/**
 * @author: Mukesh Y
 * @link: http://www.androiddevelopersolutions.com/
 */
public class MainActivity extends Activity {

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

  ImageButton addImage = (ImageButton) findViewById(R.id.action_send_email);
  addImage.setOnClickListener(new View.OnClickListener() {
   public void onClick(View view) {
    new BackGroundAsyncTask().execute();
   }
  });

 }

 public class BackGroundAsyncTask extends AsyncTask {

  ProgressDialog prog_synprocess = new ProgressDialog(MainActivity.this);

  String statusMessage = "";

  @Override
  protected void onPostExecute(String status) {
   prog_synprocess.hide();
   Toast.makeText(MainActivity.this, status, Toast.LENGTH_LONG).show();

  }

  @Override
  protected void onPreExecute() {
   prog_synprocess.setCancelable(false);
   prog_synprocess.setProgressStyle(ProgressDialog.STYLE_SPINNER);
   prog_synprocess.setMessage("Sending...");
   prog_synprocess.show();
  }

  @Override
  protected String doInBackground(String... arg0) {

   try {
    statusMessage = sendLogFile();
   } catch (Exception e) {
    Log.e("Error", e.getMessage());
    statusMessage = "Error in updation";
   }
   return statusMessage;

  }
 }

 private String sendLogFile() {
  String statusMessage = "";
  Mail m = new Mail("dataworld.dw@gmail.com", "testtest");

  String[] toArr = { "mukesh421985@gmail.com" };
  m.setTo(toArr);
  m.setFrom("dataworld.dw@gmail.com");
  String email_subject = "Testing Send mail";
  m.setSubject(email_subject);
  m.setBody("PFA");

  try {
   String pathToMyAttachedFile = Environment
     .getExternalStorageDirectory()
     + File.separator
     + "Project.log";
   File file = new File(pathToMyAttachedFile);
   if (!file.exists() || !file.canRead()) {
    statusMessage = "File not found";
    return statusMessage;
   } else {
    m.addAttachment(file.getAbsolutePath());
   }
   if (m.send()) {
    statusMessage = "Email was sent successfully.";
   } else {
    statusMessage = "Email was not sent.";
   }
  } catch (Exception e) {
   // Toast.makeText(MailApp.this,
   // "There was a problem sending the email.",
   // Toast.LENGTH_LONG).show();
   Log.e("Send Mail", e.getMessage());
   statusMessage = "There was a problem sending the email.";
  }

  return statusMessage;
 }

}

2. Mail.java 

package com.androiddeveloper.solutions.sendemail;

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * @author: Mukesh Y
 * @link: http://www.androiddevelopersolutions.com/
 */
public class Mail extends javax.mail.Authenticator {
 private String userName;
 private String password;

 private String[] to;
 private String from;

 private String portNumber;
 private String socketPortNumber;

 private String host;

 private String emailSubject;
 private String emailBody;

 private boolean auth;

 private boolean debuggable;

 private Multipart multipart;

 public Mail() {
  // default smtp server
  host = "smtp.gmail.com";
  
  // default smtp port
  portNumber = "465"; 
  // default socketfactory port
  socketPortNumber = "465";
  
  // username
  userName = ""; 
  password = ""; 
  
  // email sent from
  from = ""; 
  
  // email subject
  emailSubject = "";
  
  // email body
  emailBody = ""; 

  // debug mode on or off - default off
  debuggable = false; 
  
  // smtp authentication - default on
  auth = true; 

  multipart = new MimeMultipart();

  // There is something wrong with MailCap, javamail can not find a
  // handler for the multipart/mixed part, so this bit needs to be added.
  MailcapCommandMap mc = (MailcapCommandMap) CommandMap
    .getDefaultCommandMap();
  mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
  mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
  mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
  mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
  mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
  CommandMap.setDefaultCommandMap(mc);
 }

 public Mail(String user, String pass) {
  this();

  userName = user;
  password = pass;
 }

 public boolean send() throws Exception {
  Properties props = _setProperties();

  if (!userName.equals("") && !password.equals("") && to.length > 0
    && !from.equals("") && !emailSubject.equals("")
    && !emailBody.equals("")) {
   Session session = Session.getInstance(props, this);

   MimeMessage msg = new MimeMessage(session);

   msg.setFrom(new InternetAddress(from));

   InternetAddress[] addressTo = new InternetAddress[to.length];
   for (int i = 0; i < to.length; i++) {
    addressTo[i] = new InternetAddress(to[i]);
   }
   msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

   msg.setSubject(emailSubject);
   msg.setSentDate(new Date());

   // setup message body
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setText(emailBody);
   multipart.addBodyPart(messageBodyPart);

   // Put parts in message
   msg.setContent(multipart);

   // send email
   Transport.send(msg);

   return true;
  } else {
   return false;
  }
 }

 public void addAttachment(String filename) throws Exception {
  BodyPart messageBodyPart = new MimeBodyPart();
  FileDataSource source = new FileDataSource(filename);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName(filename);

  multipart.addBodyPart(messageBodyPart);
 }

 @Override
 public PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(userName, password);
 }

 private Properties _setProperties() {
  Properties props = new Properties();

  props.put("mail.smtp.host", host);

  if (debuggable) {
   props.put("mail.debug", "true");
  }

  if (auth) {
   props.put("mail.smtp.auth", "true");
  }

  props.put("mail.smtp.port", portNumber);
  props.put("mail.smtp.socketFactory.port", socketPortNumber);
  props.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.socketFactory.fallback", "false");

  return props;
 }

 // the getters and setters
 public String getBody() {
  return emailBody;
 }

 public void setBody(String _body) {
  this.emailBody = _body;
 }

 // more of the getters and setters …..
 public void setTo(String[] toArr) {
  this.to = toArr;
 }

 public void setFrom(String string) {
  this.from = string;
 }

 public void setSubject(String string) {
  this.emailSubject = string;
 }
}


Hope this will helps some one.
Enjoy coding... cheers :)

Friday 13 June 2014

ListView setOnItemClickListener not working by adding button | ListView setOnItemClickListener issue

Hello Friends,
                    Today, I found another issue with Android  ListView.OnItemClickListner.
Actually I have a list view with items image and text and when I am clicking on it then ListView.OnItemClickListner called and all working fine. But when I added a
button or toggle button(android switch) in existing one then in this case the ListView.OnItemClickListner stop working.

This are the step to reproduce:

1) I have a ListView with an Image and textview.
2) I set ListView.OnItemClickListner. When I run my project It's show my ListView.
3) When I click on Listview It's working fine.
4) Then I added one more item in my item.xml file i.e:added    a button
5) Then When I click on Listview It's not working.
6) Then I removed the added Button from the item.xml and run  my project again when
     I click ListView It' work
7) What wrong ?


Then I figure out the problem by adding the following two line of code in my Button view.

android:focusable="false"
android:focusableInTouchMode="false"

Hope this will helpfull for some one. Enjoy Coding....... Cheers :)

Sunday 8 June 2014

Android accessing html control inside Java class| Getting html field value inside android activity class

Hello Friends,
                This is my another android tutorial. In this android demo I am going to
cover following parts:

1. Showing Android Login form in web view or loading html file in web view.
2. Getting the control  of log in button click,user name and password value inside
    our java class.
3. Checking the field validation inside  our java code.
4. Calling web service method based on valid user name and password.





Source Code:

1. Login.html :  This is my html file in which there is two edittext and a login button.
                           When I m clicking on login Button  I am checking the value of both
this text field inside my java class and if it is valid   then I am calling my login service
url.


<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
  function showAndroidToast() {
   var name = document.getElementById("loginName").value;
   var password = document.getElementById("password").value;
   Android.showMyToast(name,password);
  }
   </script>

</head>
<body>
 <section class="container">
  <div class="login">
   <h1>Login to Android Developer Solutions</h1>
   <form>
    <p>
     <input type="text" name="login" id="loginName" value=""
      placeholder="Username or Email">
    </p>
    <p>
     <input type="password" name="password" id="password" value=""
      placeholder="Password">
    </p>
    <p class="remember_me">
     <label> <input type="checkbox" name="remember_me"
      id="remember_me"> Remember me
     </label>
    </p>
    <p class="submit">
     <input type="submit" name="commit" value="Login"
      onClick="showAndroidToast()">
    </p>
   </form>
  </div>

  <div class="login-help">
   <p>
    Forgot your password? <a href="index.html">Click here to reset
     it</a>.
   </p>
  </div>
 </section>

 <section class="about">
  <p class="about-author">
   &copy; 2013&ndash;2014 <a
    href="http://www.androiddevelopersolutions.com/" target="_blank">Android
    Developer Solution</a><br> By <a
    href="http://www.androiddevelopersolutions.com/" target="_blank">Mukesh
    Y</a>
 </section>

</body>
</html>


2. MainActivity.java

package com.mukesh.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

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

  WebView webView = (WebView) findViewById(R.id.webview);

  WebSettings webSettings = webView.getSettings();
  webSettings.setJavaScriptEnabled(true);
  webView.addJavascriptInterface(new WebAppInterface(this), "Android");
  webView.loadUrl("file:///android_asset/index.html");
 }

}


Download Code : WebView Demo

Enjoy Codiing....
Cheers :)

Wednesday 4 June 2014

Android Google Map V2 | Android Draw Polygon

Hello Friends,
                               This is my small tutorial on google map v2. This blogs covers
following point:

1. Start Drawing on Google Map | Draw geometry on Google map
2. Clear drawing | Clear polygon
3. Close Polygon
4. Save Geometry

Screen 1:  Click on start drawing button and starting drawing geometry or polygon
                 or polyline.


 Screen2: Click on close polygon button which close the polygon.




Here is my code:

1. MainActivity.java  


/*
 * Copyright (C) 2014 Mukesh Y authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package info.androiddeveloper.googlemapsv2;

import java.util.ArrayList;

import org.osmdroid.api.IGeoPoint;
import org.osmdroid.util.GeoPoint;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;

/**
 * @author Mukesh Y
 */
public class MainActivity extends Activity implements OnMapClickListener {

 // Google Map
 private GoogleMap googleMap;
 ArrayList latLang = new ArrayList();
 ArrayList listPoints = new ArrayList();
 boolean isGeometryClosed = false;
 Polygon polygon;
 Context context = MainActivity.this;
 boolean isStartGeometry = false;

 @SuppressLint("NewApi")
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  try {
   initilizeMap();
   ActionBar actionBar = this.getActionBar();
   actionBar.setDisplayHomeAsUpEnabled(true);
   actionBar.setDisplayShowCustomEnabled(true);
   actionBar.setDisplayShowTitleEnabled(true);
   actionBar.setIcon(R.drawable.ic_launcher);
  } catch (Exception e) {
  }
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater menuInflater = getMenuInflater();
  menuInflater.inflate(R.menu.map_menu, menu);
  return super.onCreateOptionsMenu(menu);
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {

  switch (item.getItemId()) {
  case R.id.action_normal:
   googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
   return true;

  case R.id.action_hybrid:
   googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
   return true;

  case R.id.action_satellite:
   googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
   return true;
  
  default:
   return super.onOptionsItemSelected(item);
  }
 }

 /**
  * function to load map. If map is not created it will create it for you
  * */
 private void initilizeMap() {
  if (googleMap == null) {

   googleMap = ((MapFragment) getFragmentManager().findFragmentById(
     R.id.map)).getMap();

   // check if map is created successfully or not
   if (googleMap == null) {
    Toast.makeText(this, "Sorry! unable to create maps",
      Toast.LENGTH_SHORT).show();
    return;
   }

   googleMap.getUiSettings().setMyLocationButtonEnabled(true);
   // set my location
   googleMap.setMyLocationEnabled(true);
   googleMap.getUiSettings().setCompassEnabled(false);
   googleMap.getUiSettings().setRotateGesturesEnabled(false);
   // set zooming controll
   googleMap.getUiSettings().setZoomControlsEnabled(true);
   googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
   googleMap.setOnMapClickListener(this);
  }

 }

 public void Draw_Map() {
  PolygonOptions rectOptions = new PolygonOptions();
  rectOptions.addAll(latLang);
  rectOptions.strokeColor(Color.BLUE);
  rectOptions.fillColor(Color.CYAN);
  rectOptions.strokeWidth(7);
  polygon = googleMap.addPolygon(rectOptions);
 }

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

 }

 /**
  * Close the Polygon / join last point to first point
  * 
  * @param view
  */
 public void closePolygon(View view) {
  if (latLang.size() > 0) {
   Draw_Map();
   isGeometryClosed = true;
   isStartGeometry = false;
  }
 }

 /**
  * Close the Polygon / join last point to first point
  * 
  * @param view
  */
 public void startDrawing(View view) {
  isStartGeometry = true;
 }

 @Override
 public void onMapClick(LatLng latlan) {
  if (!isGeometryClosed && isStartGeometry) {
   latLang.add(latlan);
   GeoPoint point = new GeoPoint(latlan.latitude, latlan.longitude);
   listPoints.add((IGeoPoint) point);
   MarkerOptions marker = new MarkerOptions().position(latlan);
   googleMap.addMarker(marker);
   if (latLang.size() > 1) {
    PolylineOptions polyLine = new PolylineOptions().color(
      Color.BLUE).width((float) 7.0);
    polyLine.add(latlan);
    LatLng previousPoint = latLang.get(latLang.size() - 2);
    polyLine.add(previousPoint);
    googleMap.addPolyline(polyLine);
   }
  }
 }

 /**
  * Clear the all draw lines
  * 
  * @param view
  *            Current view of activity
  */
 public void clearCanvas(View view) {

  try {
   AlertDialog.Builder alertdalogBuilder = new AlertDialog.Builder(
     context);

   alertdalogBuilder.setTitle("Clear");
   alertdalogBuilder
     .setMessage(
       "Do you really want to clear the geometry? This action can't be undone!")
     .setCancelable(false)
     .setPositiveButton("Yes",
       new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,
          int id) {
         // polygon.remove();
         googleMap.clear();
         latLang = new ArrayList();
         listPoints = new ArrayList();
         isGeometryClosed = false;
        }
       })
     .setNegativeButton("No",
       new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,
          int which) {
         dialog.cancel();
        }
       });

   // Create Alert Dialog
   AlertDialog alertdialog = alertdalogBuilder.create();
   // show the alert dialog
   alertdialog.show();

  } catch (Exception e) {
  }

 }

 /**
  * Method for Save Property
  * 
  * @param view
  */
 public void savePolygon(View view) {
  try {
   if (isGeometryClosed) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
      context);
    alertDialogBuilder.setTitle("Save");
    alertDialogBuilder
      .setMessage(
        "Do you really want to save? This action can't be undone!")
      .setCancelable(false)
      .setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog,
           int id) {
          // if this button is clicked, close
          // current activity
          // Prop.this.finish();
          savePolygonAfterAlert();
         }
        })
      .setNegativeButton("No",
        new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog,
           int id) {
          // if this button is clicked, just close
          // the dialog box and do nothing
          dialog.cancel();
         }
        });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
   } else {
    showDialog(context, "Alert", "Close geometry before saving");
   }
  } catch (Exception e) {

  }

 }

 /**
  * Save the Polygon made by user
  * 
  * @param view
  */

 public void savePolygonAfterAlert() {
  // save geometry of polygon
 }

 /**
  * Method to show the Dialog box
  * 
  * @param ctx
  * @param title
  * @param msg
  */
 public void showDialog(Context ctx, String title, String msg) {
  AlertDialog.Builder dialog = new AlertDialog.Builder(ctx);
  dialog.setTitle(title).setMessage(msg).setCancelable(true);
  dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
   }
  });
  AlertDialog alertDialog = dialog.create();
  alertDialog.show();
 }
}

Download Complete Code : GoogleMapV2

Enjoy Coding .....   cheers :)

 

Copyright @ 2013 Android Developers Blog.