Wednesday, 31 August 2016

Pick Image from Camera or Gallery -Android

 in this tutorial I will be showing how to get an Image from the user's Camera or from his gallery.

In this Tutorial User will have two choices:
Capture photo/ image from camera in Android
Choose photo/ image from gallery in Android

User will need to choose one option from the above two options and then depending on the option chosen by the user, we will either capture an image from the camera or open the gallery.









activity_main.xml
--------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
  
tools:context="com.sgp.anil.takephotocameraandgallery.MainActivity">

    <
Button
       
android:id="@+id/button_takephoto"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="30dp"
       
android:text="Select Photo" />

    <
ImageView
       
android:id="@+id/imageView_show"
       
android:layout_width="250dp"
       
android:layout_height="250dp"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="25dp" />
</
LinearLayout>

Utility.Java
-------------------------
package com.sgp.anil.takephotocameraandgallery;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

/**
 * Created by Anil on 31/08/16.
 */
public class Utility {
   
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
   
public static final int MY_PERMISSIONS_REQUEST_CAMERA = 124;

   
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
   
public static boolean checkPermission(final Context context) {
       
int currentAPIVersion = Build.VERSION.SDK_INT;
       
if (currentAPIVersion >= Build.VERSION_CODES.M) {
           
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
               
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                           
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);


                }
else {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                           
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                
return false;
            }
else if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
               
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.CAMERA)) {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);

                }
else {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);

                }
               
return false;
            }
else {
               
return true;
            }
        }
else {
           
return true;
        }
    }
}

MainActivity.Java
---------------------------
package com.sgp.anil.takephotocameraandgallery;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    Button
takephotobtn;
    ImageView
imageView;
   
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
   
private String userChoosenTask;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
takephotobtn = (Button) findViewById(R.id.button_takephoto);
       
imageView = (ImageView) findViewById(R.id.imageView_show);
       
takephotobtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View view) {
                takePhoto();


            }
        });
    }

   
@Override
   
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       
switch (requestCode) {
           
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE & Utility.MY_PERMISSIONS_REQUEST_CAMERA:
               
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                   
if (userChoosenTask.equals("Take Photo Gallery"))
                        galleryIntent();
                }
else {
                   
//code for deny
               
}
               
break;

           
case Utility.MY_PERMISSIONS_REQUEST_CAMERA:
               
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                   
if (userChoosenTask.equals("Take Photo Camera"))
                        cameraIntent();

                }
else {
                   
//code for deny
               
}
               
break;
        }
    }

   
private void takePhoto() {
       
final CharSequence[] items = {"Take Photo Camera", "Take Photo Gallery"};

        AlertDialog.Builder builder =
new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(
"Add Photo!");
        builder.setItems(items,
new DialogInterface.OnClickListener() {
           
@Override
           
public void onClick(DialogInterface dialog, int item) {
               
boolean result = Utility.checkPermission(MainActivity.this);

               
if (items[item].equals("Take Photo Camera")) {
                   
userChoosenTask = "Take Photo Camera";
                   
if (result)
                        cameraIntent();

                }
else if (items[item].equals("Take Photo Gallery")) {
                   
userChoosenTask = "Take Photo Gallery";
                   
if (result)
                        galleryIntent();

                }
            }
        });
        builder.show();
    }

   
private void galleryIntent() {
        Intent intent =
new Intent();
        intent.setType(
"image/*");
        intent.setAction(Intent.
ACTION_GET_CONTENT);//
       
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    }

   
private void cameraIntent() {
        Intent intent =
new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,
REQUEST_CAMERA);
    }

   
@Override
   
public void onActivityResult(int requestCode, int resultCode, Intent data) {
       
super.onActivityResult(requestCode, resultCode, data);

       
if (resultCode == Activity.RESULT_OK) {
           
if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
           
else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(data);
        }
    }

   
private void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get(
"data");
        ByteArrayOutputStream bytes =
new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.
JPEG, 90, bytes);

        File destination =
new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() +
".jpg");

        FileOutputStream fo;
       
try {
            destination.createNewFile();
            fo =
new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        }
catch (FileNotFoundException e) {
            e.printStackTrace();
        }
catch (IOException e) {
            e.printStackTrace();
        }

       
imageView.setImageBitmap(thumbnail);
    }

   
@SuppressWarnings("deprecation")
   
private void onSelectFromGalleryResult(Intent data) {

        Bitmap bm =
null;
       
if (data != null) {
           
try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            }
catch (IOException e) {
                e.printStackTrace();
            }
        }

       
imageView.setImageBitmap(bm);
    }

}

Tuesday, 23 August 2016

Share Via Option in Android


In this Application you will learn to implement an effective and user friendly share action to android app. You can add android share action anywhere in your application.
Here I have added share action in actionbar/toolbar and on button’s click event.
 If user clicks the share button from actionbar/toolbar,
many options will be available there to share like whatsapp,email, gmail, facebook, linkedin,twitter  



activity_main.xml
----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
   
app:layout_behavior="@string/appbar_scrolling_view_behavior"
   
tools:context="com.sgp.anil.sharevia.MainActivity"
   
tools:showIn="@layout/activity_main">


    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textAppearance="?android:attr/textAppearanceLarge"
       
android:text="Share via Option Example"
       
android:id="@+id/textView"
        
android:layout_gravity="center_horizontal" />

    <
TextView
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textAppearance="?android:attr/textAppearanceLarge"
       
android:text="Anil Android"
       
android:id="@+id/textView2"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="20dp" />
</
LinearLayout>

menu_main.xml
-----------------------
<menu 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"
   
tools:context="com.sgp.anil.sharevia.MainActivity">
    <
item
       
android:id="@+id/share"
       
android:actionProviderClass="android.widget.ShareActionProvider"
       
android:icon="@android:drawable/ic_menu_share"
       
android:title="Share"
       
app:showAsAction="always" />
</
menu>

MainActivity.Java
-----------------------
 package com.sgp.anil.sharevia;

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

public class MainActivity extends AppCompatActivity {

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.
toolbar);
        setSupportActionBar(toolbar);


    }

   
@Override
   
public boolean onCreateOptionsMenu(Menu menu) {
       
// Inflate the menu; this adds items to the action bar if it is present.
       
getMenuInflater().inflate(R.menu.menu_main, menu);
       
return true;
    }

   
@Override
   
public boolean onOptionsItemSelected(MenuItem item) {
       
// Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
       
int id = item.getItemId();

       
//noinspection SimplifiableIfStatement
       
if (id == R.id.share) {
            Intent sharingIntent =
new Intent(android.content.Intent.ACTION_SEND);
            sharingIntent.setType(
"text/plain");
            String shareBodyText =
"This is My Text to Send";
            sharingIntent.putExtra(android.content.Intent.
EXTRA_SUBJECT, "Subject Test");
            sharingIntent.putExtra(android.content.Intent.
EXTRA_TEXT, shareBodyText);
            startActivity(Intent.createChooser(sharingIntent,
"Sharing Option"));
           
return true;
        }

       
return super.onOptionsItemSelected(item);
    }
}