How to receive multiple gallery results in onActivityResult - android

I want to start the gallery via intent and want to get the results in my onActivityResult method.
All works fine if i click on one pic.
The question ive got now is, how do i get the results, if i choose more than one picture in the gallery?
If found hcpl´s code, which does it for one picture:
public class BrowsePicture extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

You need to store that image path into array string then retrieve it according to your requirement.
Here is a sample code which will Pop up one Dialog box with 3 selection criteria like camera, Gallery, Device.
This may help you.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class FileAttachPopUpUtils extends Activity {
private View rootView;
private Dialog popup;
private Button Assig_PopUp_DeviceBtn;
private Button Assig_PopUp_GalaryBtn;
private Button Assi_PopUp_CameraBtn;
private Button Assig_PopUp_CancelPopupBtn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.assignment_popupfile);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
/*
* getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
* WindowManager.LayoutParams.FLAG_FULLSCREEN);
*/
popup = new Dialog(this);
// popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
// popup.getWindow().setBackgroundDrawable(new
// ColorDrawable(android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.assignment_popupfile);
popup.setCanceledOnTouchOutside(false);
popup.show();
Assig_PopUp_DeviceBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_DeviceBtn);
Assig_PopUp_GalaryBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_GalaryBtn);
Assi_PopUp_CameraBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CameraBtn);
Assig_PopUp_CancelPopupBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CancelPopupBtn);
Assig_PopUp_DeviceBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* Toast.makeText(FileAttachPopUpUtils.this,
* "Device File In-Progress", Toast.LENGTH_SHORT) .show();
*/
Intent intent = new Intent(FileAttachPopUpUtils.this,
FileExplore.class);
startActivity(intent);
popup.dismiss();
finish();
}
});
Assig_PopUp_GalaryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
});
Assi_PopUp_CameraBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// ///////////////////////////////////////////////////////////////
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
Assig_PopUp_CancelPopupBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_OK) {
if (requestCode == 1) {
/*
* Intent intent = new Intent( Intent.ACTION_PICK,
* android.provider
* .MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
* startActivityForResult(intent, 2);
*/
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
// mImage.setImageBitmap(thumbnail);
// 3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
// 4
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
// File fileimage = new File(path, name);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + name);
System.out.println("FILE PATH=======>>>>>>>>>>"
+ file.toString());
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
// 5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assignments.mulPathArry.add(file.toString());
// Here Your Storing the image Path each time it calls
popup.dismiss();
FileAttachPopUpUtils.this.finish();
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = this.getContentResolver().query(selectedImage,
filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
System.out
.println("path of image from gallery......******************........."
+ picturePath);
Assignments.mulPathArry.add(picturePath);
// Here Your Storing the Image Path when each time it calls
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
}
// ///////////////////////////////////////////////////////////////////////
}
#Override
public void onBackPressed() {
return;
}
}

Related

How to get video from device and set it to imageview in android

