Convert PCM to Mu-law conversion

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;


public class MyServlet extends HttpServlet {


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // You can still access request parameters here

        String action = request.getParameter("action");


        // Output parameter value

        System.out.println("Action parameter value: " + action);


        // Continue processing the request

        // ...

    }

}


class MyFilter implements Filter {


    @Override

    public void init(FilterConfig filterConfig) throws ServletException {

        // Initialization code, if needed

    }


    @Override

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // Wrap the original request with BufferedRequestWrapper

        BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper((HttpServletRequest) request);


        // You can still access request parameters inside the filter

        String action = bufferedRequest.getParameter("action");


        // Output parameter value

        System.out.println("Action parameter value inside filter: " + action);


        // Pass the wrapped request down the filter chain

        chain.doFilter(bufferedRequest, response);

    }


    @Override

    public void destroy() {

        // Cleanup code, if needed

    }

}


class BufferedRequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    private final Map<String, String[]> parameters;


    public BufferedRequestWrapper(HttpServletRequest request) throws IOException {

        super(request);

        StringBuilder stringBuilder = new StringBuilder();

        BufferedReader bufferedReader = null;

        parameters = new HashMap<>(request.getParameterMap());


        try {

            InputStream inputStream = request.getInputStream();

            if (inputStream != null) {

                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                char[] charBuffer = new char[1024];

                int bytesRead;

                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {

                    stringBuilder.append(charBuffer, 0, bytesRead);

                }

            } else {

                stringBuilder.append("");

            }

        } finally {

            if (bufferedReader != null) {

                bufferedReader.close();

            }

        }

        body = stringBuilder.toString();

    }


    @Override

    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());

        return new ServletInputStream() {

            public int read() throws IOException {

                return byteArrayInputStream.read();

            }


            @Override

            public boolean isFinished() {

                return byteArrayInputStream.available() == 0;

            }


            @Override

            public boolean isReady() {

                return true;

            }


            @Override

            public void setReadListener(ReadListener listener) {

                // Not implemented

            }

        };

    }


    @Override

    public BufferedReader getReader() throws IOException {

        return new BufferedReader(new InputStreamReader(this.getInputStream()));

    }


    @Override

    public String getParameter(String name) {

        String[] values = parameters.get(name);

        return (values != null && values.length > 0) ? values[0] : null;

    }


    @Override

    public Map<String, String[]> getParameterMap() {

        return parameters;

    }


    @Override

    public Enumeration<String> getParameterNames() {

        return Collections.enumeration(parameters.keySet());

    }


    @Override

    public String[] getParameterValues(String name) {

        return parameters.get(name);

    }

}


Difference between abstract class and interface in Java 8

 


 Kotlin - How to pick multiple image from gallery using intent


After  seven years I am going to adding my new post is "How to pick multiple image from gallery" using intent.

For picking image from gallery we need mention write permission in the manifest file






Android Custom Navigation Drawer with Expandablelistview

Android Custom Navigation Drawer with Expandablelistview


Source Code:
https://www.dropbox.com/s/qtd51lxypodvojf/NavigationDrawer.zip

ListView problem while scrolling

ListView problem while scrolling




Source Code :https://www.dropbox.com/s/qtd51lxypodvojf/NavigationDrawer.zip


Android Sqlite Tutorial

Android Sqlite Tutorial



Source Code:
https://www.dropbox.com/s/63vufkq32zp5g07/Sqlite.zip?dl=0

Step 1:
We need to create database

package com.example.slide;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "Test";
//Table Name
private static final String TABLE_TEST = "TestTable";
//Column Name
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

//Create Table
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_AGE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}

//Insert Value
public void adddata(Context context,String movieId,String songId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, movieId);
values.put(KEY_AGE, songId);
db.insert(TABLE_TEST, null, values);
db.close();
}

//Get Row Count
public int getCount() {
String countQuery = "SELECT  * FROM " + TABLE_TEST;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}

//Delete Query
public void removeFav(int id) {
String countQuery = "DELETE FROM " + TABLE_TEST + " where " + KEY_ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(countQuery);
}

//Get FavList
public List<FavoriteList> getFavList(){
String selectQuery = "SELECT  * FROM " + TABLE_TEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<FavoriteList> FavList = new ArrayList<FavoriteList>();
if (cursor.moveToFirst()) {
do {
FavoriteList list = new FavoriteList();
list.setId(Integer.parseInt(cursor.getString(0)));
list.setName(cursor.getString(1));
list.setAge(cursor.getString(2));
FavList.add(list);
} while (cursor.moveToNext());
}
return FavList;
}

}

Step 2:
We need to create Activity with listview using Base Adapter
package com.example.slide;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
FavoriteList favList = new FavoriteList();
Button add,checkcount,list;
Context context = this;
DatabaseHandler db;
ListView listView;
List<FavoriteList> favoriteList;
LinearLayout layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

