Send Data to Gmail useing Android Application?


Following section explains different parts of our Intent object required to send an email.

Intent Object - Action to send Email

You will use ACTION_SEND action to launch an email client installed on your Android device. Following is simple syntax to create an intent with ACTION_SEND action
Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email

To send an email you need to specify mailto: as URI using setData() method and data type will be totext/plain using setType() method as follows:
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Intent Object - Extra to send Email

Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the intent before sending the intent to a target email client. You can use following extra fields in your email:
S.N.Extra Data & Description
1EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML formatted text.
5EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
6EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal data to be sent.
7EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER.
Here is an example showing you how to assign extra data to your intent:
emailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
emailIntent.putExtra(Intent.EXTRA_TEXT   , "body of email");

Example


MainActivity.java

  1.  public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_EMAIL,new String[] { "" });
    i.putExtra(Intent.EXTRA_SUBJECT," \n\n www.google.com"); // your url
    i.putExtra(Intent.EXTRA_TEXT,"new test"); // your text in place of contentStr
    try {
    MainActivity.this.startActivity(Intent.createChooser(i,"Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
    ex.printStackTrace();
    }
    }
    });
    }

    }

main.xml

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

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_below="@+id/textView1"
            android:text="Send data to gmail" />

    </RelativeLayout>

Android Application Components?

Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.
There are following four main components that can be used within an Android application:
ComponentsDescription
ActivitiesThey they dictate the UI and handle the user interaction to the smartphone screen
ServicesThey handle background processing associated with an application.
Broadcast ReceiversThey handle communication between Android OS and applications.
Content ProvidersThey handle data and database management issues.

Activities

An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows:
public class MainActivity extends Activity {

}

Services

A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows:
public class MyService extends Service {

}

Broadcast Receivers

Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcasted as an Intent object.
public class MyReceiver  extends  BroadcastReceiver {

}

Content Providers

A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends  ContentProvider {

}
We will go through these tags in detail while covering application components in individual chapters.

Additional Components

There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are:
ComponentsDescription
FragmentsRepresents a behavior or a portion of user interface in an Activity.
ViewsUI elements that are drawn onscreen including buttons, lists forms etc.
LayoutsView hierarchies that control screen format and appearance of the views.
IntentsMessages wiring components together.
ResourcesExternal elements, such as strings, constants and drawables pictures.
ManifestConfiguration file for the application.

Adjust Text size in All Android Devices?

Today iam try to solve Text size in all Android Devices, last one week am struggle to solve this issue finally found the solution of this issue.

STEP : 1
   first in   ` res` folder =>  values => dimensions.xml=> create  `dimensions.xml`  file to  `values folder`  in that create like below code depending on textsize

         <?xml version="1.0" encoding="utf-8"?>
           <resources>
               <dimen name="textsize">8sp</dimen>
               <dimen name="text">10sp</dimen>
               <dimen name="comments">7sp</dimen>
           </resources>

STEP : 2
   in java file write this line

    TextView textviewtwo = (TextView)findViewById(R.id.sponsertwo_txt);
   textviewtwo.setText("brought to you by");
   textviewtwo.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.textsize));
          // in place of textsize use text and comments what ever we want depending on size. use like text size                  adjust automatically in all devices


ANDROID:BITMAP IMAGE STORE IN EXTERNAL OR INTERNAL STORAGE?

Write this line in onCreate() method, This line of code is used for checking Sd card  is available or not.


  1. Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals
                             (android.os.Environment.MEDIA_MOUNTED);