I am trying to get video from device storage and set it to the
imageview but when i am selecting video the video is not display to
me in my imageview. and i want to share video to people like share it, whats app etc...when i am clicking on image it will get the video but not set the preview on imageview.
here is my code any solution please provide
package com.example.priya.electionmgntdemoapplication.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.priya.electionmgntdemoapplication.R;
public class VideoDemo extends AppCompatActivity implements View.OnClickListener {
int SELECT_VIDEO_REQUEST = 100;
String selectedVideoPath = "";
private static final int SELECT_VIDEO = 2;
String selectedPath = "";
Uri selectedImageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_demo);
imageView = (ImageView) findViewById(R.id.video);
imageView.setOnClickListener(this);
}
public void openGalleryAudio() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video "), SELECT_VIDEO);
}
public void selectVideoFromGallery() {
Intent intent;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
} else {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI);
}
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data", true);
startActivityForResult(intent, SELECT_VIDEO_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO_REQUEST) {
if (data.getData() != null) {
selectedVideoPath = getPath(data.getData());
Bitmap bmThumbnail;
// MINI_KIND: 512 x 384 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(selectedVideoPath,
MediaStore.Images.Thumbnails.MINI_KIND);
imageView.setImageBitmap(bmThumbnail);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shareIt();
}
});
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
/* if (requestCode == SELECT_VIDEO) {
System.out.println("SELECT_VIDEO");
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
System.out.println("SELECT_VIDEO Path : " + selectedPath);
imageView.setImageURI(selectedImageUri);
} */
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Video.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void onClick(View view) {
// openGalleryAudio();
selectVideoFromGallery();
}
private void shareIt() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("video");
intent.putExtra(Intent.EXTRA_STREAM, selectedImageUri);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Check My Image ");
startActivity(Intent.createChooser(intent, "Share video"));
}
}
Here is a example how to get/create a thumbnail from a video:
public static String getThumbnailPathForLocalFile(Context context, Uri fileUri) {
long fileId = getFileId(context, fileUri);
MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), fileId, 3, null);
Cursor thumbCursor = context.getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, thumbColumns, "video_id = " + fileId, null, null);
if (thumbCursor.moveToFirst()) {
return thumbCursor.getString(thumbCursor.getColumnIndex("_data"));
}
return null;
}
public static long getFileId(Context context, Uri fileUri) {
Cursor cursor = context.getContentResolver().query(fileUri, mediaColumns, null, null, null);
if (cursor.moveToFirst()) {
return (long) cursor.getInt(cursor.getColumnIndexOrThrow(SQLiteHelper._ID));
}
return 0;
}
then in onActivityResult:
String thumbPathString = getThumbnailPathForLocalFile(this, data.getData());
imageView.setImageURI(Uri.parse(thumbPathString));
I hope this helps you.
I haven't tested this because thumbnail path is stored in SQLite..

Spring Boot REST Post Image Upload To Server In Android Using Multi Part Request

#RequestMapping(value="/upload/{id}", method=RequestMethod.POST)
public #ResponseBody BillUpload billUpload(#PathVariable Integer id,
#RequestParam("file") MultipartFile files) throws IOException{
if (!files.isEmpty()) {
FileUploadBean fileBean=new FileUploadBean();
fileBean.setFile(files.getBytes());
fileBean.setConsumerId(id);
fileBean.setFileName(files.getOriginalFilename());
String path= FileUploadProcess.createFile(fileBean);
BillUpload billUpload=new BillUpload();
billUpload.setUri(path);
return billuploadRepository.save(billUpload);
} else {
return new BillUpload();
}
}
This is RestController Which is a Multipart Request to Upload Image to Server.
I'm trying to Upload the selected Image from Gallery to Server Using Multi-part Request.
package com.example.takeimage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
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.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import org.springframework.web.client.RestTemplate;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends Activity implements View.OnClickListener {
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
Button btnSelect;
ImageView ivImage;
Button btnClick;
static String ConsumerId = " ";
String path="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.ivImage);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
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) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaColumns.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
ivImage.setImageBitmap(bm);
}
#Override
public void onClick(View v) {
}
}
}
My MainActivity when the user selected any Image (from Gallery or Camera).
The selected Image must Uploaded to Server when The Upload Button is pressed.
As I added above the sending Request will be Multi Part Request (Post Method).
Can anyone Help me how to do this Thankful to them........
If you have any code share with me.

Capturing a picture and than displaying within an ImageView - Android