add = (Button)findViewById(R.id.add);
add.setOnClickListener(addOnClick);
checkcount = (Button)findViewById(R.id.checkcount);
checkcount.setOnClickListener(checkcountOnClick);
list = (Button)findViewById(R.id.list);
list.setOnClickListener(listOnClick);
layout = (LinearLayout)findViewById(R.id.layout);
listView = (ListView)findViewById(R.id.listView);
db = new DatabaseHandler(this);

//db.removeFav();

/*favList = db.getFavList();
Toast.makeText(getApplicationContext(), ""+favList.getSongname(), Toast.LENGTH_LONG).show();*/
}

View.OnClickListener addOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.row);
dialog.setTitle("Add Data to Database");
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText age = (EditText) dialog.findViewById(R.id.age);
Button Add = (Button) dialog.findViewById(R.id.Add);
Add.setText("Add");
Add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(name.getText().toString() != null && name.getText().toString().length() >0 ){
if(age.getText().toString() != null && age.getText().toString().length() >0 ){
db.adddata(context, name.getText().toString(), age.getText().toString());
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
dialog.dismiss();
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Age", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Name", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
};

View.OnClickListener checkcountOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
int uyu = db.getCount();
Toast.makeText(getApplicationContext(), ""+uyu, Toast.LENGTH_LONG).show();
}
};

View.OnClickListener listOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
};

public class ViewAdapter extends BaseAdapter {

LayoutInflater mInflater;

public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
return favoriteList.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem,null);
}

final TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
nameText.setText("Name : "+favoriteList.get(position).getName());
final TextView ageText = (TextView) convertView.findViewById(R.id.ageText);
ageText.setText("Age : "+favoriteList.get(position).getAge());

final Button delete = (Button) convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
db.removeFav(favoriteList.get(position).getId());
notifyDataSetChanged();
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
});
return convertView;
}
}
}


XML files

We need to create activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="Add Data to Database"
            android:textColor="#228B22"
            android:textSize="16dp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/add"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:text="Add"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:text="Show List of Data"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/checkcount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:text="Check value Count"
            android:textColor="#FFFFFF" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="5dp"
        android:layout_weight="1" >

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>
</LinearLayout>


BaseAdapter listview XML is listitem.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/nameText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#228B22" />

            <TextView
                android:id="@+id/ageText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#228B22" />
        </LinearLayout>

        <Button
            android:id="@+id/edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:text="Edit"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:text="Delete"
            android:textColor="#FFFFFF" />
    </LinearLayout>


</LinearLayout>

We need to create Model for storing the data
FavoriteList .java

package com.example.slide;

public class FavoriteList {

//private variables
int id;
String name;
String age;

// Empty constructor
public FavoriteList(){

}
// constructor
public FavoriteList(int id, String name, String age){
this.id = id;
this.name = name;
this.age = age;
}

// getting id
public int getId(){
return this.id;
}

// setting id
public void setId(int id){
this.id = id;
}

// getting name
public String getName(){
return this.name;
}

// setting name
public void setName(String name){
this.name = name;
}

// getting Moviename
public String getAge(){
return this.age;
}

// setting Moviename
public void setAge(String age){
this.age = age;
}

}

I have used buttoncolor.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
 
    <padding android:top="7dp"
        android:bottom="7dp"/>
 
    <corners android:radius="7dp"/>

    <solid android:color="#228B22"/>
 

</shape>

Another one is shape.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
 
    <padding android:top="7dp"
        android:bottom="7dp"/>
 
    <stroke android:color="#228B22" android:width="2dp"/>
 
    <corners android:radius="7dp"/>

    <solid android:color="#FFFFFF"/>
 

</shape>


Android Select multiple images from gallery

Android Select multiple images from gallery


In this tutorial cover two functionality
a. Take Photo.
b. Choose Custom Gallery

Take Photo:
I will take the photo and save into the SD Card(AndroOne).

Choose From Gallery:
  • All gallery images shows with checkbox.
  • Only same time upload 10 images Only.

    We need add below library : universal-image-loader-1.6.1-with-src.jar


Design the 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"
    android:background="@color/Black" >
    <TextView
        android:id="@+id/titleView"
        style="@style/screen_title_style"
        android:text="@string/add_picture_title" />
    <LinearLayout
        android:id="@+id/customGalleryFooter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/captureBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="100dip"
            android:text="Capture" />
        <Button
            android:id="@+id/selectBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="100dip"
            android:text="Select" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/changeLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/customGalleryFooter"
        android:layout_below="@id/titleView" >
        <GridView
            android:id="@+id/PhoneImageGrid"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:columnWidth="90dp"
            android:gravity="center"
            android:horizontalSpacing="10dp"
            android:numColumns="auto_fit"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp" />
    </LinearLayout>
</RelativeLayout>

2.We need to show the multiple Photo.Design another Layout griditem.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" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/back" />
    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/imageView1"
        android:layout_centerVertical="true" />
</RelativeLayout>

3.Next create MainActivity.java