And this method is used for save your bitmap file in external and internal storage.

  1. private String SaveImage_Sta(Bitmap finalBitmap, String name) {
    if(isSDPresent) {
    Log.i("isSDPresent yes", " path is==> " +isSDPresent );
    String root = Environment.getExternalStorageDirectory().toString() + "/profile";
    File myDir = new File(root);
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = name + ".jpg";
    file = new File(myDir, fname);
    if (file.exists())
    file.delete();
    try {
    FileOutputStream out = new FileOutputStream(file);
    finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.flush();
    out.close();

    } catch (Exception e) {
    e.printStackTrace();
    }
        } else {
        
         Log.i("isSDPresent no ", " path is==> false ");
         ContextWrapper cw = new ContextWrapper(getApplicationContext());
             // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            file =new File(directory,"profile.jpg");       
          
            if (file.exists())
    file.delete();
            try {        
             FileOutputStream fos = new FileOutputStream(file);
             finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
             fos.flush();
                fos.close();
            
            } catch (Exception e) {
                e.printStackTrace();
            }       
        }
    return file.toString();


Check whether the sd card is available or not programatically?

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

if(isSDPresent) {
  // yes SD-card is present available
}
else   {
 // Sorry no sd card available
}

Calculate the time difference between two time fields?

long difference = date2.getTime() - date1.getTime(); 

days = (int) (difference / (1000*60*60*24));  
hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);

Multiple Selection Listview in Android?

  • In this example, we will create a ListView with multiple selection mode with button click event. On button click event, we retrieve the selected list view items and create a Bundle with array of selected items and store it in Intent and start another activity (ResultActivity).
  • ResultActivity retrieves the array and displays the result in ListView.

XML layout files

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/testbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="submit" />

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/testbutton"
        android:layout_alignParentTop="true" />

</RelativeLayout>

resultactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/outputList"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


Activity classes

MainActivity.java

 public class MainActivity extends Activity implements OnClickListener {
    Button button;
    ListView listView;
    ArrayAdapter<String> adapter;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewsById();
        String[] data = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
    "Cricket", "Tennis", "Foodball", "Tabletennis", "Hockey", "Golf", "Handball", "Vollyball",
    "Chess", "More" };
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, data);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setAdapter(adapter);
        button.setOnClickListener(this);
    }
    private void findViewsById() {
        listView = (ListView) findViewById(R.id.list);
        button = (Button) findViewById(R.id.testbutton);
    }
    public void onClick(View v) {
        SparseBooleanArray checked = listView.getCheckedItemPositions();
        ArrayList<String> selectedItems = new ArrayList<String>();
        for (int i = 0; i < checked.size(); i++) {
            // Item position in adapter
            int position = checked.keyAt(i);
            // Add sport if it is checked i.e.) == TRUE!
            if (checked.valueAt(i))
                selectedItems.add(adapter.getItem(position));
        }
        String[] outputStrArr = new String[selectedItems.size()]; 
        for (int i = 0; i < selectedItems.size(); i++) {
            outputStrArr[i] = selectedItems.get(i);
        }
        Intent intent = new Intent(getApplicationContext(),  ResultActivity.class); 
        // Create a bundle object
        Bundle b = new Bundle();
        b.putStringArray("selectedItems", outputStrArr); 
        // Add the bundle to the intent.
        intent.putExtras(b); 
        // start the ResultActivity
        startActivity(intent);
    }
}

ResultActivity.java

package com.example.multiblecheckboxs;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ResultActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultactivity);

Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
         android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);
}
}

Output




Changing Edit-text status to password programmatically.


EditText edit = new EditText(MainActivity.this);
String temporary_stored_text = edit.getText().toString().trim();
edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
edit.setText(temporary_stored_text);

Android Facebook login Using Facebook sdk3.0

First we check Facebook session in open or not Useing this

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrContext = this;
setContentView(R.layout.fb_activity_main);
facebook_button = (Button) findViewById(R.id.LikeFB_Button);

Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        fb_session = Session.openActiveSessionFromCache(mCurrContext);

If Your Facebook session in null and not open state click this button to login facebook

          Button button =(Button) findViewById(R.id.button_share);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (fb_session != null && fb_session.isOpened()) {
makeMeRequest(fb_session);
Log.i("Facebook Login State == >", "Facebook Login State");
} else {
if (fb_session == null) {
fb_session = new Session(mCurrContext);          
       }
Session.setActiveSession(fb_session);
ConnectToFacebook();
  Log.i("Facebook not Login State == >", "Facebook Not login State");
}
}
});
   }