Hey guys I am using my webcam to simulate a camera in the emulator and when I go to take the picture and select the check mark button to use the picture I run across an error while trying to display the image back into my ImageView on the app.
Here is my code:
Initiator:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
function....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
img.setImageURI(selectedImageUri);
imagePath.getBytes();
Bitmap bm = BitmapFactory.decodeFile(imagePath);
Log.w("Here","error");
Bitmap bm = BitmapFactory.decodeFile(imagePath);
ImageView image = (ImageView) findViewById(R.id.gimg1);
image.setImageBitmap(bm);
} else if (resultCode == RESULT_CANCELED){
}
}
}
I run across a runtime error
Suggestions and thoughts are needed!
You can use the following codes. It's fully functional and allows you set image from both your camera and gallery as well. I am almost sure that your runtime error is "OutOfMemoryError: bitmap size exceeds VM budget" as I am seeing that you have loaded the captured image directly to your imageView. You should scale it , please take a look at the method called GetScaledBitmap in my following code. Hope your codes will work ok if you use that method only when you load the image to your imageview. Full example is done for you , Hope it helps.
package com.tseg.android.mctemplate;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.tseg.android.mctemplate.R;
public class PhotoTake extends Activity {
Button add1 ;
ImageView img1 ;
private static final int ACTIVITY_PHOTOS = 0;
private static final String PACKAGE = "spine";
Uri mCapturedImageURI;
private int photo_count = 0;
boolean hasPhotos = false;
Bitmap bitmap;
String[] paths;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
add1 = (Button) findViewById(R.id.add1);
img1 = (ImageView) findViewById(R.id.img1);
add1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ShowDialog(100, 1000);
}
});
}
void ShowDialog(final int req, final int choose) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("");
builder.setTitle("Select Photo")
.setCancelable(false)
.setNegativeButton("Take Photo",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d("Photo Take", "Can't create directory to save image.");
Toast.makeText(PhotoTake.this , "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
String filepath = pictureFileDir.getPath() + File.separator;
File imageFile = new File(filepath , photoFile);
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, photoFile);
image.put(Images.Media.DISPLAY_NAME, photoFile);
image.put(Images.Media.DESCRIPTION, "Accident data Accachment " + date);
image.put(Images.Media.DATE_ADDED, date);
image.put(Images.Media.DATE_TAKEN, date);
image.put(Images.Media.DATE_MODIFIED, date);
image.put(Images.Media.MIME_TYPE, "image/jpeg");
image.put(Images.Media.ORIENTATION, 0);
File parent = imageFile.getParentFile();
String path = parent.toString().toLowerCase();
String name = parent.getName().toLowerCase();
image.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
image.put(Images.Media.SIZE, imageFile.length());
image.put(Images.Media.DATA, imageFile.getAbsolutePath());
mCapturedImageURI = PhotoTake.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mCapturedImageURI);
startActivityForResult(intent, req);
}
})
.setPositiveButton("Choose Existing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(
intent, "Complete action using"),
choose);
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// From camera
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
if (mCapturedImageURI != null) {
img1.setImageBitmap(getScaledBitmap(mCapturedImageURI));;
System.out.println("Onactivity Result uri = " + mCapturedImageURI.toString());
} else {
Toast.makeText(PhotoTake.this, "Error getting Image",
Toast.LENGTH_SHORT).show();
}
}
//From gallery
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
System.out.println("Content Path : " + selectedImage.toString());
if (selectedImage != null) {
img1.setImageBitmap(getScaledBitmap(selectedImage));
} else {
Toast.makeText(PhotoTake.this, "Error getting Image",
Toast.LENGTH_SHORT).show();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(PhotoTake.this, "No Photo Selected",
Toast.LENGTH_SHORT).show();
}
}
}
public Bitmap getBitmap(String path) {
Bitmap myBitmap = null;
File imgFile = new File(path);
if (imgFile.exists()) {
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
return myBitmap;
}
public String getPath(Uri photoUri) {
String filePath = "";
if (photoUri != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(photoUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
}
return filePath;
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "SpineAttachments");
}
private Bitmap getScaledBitmap(Uri uri){
Bitmap thumb = null ;
try {
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=8;
thumb = BitmapFactory.decodeStream(in,null,options);
} catch (FileNotFoundException e) {
Toast.makeText(PhotoTake.this , "File not found" , Toast.LENGTH_SHORT).show();
}
return thumb ;
}
}
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.gimg1);
image.setImageBitmap(image);
}
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){
Bitmap image = (Bitmap) data.getExtra("data");
image_taken.setImageBitmap(image);
}
You were calling data.getData() whereas it should have been data.getExtra("data") as data is an intent which you will have put the bitmap
Very Simple way to Click button and set store image in imageview.
`public class MainActivity extends Activity {
private static final int CAMERA_PIC_REQUEST = 22;
Uri cameraUri;
Button BtnSelectImage;
private ImageView ImgPhoto;
private String Camerapath ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImgPhoto = (ImageView) findViewById(R.id.imageView1);
BtnSelectImage = (Button) findViewById(R.id.button1);
BtnSelectImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode == RESULT_OK) {
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImgPhoto.setImageBitmap(photo);
} catch (Exception e) {
Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
break;
default:
break;
}
} catch (Exception e) {
}
}
}`
Set this Manifest.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>

