Sunday, September 22, 2013

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)MainActivity.java

package com.manish.sendemaildemo;

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 manish
 *
 */
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)activity_main.xml

<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" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        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: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" />
    </RelativeLayout>

</ScrollView>

3)AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.sendemaildemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <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" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.sendemaildemo.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>
    </application>

</manifest>

Thanks!


Wednesday, September 4, 2013

Android Call History Example | How to Get Phone Call Record in Android | Read Call History in Android Phone | Code for Get Phone Call Record in Android

Hello Friends!
Today I am going to share very important code for get phone call history in Android. Don't forget to add
permission-
<android:name="android.permission.READ_CALL_LOG"/>


MainActivity.java


package com.manish.callhistory;

import java.util.Date;

import com.manish.callhistory.R;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;

public class MainActivity extends Activity {
 TextView textView = null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textView = (TextView) findViewById(R.id.textview_call);
  getCallDetails();
 }

 private void getCallDetails() {

  StringBuffer sb = new StringBuffer();
  Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
    null, null, null);
  int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
  int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
  int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
  int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
  sb.append("Call Log :");
  while (managedCursor.moveToNext()) {
   String phNumber = managedCursor.getString(number);
   String callType = managedCursor.getString(type);
   String callDate = managedCursor.getString(date);
   Date callDayTime = new Date(Long.valueOf(callDate));
   String callDuration = managedCursor.getString(duration);
   String dir = null;
   int dircode = Integer.parseInt(callType);
   switch (dircode) {
   case CallLog.Calls.OUTGOING_TYPE:
    dir = "OUTGOING";
    break;

   case CallLog.Calls.INCOMING_TYPE:
    dir = "INCOMING";
    break;

   case CallLog.Calls.MISSED_TYPE:
    dir = "MISSED";
    break;
   }
   sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
     + dir + " \nCall Date:--- " + callDayTime
     + " \nCall duration in sec :--- " + callDuration);
   sb.append("\n----------------------------------");
  }
  //managedCursor.close();
  textView.setText(sb);
 }

}

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=".MainActivity" >

    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textview_call"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" />
    </ScrollView>

</RelativeLayout>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.callhistory"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <android:name="android.permission.READ_CALL_LOG"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.callhistory.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>
    </application>

</manifest>

Thanks!

Monday, September 2, 2013

Android Dynamic Check-box Example | Check-box Demo in Android | Manage click in dynamic check-box in android

Hello Friends!
Today I am sharing very important code for dynamic check-box in android. Main part of this demo is manage dynamic click of check-box. Just copy paste below code and modify according your need.


MainActivity.java


package com.manish.checkboxdemo;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;

import com.manish.checkboxdemo.R;

/**
 * 
 * @author manish
 * 
 */

public class MainActivity extends Activity {
 LinearLayout linearMain;
 CheckBox checkBox;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  linearMain = (LinearLayout) findViewById(R.id.linearMain);
  /**
   * create linked hash map for store item you can get value from database
   * or server also
   */
  LinkedHashMap<String, String> alphabet = new LinkedHashMap<String, String>();
  alphabet.put("1", "Apple");
  alphabet.put("2", "Boy");
  alphabet.put("3", "Cat");
  alphabet.put("4", "Dog");
  alphabet.put("5", "Eet");
  alphabet.put("6", "Fat");
  alphabet.put("7", "Goat");
  alphabet.put("8", "Hen");
  alphabet.put("9", "I am");
  alphabet.put("10", "Jug");

  Set<?> set = alphabet.entrySet();
  // Get an iterator
  Iterator<?> i = set.iterator();
  // Display elements
  while (i.hasNext()) {
   @SuppressWarnings("rawtypes")
   Map.Entry me = (Map.Entry) i.next();
   System.out.print(me.getKey() + ": ");
   System.out.println(me.getValue());

   checkBox = new CheckBox(this);
   checkBox.setId(Integer.parseInt(me.getKey().toString()));
   checkBox.setText(me.getValue().toString());
   checkBox.setOnClickListener(getOnClickDoSomething(checkBox));
   linearMain.addView(checkBox);
  }

 }

 View.OnClickListener getOnClickDoSomething(final Button button) {
  return new View.OnClickListener() {
   public void onClick(View v) {
    System.out.println("*************id******" + button.getId());
    System.out.println("and text***" + button.getText().toString());
   }
  };
 }

}

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

</LinearLayout>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.checkboxdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.checkboxdemo.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>
    </application>

</manifest>

Thanks!