This methods used for Login to Facebook Session

  private void ConnectToFacebook(){
Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
        Log.i("ConnectToFacebook  if == >", "ConnectToFacebook if");
        OpenRequest newSession = new Session.OpenRequest(this);
        newSession.setCallback(callback);
        session.openForRead(newSession);          
        try {
        Session.OpenRequest request = new Session.OpenRequest(this);
        request.setPermissions(Arrays.asList("email"));
        } catch (Exception e) {
        e.printStackTrace();
        }
        } else {
        Log.i("ConnectToFacebook  else == >", "ConnectToFacebook else");
            Session.openActiveSession(this, true, callback);        
        }
}

private Session.StatusCallback callback = new Session.StatusCallback() {
       public void call(final Session session, final SessionState state, final Exception exception) {
           onSessionStateChange(session, state, exception);
       }
   };
 
   private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
       if (session != null && session.isOpened()) {
        makeMeRequest(session);
       }
   }
 
   private void makeMeRequest(final Session session) {
     Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
    public void onCompleted(GraphUser user, Response response) {
    try{
      //UserInfoDisplay(user);
    //FrieddsInfoDisplay(session);
       } catch (Exception e) {
    e.printStackTrace();
    }
    }
    });              
       request.executeAsync();
   }

NOTE:

InManifestfile you Implement facebook login activity like this

  <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />        

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

And your App id create create in  res/values/string
  Like this

<resources>   
    <string name="app_id">FACEBOOKAPPLICATIONID</string> 
</resources> 

Android Store data and Image to server?

First Declare file to global like this
private File file;
After that convert to Drawable Image to Bitmap usein this two lines

Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
After that call your method where we want  "SaveImage_State" and give String name by default

SaveImage_State(myLogo, "name");


private String SaveImage_State(Bitmap finalBitmap, String name) {
String root = Environment.getExternalStorageDirectory().toString() + "/pm";
File myDir = new File(root);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = name + ".jpg";
file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.toString();
}


Call this where you want button on click like ......


AsyncTask<Void, Void, HttpEntity> editProfileTask = new AsyncTask<Void, Void, HttpEntity>() {
        
@Override
 protected HttpEntity doInBackground(Void... params) {          
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("Your url"); // your url

 try {                     
 MultipartEntity reqEntity = new MultipartEntity();
  reqEntity.addPart("firstname",new StringBody(firstnameEV.getText().toString(),
   "text/plain",Charset.forName("UTF-8")));
                   "text/plain",Charset.forName("UTF-8")));
 if (file != null) {
   reqEntity.addPart("image",new FileBody(((File) file),"application/zip"));
 }         
 httppost.setEntity(reqEntity);
 HttpResponse resp = httpclient.execute(httppost);          
 HttpEntity resEntity = resp.getEntity();
  return resEntity;
 } catch (ClientProtocolException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }return null;
 }
   @Override
   protected void onPostExecute(HttpEntity resEntity) {
     if (resEntity != null) {             
       try {
         JSONObject responseJsonObject = new JSONObject(EntityUtils.toString(resEntity));
          String status = responseJsonObject.getString("status");             
           if (status.equals("success")) {
                Toast.makeText(activity, "Your Profile is updated", Toast.LENGTH_LONG).show();
                 String data = responseJsonObject.getString("data");              
                 isUpdatedSuccessfully=true;            
           } else {
              Toast.makeText(activity, "Profile not updated", Toast.LENGTH_LONG).show();
         }
        } catch (Exception e) {
       e.printStackTrace();
      }
        }            
  }
       };
 editProfileTask.execute(null, null, null);
      



Select DateRange UsingRangePicker.

  /* * This Method is for select range from picker. * */ private fun selectDateRangeUsingRangePicker () { pageNumber = 1 val displ...