Pages

Saturday, May 31, 2014

Image pass in Json Android

package com.example.fb;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;





import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Test extends Activity implements OnClickListener{
EditText email,pass;
Button btn,btn1,btn2;
ArrayList<NameValuePair> np;
ProgressDialog pd;
JSONParser jp;
String Status;
AlertDialogManager alert;
String pathMaster ="";
byte[] byteImage1 = null;
String byteImage;
String Image;
Bitmap bmp;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);

alert = new AlertDialogManager();

/*email = (EditText)findViewById(R.id.editresetemail);
pass = (EditText)findViewById(R.id.editresetpass);*/
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
btn1 = (Button)findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2 = (Button)findViewById(R.id.button3);
btn2.setOnClickListener(this);

jp = new JSONParser();
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub


if(v == btn){

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
   // request code

   startActivityForResult(cameraIntent, 99);
}
if(v == btn1){

Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 0);
}
if(v == btn2){

getImage1();
new insert().execute();
}

}

private void getImage1() {
// TODO Auto-generated method stub

ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byteImage1 = bao.toByteArray();
    Image=Base64.encodeToString(byteImage1, Base64.DEFAULT);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK && requestCode==99)
{
Uri targetUri = data.getData();
pathMaster = getRealPathFromURI(targetUri);

bmp = ShrinkBitmap(pathMaster, 100, 100);
        ImageView image1 = (ImageView)findViewById(R.id.image);
        image1.setImageBitmap(bmp);

}
else if(resultCode == RESULT_OK && requestCode==0)
{
Uri targetUri = data.getData();
        pathMaster = getRealPathFromURI(targetUri).toString();            
        bmp = ShrinkBitmap(pathMaster, 100, 100);
        ImageView image1 = (ImageView)findViewById(R.id.image);

        image1.setImageBitmap(bmp);
    }  
super.onActivityResult(requestCode, resultCode, data);
}


/*
************************ Compress Image **************************
*/
private Bitmap ShrinkBitmap(String path, int width, int height) {
// TODO Auto-generated method stub

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, bmpFactoryOptions);

int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);

if (heightRatio > 1 || widthRatio > 1)
{
 if (heightRatio > widthRatio)
 {
  bmpFactoryOptions.inSampleSize = heightRatio;
 } else {
  bmpFactoryOptions.inSampleSize = widthRatio;
 }
}

bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(path, bmpFactoryOptions);
return bitmap;


}

/*
*************** Get path of image from camera or gallery *******************
*/

private String getRealPathFromURI(Uri targetUri) {
// TODO Auto-generated method stub
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( targetUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}




class insert extends AsyncTask<Void, Void, Void>{





@Override
protected void onPreExecute() {
// TODO Auto-generated method stub

pd = new ProgressDialog(Test.this);
pd.setMessage("Loading....");
pd.setTitle("Update Password");
pd.show();

super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {



np = new ArrayList<NameValuePair>();
np.add(new BasicNameValuePair("session_id","85"));
np.add(new BasicNameValuePair("ns_data",Image));



JSONObject jo = jp.makeHttpRequest(Constant.PROFILEPIC, "POST", np);



// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pd.dismiss();



super.onPostExecute(result);
}



}



}

Tuesday, May 6, 2014

SOAP

package com.webservice;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WebServiceDemoActivity extends Activity
{
    /** Called when the activity is first created. */
      private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
      private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
      private static String NAMESPACE = "http://tempuri.org/";
      private static String METHOD_NAME1 = "FahrenheitToCelsius";
      private static String METHOD_NAME2 = "CelsiusToFahrenheit";
      private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";

      Button btnFar,btnCel,btnClear;
      EditText txtFar,txtCel;
   
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        btnFar = (Button)findViewById(R.id.btnFar);
        btnCel = (Button)findViewById(R.id.btnCel);
        btnClear = (Button)findViewById(R.id.btnClear);
        txtFar = (EditText)findViewById(R.id.txtFar);
        txtCel = (EditText)findViewById(R.id.txtCel);
     
        btnFar.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        //Initialize soap request + add parameters
                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);      
               
                  //Use this to add parameters
                  request.addProperty("Fahrenheit",txtFar.getText().toString());
               
                  //Declare the version of the SOAP request
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
               
                  envelope.setOutputSoapObject(request);
                  envelope.dotNet=true;
               
                  try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                     
                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION1, envelope);
                     
                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject)envelope.bodyIn;

                        if(result != null)
                        {
                              //Get the first property and change the label text
                              txtCel.setText(result.getProperty(0).toString());
                        }
                        else
                        {
                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  }
            });
     
        btnCel.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        //Initialize soap request + add parameters
                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);      
               
                  //Use this to add parameters
                  request.addProperty("Celsius",txtCel.getText().toString());
               
                  //Declare the version of the SOAP request
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
               
                  envelope.setOutputSoapObject(request);
                  envelope.dotNet = true;
               
                  try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                     
                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION2, envelope);
                     
                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject)envelope.bodyIn;

                        if(result != null)
                        {
                              //Get the first property and change the label text
                              txtFar.setText(result.getProperty(0).toString());
                        }
                        else
                        {
                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  }
            });
     
        btnClear.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        txtCel.setText("");
                        txtFar.setText("");
                  }
            });
    }
}