pictures or camera browser

I'm trying to do the next:
I have an ImageView and i want it to appears a pictures browser or camera when user touchs it to let him select or take a picture.
I've found that:
private void openPictureBrowser()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_TITLE,"A Custom Title"); //optional
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); //optional
try {
startActivityForResult(intent, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case 1: {
if (resultCode == RESULT_OK && data != null && data.getData() != null) {
String filePath = data.getData().getPath(); //WARNING: this is NOT your real path (in my case, value is set to "/external/images/media/4"
}
}
}
}
What can i do in openPictureBrowser if I want to add the camera?
And what should I do in onActivityResult to set filePath as ImageView background?
Can anybody give me a hint??
Thanxs!
public class Set_image extends Activity implements OnClickListener
{
Button btn_capture_image,btn_share_from_gallery;
ImageView iv_set_image;
private static final int REQUEST_CODE = 1;
private static final int CAMERA_REQUEST = 1888;
String filePath="";
Bitmap Main_bitmap;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.set_image);
btn_capture_image =(Button) findViewById(R.id.button_capture_image);
btn_share_from_gallery =(Button) findViewById(R.id.button_share_from_gallery);
iv_set_image = (ImageView) findViewById(R.id.imageView_set_iamge);
btn_capture_image.setOnClickListener(this);
btn_share_from_gallery.setOnClickListener(this);
}
public void onClick(View v)
{
if (v == btn_capture_image)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
if (v == btn_share_from_gallery)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST)
{
Main_bitmap = (Bitmap) data.getExtras().get("data");
iv_set_image.setImageBitmap(Main_bitmap);
}
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
BitmapFactory.Options options4 = new BitmapFactory.Options();
options4.inSampleSize = 1;
Main_bitmap = BitmapFactory.decodeFile(filePath, options4); iv_set_image.setImageBitmap(Main_bitmap);
}
cursor.close();
}
catch (Exception e)
{
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
use the following code :
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class LoadImage extends Activity
{
Activity activity=null;
Context context=null;
Button header_left_btn=null;
Button header_right_btn=null;
TextView header_text=null;
TableLayout image_table=null;
ArrayList<String> image_list=new ArrayList<String>();
ArrayList<Drawable> image_drawable=new ArrayList<Drawable>();
String path="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.header);
activity=LoadImage.this;
context=LoadImage.this;
header_left_btn=(Button)findViewById(R.id.header_left_btn);
header_right_btn=(Button)findViewById(R.id.header_right_btn);
header_text=(TextView)findViewById(R.id.header_text);
image_table=(TableLayout)findViewById(R.id.image_table);
header_text.setText("Image Table");
header_left_btn.setText("Select");
header_right_btn.setText("Clear");
registerForContextMenu(header_left_btn);
header_left_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
openContextMenu(header_left_btn);
}
});
header_right_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
image_list.clear();
image_drawable.clear();
deletePhotos();
updateImageTable();
}
});
}
public void deletePhotos()
{
String folder=Environment.getExternalStorageDirectory() +"/LoadImg";
File f=new File(folder);
if(f.isDirectory())
{
File[] files=f.listFiles();
Log.v("Load Image", "Total Files To Delete=====>>>>>"+files.length);
for(int i=0;i<files.length;i++)
{
String fpath=folder+File.separator+files[i].getName().toString().trim();
System.out.println("File Full Path======>>>"+fpath);
File nf=new File(fpath);
if(nf.exists())
{
nf.delete();
}
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Post Image");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.camer_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.take_photo:
//Toast.makeText(context, "Selected Take Photo", Toast.LENGTH_SHORT).show();
takePhoto();
break;
case R.id.choose_gallery:
//Toast.makeText(context, "Selected Gallery", Toast.LENGTH_SHORT).show();
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
break;
case R.id.share_cancel:
closeContextMenu();
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
public void takePhoto()
{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File folder = new File(Environment.getExternalStorageDirectory() + "/LoadImg");
if(!folder.exists())
{
folder.mkdir();
}
final Calendar c = Calendar.getInstance();
String new_Date= c.get(Calendar.DAY_OF_MONTH)+"-"+((c.get(Calendar.MONTH))+1) +"-"+c.get(Calendar.YEAR) +" " + c.get(Calendar.HOUR) + "-" + c.get(Calendar.MINUTE)+ "-"+ c.get(Calendar.SECOND);
path=String.format(Environment.getExternalStorageDirectory() +"/LoadImg/%s.png","LoadImg("+new_Date+")");
File photo = new File(path);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
startActivityForResult(intent, 2);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1)
{
Uri photoUri = data.getData();
if (photoUri != null)
{
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Log.v("Load Image", "Gallery File Path=====>>>"+filePath);
image_list.add(filePath);
Log.v("Load Image", "Image List Size=====>>>"+image_list.size());
//updateImageTable();
new GetImages().execute();
}
}
if(requestCode==2)
{
Log.v("Load Image", "Camera File Path=====>>>"+path);
image_list.add(path);
Log.v("Load Image", "Image List Size=====>>>"+image_list.size());
//updateImageTable();
new GetImages().execute();
}
}
public void updateImageTable()
{
image_table.removeAllViews();
if(image_drawable.size() > 0)
{
for(int i=0; i<image_drawable.size(); i++)
{
TableRow tableRow=new TableRow(this);
tableRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tableRow.setGravity(Gravity.CENTER_HORIZONTAL);
tableRow.setPadding(5, 5, 5, 5);
for(int j=0; j<1; j++)
{
ImageView image=new ImageView(this);
image.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
/*Bitmap bitmap = BitmapFactory.decodeFile(image_list.get(i).toString().trim());
bitmap = Bitmap.createScaledBitmap(bitmap,500, 500, true);
Drawable d=loadImagefromurl(bitmap);*/
image.setBackgroundDrawable(image_drawable.get(i));
tableRow.addView(image, 200, 200);
}
image_table.addView(tableRow);
}
}
}
public Drawable loadImagefromurl(Bitmap icon)
{
Drawable d=new BitmapDrawable(icon);
return d;
}
public class GetImages extends AsyncTask<Void, Void, Void>
{
public ProgressDialog progDialog=null;
protected void onPreExecute()
{
progDialog=ProgressDialog.show(context, "", "Loading...",true);
}
#Override
protected Void doInBackground(Void... params)
{
image_drawable.clear();
for(int i=0; i<image_list.size(); i++)
{
Bitmap bitmap = BitmapFactory.decodeFile(image_list.get(i).toString().trim());
bitmap = Bitmap.createScaledBitmap(bitmap,500, 500, true);
Drawable d=loadImagefromurl(bitmap);
image_drawable.add(d);
}
return null;
}
protected void onPostExecute(Void result)
{
if(progDialog.isShowing())
{
progDialog.dismiss();
}
updateImageTable();
}
}
}
i have got this code from following link :
http://tjkannan.blogspot.in/2012/01/load-image-from-camera-or-gallery.html
Hope this will help you .

Image sd card path from intent gallery

I am starting gallery through intent otherwise its giving problem to display gallery in grid view.
But i want the actual sd card path of the image i am selection from the gallery, opened by intent.
here is the code..
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/jpg");
photoPickerIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/Pictures/image.jpg"));
startActivityForResult(photoPickerIntent, 1);
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
showToast(this,"Activity cancelled");
return;
}
else if(resultCode == RESULT_OK) {
System.out.println("requestCode--"+requestCode);
System.out.println("resultCode--"+resultCode);
System.out.println("data--"+intent.getData());
Uri uri = intent.getData();
String data = uri.getPath();
System.out.println("uri.getPath()--"+uri.getPath());
System.out.println("type--"+intent.getType());
System.out.println("path--"+Environment.getExternalStorageState());
return;
}
switch (requestCode) {
case CAMERA_ACTIVITY:
Bundle b = intent.getExtras();
Bitmap bm = (Bitmap) b.get("data");
// mImageView.setImageBitmap(bm); // Display image in the View
// large image?
if (b.containsKey(MediaStore.EXTRA_OUTPUT)) { // large image?
Log.i(TAG, "This is a large image");
showToast(this,"Large image");
// Should have to do nothing for big images -- should already saved in MediaStore ... but
MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);
}
else {
Log.i(TAG, "This is a small image");
showToast(this,"Small image");
MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);
}
break;
}
}
}
I am getting all data from intent object. But i want the sd card path for the image what i am selecting to upload that image in server..
how do i get that?
You may want something like this:
Uri uri = (Uri) intent.getExtras().get("android.intent.extra.STREAM");
if ( intent.getAction().equals( Intent.ACTION_SEND ) )
{
if ( uri.getScheme().equals("content"))
{
Cursor cursor = getContentResolver().query( uri, null, null, null, null );
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndexOrThrow(Images.Media.DATA));
}
}
This Code may help you
This code will pop up one Dialog Box with Camera and gallery and devices SD card to get the images path.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.fanosedu.R;
public class FileAttachPopUpUtils extends Activity {
private View rootView;
private Dialog popup;
private Button Assig_PopUp_DeviceBtn;
private Button Assig_PopUp_GalaryBtn;
private Button Assi_PopUp_CameraBtn;
private Button Assig_PopUp_CancelPopupBtn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.assignment_popupfile);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
/*
* getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
* WindowManager.LayoutParams.FLAG_FULLSCREEN);
*/
popup = new Dialog(this);
// popup.requestWindowFeature(Window.FEATURE_NO_TITLE);
// popup.getWindow().setBackgroundDrawable(new
// ColorDrawable(android.graphics.Color.TRANSPARENT));
popup.setContentView(R.layout.assignment_popupfile);
popup.setCanceledOnTouchOutside(false);
popup.show();
Assig_PopUp_DeviceBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_DeviceBtn);
Assig_PopUp_GalaryBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_GalaryBtn);
Assi_PopUp_CameraBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CameraBtn);
Assig_PopUp_CancelPopupBtn = (Button) popup
.findViewById(R.id.Assignment_PopUp_CancelPopupBtn);
Assig_PopUp_DeviceBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* Toast.makeText(FileAttachPopUpUtils.this,
* "Device File In-Progress", Toast.LENGTH_SHORT) .show();
*/
Intent intent = new Intent(FileAttachPopUpUtils.this,
FileExplore.class);
startActivity(intent);
popup.dismiss();
finish();
}
});
Assig_PopUp_GalaryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
});
Assi_PopUp_CameraBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// ///////////////////////////////////////////////////////////////
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
Assig_PopUp_CancelPopupBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_OK) {
if (requestCode == 1) {
/*
* Intent intent = new Intent( Intent.ACTION_PICK,
* android.provider
* .MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
* startActivityForResult(intent, 2);
*/
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
// mImage.setImageBitmap(thumbnail);
// 3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
// 4
String name;
int n = 100000;
int rand;
rand = new Random().nextInt(n);
name = "Image-" + rand + ".jpg";
// File fileimage = new File(path, name);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + name);
System.out.println("FILE PATH=======>>>>>>>>>>"
+ file.toString());
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
// 5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assignments.mulPathArry.add(file.toString());
// Here You will get the full path
FileAttachPopUpUtils.this.finish();
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = this.getContentResolver().query(selectedImage,
filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Assignments.mulPathArry.add(picturePath);
// Here you will get Path
popup.dismiss();
FileAttachPopUpUtils.this.finish();
}
}
// ///////////////////////////////////////////////////////////////////////
}
#Override
public void onBackPressed() {
return;
}
}

Categories

Resources