Pages

Thursday 25 July 2013

Fetching image from GALLERY



  •   To fetching image from the gallery. We use Intent.ACTION_GET_CONTENT in Intent function.
  •   Then, We have to set type to intent.setType("image/*").

            Function

  •             Intent(Intent.ACTION_GET_CONTENT).
  •             setType("image/*").
  •    startActivityForResult.

  
       Coding Part:

                 XML:

       <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />

       Activity:

       public class Gallery extends Activity {

    Button clickBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);

 clickBtn=(Button)findViewById(R.id.button1);

clickBtn.setOnClickListener(new OnClickListener() {

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

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                     intent.setType("image/*");
                     startActivityForResult(intent, 0);
}
});


     protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
          super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

          switch(requestCode) {
          case 0:
              if(resultCode == RESULT_OK){
                  Uri selectedImage = imageReturnedIntent.getData();

                  String[] filePathColumn = {MediaStore.Images.Media.DATA};
                  Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

                  cursor.moveToFirst();

                  int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

                 //file path of selected image
                  filePath = cursor.getString(columnIndex);
                  File f = new File(filePath);
                  filename= f.getName();
               
                  Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
                  Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
                  cursor.close();
           
   
              }
              break;
}
     }
}
}

IN MANIFEST:

Add the following things to your Manifest.
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />






No comments:

Post a Comment