FB Login

Declare

private boolean isFacebookLogin = false;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
String name,email,bdate,contact;
private ProgressDialog mProgressDialog = null;
ProgressDialog pd;

RelativeLayout rl;

//OnCreate()

Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }
        getFBUserData(session);

Login Click

call  onClickLogin()

@Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }
 

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            Toast.makeText(Login.this, "sucess", 10).show();
           // getFBUserData(session);
        } else {
            Session.openActiveSession(this, true, statusCallback);
            Toast.makeText(Login.this, "sucess", 10).show();
           // getFBUserData(session);
        }
    }

    private void onClickLogout() {
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        public void call(Session session, SessionState state, Exception exception) {
        getFBUserData(session);
       
        }
    }
    public void getFBUserData(Session session) {

if (session.isOpened()) {
if (Login.this != null) {
mProgressDialog = ProgressDialog.show(Login.this, "", "Please Wait...");
}

Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

public void onCompleted(GraphUser user, Response response) {
if (user != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}

String link = user.getLink();
name = user.getName();
email = user.getUsername();
bdate = user.getBirthday();


isFacebookLogin = true;

if (link.length() != 0) {

SharedPreferences savedData = getSharedPreferences("Dompanion", 0);

SharedPreferences.Editor editor = savedData.edit();



editor.putString("email", email);
editor.putString("name", name);

editor.putInt("logged_in", 2);
editor.putString("dom", "A");
editor.commit();

Intent i = new Intent(Login.this,MainActivity.class);
startActivity(i);

}


}
}
});
}

Menifest.xml

<meta-data
            android:name="com.facebook.sdk.ApplicationId"

            android:value="@string/client_app_id" />

Download

    

xml parse

Parser Class


public class parser {

// constructor
public parser() {

}

/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;

try {
// defaultHttpClient
 HttpClient httpClient = new DefaultHttpClient();

 HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);

HttpEntity httpEntity = httpResponse.getEntity();


xml = EntityUtils.toString(httpEntity);

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}

/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {



DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource();
     
is.setCharacterStream(new StringReader(xml));
 
doc = db.parse(is);

} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
           return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}

       return doc;
}

/** Getting node value
 * @param elem element
 */

/**
 * Getting node value
 * @param Element node
 * @param key string
 * */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
/*Node child;
for( child = n.item(0).getFirstChild(); child != null; child = child.getNextSibling() )
            {
           
            return child.getNodeValue();
             
            }*/
return n.item(0).getFirstChild().getNodeValue();

}

}

Java Class

ArrayList<HashMap<String, String>> list = new  ArrayList<HashMap<String,String>>();
String URL = "";

@SuppressLint("NewApi")
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);

