Tuesday, September 22, 2015

RoboGuice: (Android findViewById() vs @Inject View)


Roboguice is a dependency injection framework for Android applications, that brings the simplicity and ease of Dependency Injection to Android, using Google’s own Guice library. It smoothes out some of the wrinkles in your Android app development experience make things simple and fun. Do you always forget to check for null when you getIntent().getExtras()? RoboGuice 2 will help you. Think casting findViewById() to a TextView shouldn’t be necessary? RoboGuice is on it.
Using RoboGuice, you can inject your View, Resource, System Service, or any other object. RoboGuice can help you to slim down application code. Less code means less chances of issues/bugs and can help you to save efforts required to write or modify particular code in a project. It helps you to generate readable code which could be easier to follow.
Let’s look at different usage of RoboGuice library.

Usage of RoboGuice library:

  • Views Injection:: To initialize views, use @InjectViews, for example: @InjectView(R.id.textView1) TextView textView1;
  • Resources Injection: To initialize and get resources, use @InjectResources, for example: @InjectResource(R.string.app_name) String name;
  • System services Injection: To initialize and access system services, use @Inject, for example: @Inject LayoutInflater inflater;
  • POJO object Injection: To inject and initialize POJO object, use @Inject, for example: @Inject Foo foo;
Let’s look at an example of general activity code:
public class TestActivity extends Activity{
    TextView textView1;
    TextView textView2;
    ImageView imageView1;
    String name;
    Drawable icLauncher;
    LocationManager locManager;
    LayoutInflater inflater;
    NotificationManager notifyManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);
        imageView1 = (ImageView) findViewById(R.id.imageView1);
        name = getString(R.string.app_name);
        icLauncher = getResources().getDrawable(R.id.ic_launcher);
        locManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
        inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        notifyManager = (NotificationManager)        getSystemService(Activity.NOTIFICATION_SERVICE);
        textView1.setText("Hello World! RoboGuice demo");
    }
}

Let’s check the magic of RoboGuice and let’s slim down the code.

Using RoboGuice

To use RoboGuice for the dependency injection, you are required to extends eitherRoboActivity or RoboFragment.
public class TestActivity extends RoboActivity{


    @InjectView(R.id.textView1) TextView textView1;

    @InjectView(R.id.textView2) TextView textView2;
    @InjectView(R.id.imageView1) ImageView imageView1;
    @InjectResource(R.string.app_name) String name;
    @InjectResource(R.drawable.ic_launcher) Drawable icLauncher;
    @Inject LocationManager locManager;
    @Inject LayoutInflater inflater;
    @Inject NotificationManager notifyManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);
        textView1.setText(name);
    }
}
Benefits of using RoboGuice
  • No need to initialize views, if you want then Inject it using @InjectViews
  • No need to initialize System service. If you need then Inject it using @Inject
  • No need to initialize Drawable, string and other resources. If you require then Inject it using @InjectResource
  • All of these above practices helps you to slim down the code.
  • Less code => Less chances of bugs/issues
  • Less code => Android developer can save coding efforts and can focus fully on actual business logic of android app

RoboGuice and ActionBarSherlock

As I have mentioned earlier in alert box that you are required to extend either RoboActivity or RoboFragment to use RoboGuice in either Activity or Fragment particularly. But what if you have included ActionBarSherlock in your project to manage compatibility? The problem is you have extended either SherlockActivity or SherlockFragmentActivity for your activity or fragment particularly and now the situation is we could not use RoboGuice with ActionBarSherlock.
But There is one solution for it too, you have to define custom base classes for Activities and Fragments to use RoboGuice and ActionBarSherlock both.
You can download base classes from here: https://github.com/rtyley/roboguice-sherlock or download a JAR file for the same: RoboGuice+Sherlock.jar, include either of them in your project.
You can download a sample code here.

Reference:

Wednesday, September 16, 2015

Sending email with attachment using JavaMail API


For sending email with attachment, JavaMail API provides some useful classes like BodyPart, MimeBodyPart etc.

For better understanding of this example, learn the steps of sending email using JavaMail API first.
For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar
download these jar files (or) go to the Oracle site to download the latest version.

Sending email with attachment using JavaMail API


There are total 7 steps for sending attachment with email. They are:
  1. Get the session object
  2. compose message
  3. create MimeBodyPart object and set your message text
  4. create new MimeBodyPart object and set DataHandler object to this object
  5. create Multipart object and add MimeBodyPart objects to this object
  6. set the multiplart object to the message object
  7. send message

Example of sending email with attachment using JavaMail API

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  
  
class SendAttachment{  
 public static void main(String [] args){  
  
  String to="example@gmail.com";//change accordingly  
  final String user="example@gmail.com";//change accordingly  
  final String password="xxxxx";//change accordingly  
   
  //1) get the session object    

//GMail via TLS
 Properties properties = System.getProperties();  
 properties.put("mail.smtp.host", "smtp.gmail.com");  
 properties.put("mail.smtp.auth", "true");  
 properties.put("mail.transport.protocol", "smtps");
 properties.put("mail.smtp.port", "587");
 properties.put("mail.smtp.starttls.enable", "true");
 // GMail via SSL

/*properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");*/
   Session session = Session.getDefaultInstance(properties,  
   new javax.mail.Authenticator() {  
   protected PasswordAuthentication getPasswordAuthentication() {  
   return new PasswordAuthentication(user,password);  
   }  
  });  
     
  //2) compose message     
  
try{  
    MimeMessage message = new MimeMessage(session);  
    message.setFrom(new InternetAddress(user));  
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
    message.setSubject("Message Aleart");  
      
    //3) create MimeBodyPart object and set your message text     

    BodyPart messageBodyPart1 = new MimeBodyPart();  
    messageBodyPart1.setText("This is message body");  
      
    //4) create new MimeBodyPart object and set DataHandler object to this object      

    MimeBodyPart messageBodyPart2 = new MimeBodyPart();  
  
    String filename = "SendAttachment.java";//change accordingly  
    DataSource source = new FileDataSource(filename);  
    messageBodyPart2.setDataHandler(new DataHandler(source));  
    messageBodyPart2.setFileName(filename);  
     
     
    //5) create Multipart object and add MimeBodyPart objects to this object      

    Multipart multipart = new MimeMultipart();  
    multipart.addBodyPart(messageBodyPart1);  
    multipart.addBodyPart(messageBodyPart2);  
  
    //6) set the multiplart object to the message object  

    message.setContent(multipart );  
     
    //7) send message  

    Transport.send(message);  
   
   System.out.println("message sent....");  
   }catch (MessagingException ex) {ex.printStackTrace();}  
 }  
}

You can download full source code Here.