package com.android.androone;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class MainActivity extends BaseActivity {

private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
SparseBooleanArray mSparseBooleanArray;
private static final String DIRECTORY = "AndroOne";
Uri imgUri,imageUri;
final private int CAPTURE_IMAGE = 1;
String imgPath;
GridView gridView;
Cursor imagecursor;
private ArrayList<String> nImageUrl = new ArrayList<String>();
private ArrayList<Integer> checkImage = new ArrayList<Integer>();
private static final String IMAGE_PATH = "path";
String currentPhotoPath = "";
LinearLayout changeLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mSparseBooleanArray = new SparseBooleanArray();

final Button selectBtn = (Button) findViewById(R.id.selectBtn);
selectBtn.setOnClickListener(selectOnClickListener);

final Button captureBtn = (Button) findViewById(R.id.captureBtn);
captureBtn.setOnClickListener(captureOnClickListener);

changeLayout = (LinearLayout)findViewById(R.id.changeLayout);

imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));

final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
@SuppressWarnings("deprecation")
Cursor imagecursor1 = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");

this.imageUrls = new ArrayList<String>();
imageUrls.size();

for (int i = 0; i < imagecursor1.getCount(); i++) {
imagecursor1.moveToPosition(i);
int dataColumnIndex = imagecursor1
.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor1.getString(dataColumnIndex));
}

options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory().cacheOnDisc().build();

imageAdapter = new ImageAdapter(this, imageUrls);

gridView = (GridView) findViewById(R.id.PhoneImageGrid);
gridView.setAdapter(imageAdapter);
}

@Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}

public void btnChoosePhotosClick(View v) {
ArrayList<String> selectedItems = imageAdapter.getCheckedItems();
Toast.makeText(MultiPhotoSelectActivity.this,"Total photos selected: " + selectedItems.size(),Toast.LENGTH_SHORT).show();
Log.d(MultiPhotoSelectActivity.class.getSimpleName(),"Selected Items: " + selectedItems.toString());
}

public class ImageAdapter extends BaseAdapter {

ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;

public ImageAdapter(Context context, ArrayList<String> imageList) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
mList = new ArrayList<String>();
this.mList = imageList;

}

public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();

for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}

@Override
public int getCount() {
return imageUrls.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

if (convertView == null) {
convertView = mInflater.inflate(R.layout.griditem,null);
}

final CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
imageLoader.displayImage("file://" + imageUrls.get(position),imageView, options, new SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(Bitmap loadedImage) {
Animation anim = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this,R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
});

mCheckBox.setTag(position);
if(nImageUrl.contains(imageUrls.get(position))){
mCheckBox.setChecked(true);
checkImage.add(position);
}
if(!checkImage.contains(position)){
mCheckBox.setChecked(false);
}
mCheckBox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String url = imageUrls.get(position);
if(mCheckBox.isChecked()){
nImageUrl.add(url);
}else{
nImageUrl.remove(url);
}
}
});
return convertView;
}

}

View.OnClickListener selectOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (nImageUrl.size() < 11) {
if (nImageUrl.size() == 0) {
Toast.makeText(getApplicationContext(),"Please select at least one image",Toast.LENGTH_LONG).show();
} else {
Intent imageIntent = new Intent(ManiActivity.this,UploadActivity.class);
imageIntent.putStringArrayListExtra("NIMAGE", nImageUrl);
startActivity(imageIntent);
}
} else {
Toast.makeText(getApplicationContext(),"Upload ten Images only", Toast.LENGTH_LONG).show();
}
}
};

View.OnClickListener captureOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String fileName = "IMG_" + sdf.format(new Date()) + ".jpg";
File myDirectory = new File(Environment.getExternalStorageDirectory() + "/" + DIRECTORY + "/");
if (!myDirectory.exists())
myDirectory.mkdirs();
File file = new File(myDirectory, fileName);
imageUri = Uri.fromFile(file);
currentPhotoPath = file.getAbsolutePath();
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAPTURE_IMAGE);
}
};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE) {
if(resultCode == Activity.RESULT_OK) {
MediaScannerConnection.scanFile(getApplicationContext(), new String[] { imageUri.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
Log.i("Scanned = ", "Scanned " + path);
runOnUiThread(new Runnable() {
public void run() {
//UI Works
loadData();
}
});
}
});
       }
       else if(resultCode == Activity.RESULT_CANCELED) {
           Toast.makeText(getApplicationContext(), "Picture could not be taken.", Toast.LENGTH_SHORT).show();
       }

} else {
super.onActivityResult(requestCode, resultCode, data);
}
}

private void loadData() {
final String[] columns = { MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
@SuppressWarnings("deprecation")
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,null, orderBy + " DESC");

Log.i("imageUrls = ", "Scanned " + imageUrls);
this.imageUrls.clear();

for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
}

nImageUrl.add(imageUrls.get(0));
imageAdapter = new ImageAdapter(this, imageUrls);
gridView.setAdapter(imageAdapter);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString(IMAGE_PATH, currentPhotoPath);

super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);

currentPhotoPath = savedInstanceState.getString(IMAGE_PATH);
}
}

Sample Code :  https://www.dropbox.com/s/ciri0a6ew30pexc/HomeActivity.zip