parser parser = new parser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("item");
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
String id = parser.getValue(e, "id");
String name = parser.getValue(e, "name");
String cost = parser.getValue(e, "cost");
map.put("A", id);
map.put("B", name);
map.put("C", cost);
list.add(map);
// Toast.makeText(MainActivity.this, ""+id.toString(), 10).show();
}
        
String from[] = {"A","B","C"};
int to[] = {R.id.a1,R.id.a2,R.id.a3};
ListAdapter adp = new SimpleAdapter(MainActivity.this, list, R.layout.abc, from, to);
setListAdapter(adp);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
HashMap<String, String> nn = (HashMap<String, String>)arg0.getItemAtPosition(arg2);
Toast.makeText(MainActivity.this, ""+nn.get("B"), 10).show();
}
});

}

Map

XML file

<?xml version="1.0" encoding="utf-8"?>
<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" >

   
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>


</RelativeLayout>

Manifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <permission android:name="com.example.kets.permission.MAPS_RECEIVE"
         android:protectionLevel="signature"></permission>
     <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
   
    <uses-permission android:name="com.example.kets.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
   
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
   
   
   

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.kets.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>
        <meta-data android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAiRUNy8pqAE17_eLk96PwZlc45KHokiyw"/>
        <activity android:name="map"></activity>
       
    </application>


</manifest>

JAVA CLASS

try{
URL url = new URL(b.getString("flag"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
conn.setDoInput(true);  
conn.connect();    
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch(Exception e){
e.printStackTrace();
}






android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
   SupportMapFragment mapFragment = (SupportMapFragment) fragmentManager
           .findFragmentById(R.id.map);
   map = mapFragment.getMap();
 
 
   map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
   map.setMyLocationEnabled(true);
   map.setOnMarkerClickListener(this);
   map.setOnInfoWindowClickListener(this);
 
    map.addMarker(new MarkerOptions()
    .snippet(""+b.getString("vic"))
           .position(new LatLng(Double.parseDouble(b.getString("lat")), Double.parseDouble(b.getString("long"))))
           .title(""+b.getString("name")))
         
           .setIcon(BitmapDescriptorFactory.fromBitmap(bmImg));
   
    CameraPosition cp = new CameraPosition.Builder().target(new LatLng(Double.parseDouble(b.getString("lat")), Double.parseDouble(b.getString("long")))).zoom(20).build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
   
   
   

}
@Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub

Toast.makeText(this, ""+arg0.getTitle(), 10).show();
return false;
}
@Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, ""+arg0.getSnippet(), 10).show();


}

}

Json Parser



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
Log.e("param--- is:-",""+params);
// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();


}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.e("-------------------------->", paramString.toString());
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);

HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}


} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);

StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");

}

Log.e("ANIL", "sb.toString() >>>>>"+sb.toString());




is.close();
json = sb.toString();



} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}

ImageDB Android

Button Click

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               startActivityForResult(intent, 52);



//Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)
      {
          super.onActivityResult(requestCode, resultCode, data);
          
          if(resultCode == RESULT_OK && requestCode==52)
          {
          selectedImage = data.getData();    
          bmImage.setImageURI(selectedImage);
          }
       
      }

Button Click

String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
           if(c == null) return;            
           c.moveToFirst();
           int columnIndex = c.getColumnIndex( MediaStore.Images.Media.DATA);
           ImagePath = c.getString(columnIndex);
           c.close();
           
           
          
                 
                byte byteImage1 [] = null;
                try{ 
                FileInputStream instream = new FileInputStream(ImagePath); 
             BufferedInputStream bif = new BufferedInputStream(instream); 
             byteImage1 = new byte[bif.available()];
             bif.read(byteImage1); 
             
             Log.d("Byte Value",""+byteImage1.length); 
                }catch (IOException e) {
}
                d = h.getWritableDatabase();
                ContentValues cv =new  ContentValues();
                cv.put(h.IMAGE_DATA, byteArray);
                d.insert(h.IMAGE_TABLE, null,cv);
                d.close();
                Toast.makeText(getApplicationContext(), "Save", 6).show();