I want to capture image & save it to SD card. Now its working fine.
My problem is 1) after capture OK and Cancel button are avialble.When I click Ok only it need to save the image into SD card.
2) It doesn't come to onActivityResult method. I have written my onActivityResult inside the ActivityGroup class.
This code for When User click on Camera button, it will open cameara & save it
//Camera
Button btnCamera =(Button)findViewById(R.id.btnCamera);
btnCamera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
selectedImagePath = Environment.getExternalStorageDirectory()+"/"+retailerCode+"-"+count+".jpg";
imgName =retailerCode+"-"+count+".jpg";
count++;
File file = new File(selectedImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Bundle b = new Bundle();
b.putString("Activity", "RetailerOrderSActivity");
b.putString("RetailerName", seletctedRetailer);
b.putString("RetailerCode", retailerCode);
intent.putExtras(b);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
onPhotoTaken();
}
});
protected void onPhotoTaken() {
_taken = true;
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(CameraMainActivity.this);
dbAdapter.openDataBase();
boolean status = dbAdapter.saveImageInfo(retailerCode,strExecutive,strBusinessUnit,strTerritoryCode,imgName,visitNumber);
if(status) {
Toast.makeText(SalesActivityGroup.group.getApplicationContext(), "Image has been saved successfully" , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(SalesActivityGroup.group.getApplicationContext(), "Image has not been saved successfully" , Toast.LENGTH_SHORT).show();
}
dbAdapter.close();
lstCaptures = getAllImage(imgDateVal.getText().toString());
imageViewTable.removeAllViews();
loadTableLayout();
}
This is code for ActivityGroup
public class SalesActivityGroup extends ActivityGroup {
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("===REQUEST=====" +requestCode);
System.out.println("==resultCode==" +resultCode); } }
Actually I need to call onPhotoTaken from onActivityResult. According current my code if the user click cancel also, it saving information to DB. Image is not captured..
This is my app image :
This is button showing after capture image:
Please anybody sort out this issue..
Thanks in advance
Check the following answer
Suppose I have a button Select & when the user clicks on the button , Camera screen will open.
btn_select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String fileName = new StringBuilder(String.valueOf(System.currentTimeMillis())).append(
".jpg").toString();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, IShipdocsMobileConstants.CAMERA_ACTION);
}
});
After the user takes a photo & clicks on the Save/OK button (depends on the mobile device) , use the following code to fetch the data for the captured image.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == IShipdocsMobileConstants.CAMERA_ACTION) {
if (resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
SelectedFileInfo selectedFileObj = null;
ArrayList<SelectedFileInfo> cameraArrList = new ArrayList<SelectedFileInfo>();
File fileObj = new File(capturedImageFilePath);
String fileSize = String.valueOf(fileObj.length()); //File Size
String fileName = Utils.getFileName(capturedImageFilePath); //File Name
}else if (resultCode == RESULT_CANCELED) {
// handle the condition in which the user didn't save the image
}
} else {
// handle the condition in which the request code was not CAMERA_ACTION , maybe send the user to the home/default screen
}
}
}
Problem is calling place I need to call getParent().startActivityForResult(intent, CAMERA_PIC_REQUEST); more details see here
Related
i have a registration activity in which user can upload image from his gallery, i want to pass this photo to navigation drawer in main activity & also to userprofile activity and i cant find the way how, code for RegistrationActivity:
code for RegistrationActivity:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
de.hdodenhof.circleimageview.CircleImageView uplo;
private static int RESULT_LOAD_IMAGE = 1;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final Button bRegister = (Button) findViewById(R.id.bRegister);
//upload profile image
uplo = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.uploadimage);
uplo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(RegisterActivity.this,MainActivity.class);
i.putExtra("picture", String.valueOf(uplo));
startActivity(i);
finish();
}
});
}
//to take the chosen image from user mobile gallery
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
uplo.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
a sample of code would be very helpful
thank you
Send the intent
Intent intent = new Intent(Home.this, Upload.class);
intent.putExtra("picture", thumbnail);
and receive in other other activity
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("picture");
hope it work :)
If you want to send the image, just send the path.
change it to.
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(RegisterActivity.this,MainActivity.class);
i.putExtra("picture", picturePath);// send path
startActivity(i);
finish();
}
});
and receive the path in another activity.
and set as..
.setImageBitmap(BitmapFactory.decodeFile(picturePath));
2nd If you want to access picture on other activities
Just put the path in shared preferences as USER_DP string. and get it whenever you want. eg.
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
shared.edit().putString("USER_DP",picturePath).commit();// like this
You can use below code to save your path in to shared preferences and you can fetch it as per your requirement. initialise shared preference
SharedPreferences sharedPref = context.getSharedPreferences(SHARED,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
save path
public void savePath(String key,String path){
editor.putString(key, path);
editor.commit();
}
retrieve path in your specific class--
` public String getPath(String key ){
if (sharedPref.contains(key)){
String path="";
path=sharedPref.getString(key, " ");
return path;
}
return "";
} `
I did code for capturing the image from camera and it works fine,
After capturing the image it is asking for click ok in camera but i want to get image without clicking on ok button. my code for is as below and i don't have idea to get image without clicking ok button so please help me.
button_camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Log.e("PATH", filePath+"");
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
}
};
On button click listerner write the following code
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
To achieve this, we should notify the camera intent to enable quick capture mode, while calling it. Below the code:
private static final int REQUEST_IMAGE_CAPTURE = 1;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra("android.intent.extra.quickCapture", true); // enables single click image capture
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Note: I learned from stackoverflow and few other sites people say some devices do not support this mode. And I am not sure what devices those are. To this date, I've tested on devices from different brands with API levels 21 to 28, which all has worked for me so far.
In my app i'm using the camera app on the phone in order to take a picture. After taking the picture it returns back to my app. I noticed that it acts differently in different phones. In Galaxy s3 I found that after taking a picture it shows the picture and gives an option to save it (and then go back to my app) or discard (and go back to the camera app). The problem is that when the screen is rotated the app crushes when the save/discard screen appears. The only way to stop it from crushing is to take the picture without rotating the screen and keep it that way.
Is there a solution to this problem? Maybe there is a way that I can define that it won't allow rotation at this screen?
Here is the code:
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Specify target file
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
newPicName = android.os.Environment.getExternalStorageDirectory() + "/"+app.APP_FOLDER + "/" + app.getSession()+ "_"+app.getDateTime()+ "_" +sdf.format(cal.getTime()) +".jpg";
File imageFile = new File(newPicName);
Uri imageFileUri = Uri.fromFile(imageFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(intent, 0);
If you just want to limit the orientation of the screen you need to specify it in your manifest… For example:
<activity
android:name="com.xxx"
android:label="#string/xxx"
android:screenOrientation="portrait" > //this limits the screen to only portrait.
</activity>
Additional Info
This is how I do it and it works for me perfectly.
//instance variables
private static final int TAKE_PICTURE = 0;
private Uri mUri;
private Bitmap mPhoto;
//First I create a method to capture the image.
private void captureImage() {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "profile.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
startActivityForResult(i, TAKE_PICTURE);
}
//Then I handle the result.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE://this is a constant defined in my instance variables.
if (resultCode == Activity.RESULT_OK) {
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try {
mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, mUri);
//set your photo in a screen…
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Try following code :
private File tempFile;
private static final int CAMERA_IMAGE = 1;
public void takePicFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (tempFile != null) {
Log.i(""image Path : "", tempFile.getPath());
Uri picUri = Uri.fromFile(tempFile); // convert path to Uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
Log.i("Picture Uri", " : " + picUri);
}
startActivityForResult(intent, MedicationConstants.CAMERA_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {
if (requestCode == MedicationConstants.CAMERA_IMAGE) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (tempFile != null) {
//do anything with image file. Store in database. Or even should add functionality of dropping
}
}
}, 2000);
}
}
In on onActivityResult you should add functionality of image cropping. Please have a look at simple-crop-image-lib. It is great library & works for almost all device.
Thanks
I want to save image uri from taking camera or gallery into SQLite.
And I want to display the image which called uri from SQLite.
If I want to do this, someone said you have to save image uri into SQLite as byte, and
you can set image on imageView.
I understand the theory, but I am still getting stuck with my coding.
If it is true, I want to save formatted image into sdcard or somewhere.
someone said use BitmapFactory and decodeResource.
and call the uri from R.drawable.
However, I don't know how to save image into R.drawable folder.
Could you help me? I will give you some my coding.
I am fighting with saving image into SQLite and how to load it, and how to modify it during two weeks!
Sorry for really long coding. I don't know where I am now.
Thank you.
fridgeDetails.java
populateFields();
private void populateFields()
{
if (mRowId != null)
{
Cursor data = mDbHelper.fetchItem(mRowId);
startManagingCursor(data);
//load image from sqlite
byte[] blob = data.getBlob(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_IMAGE));
mImageView.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length));
nameEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_NAME)));
categoryEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_CATEGORY)));
expired_Date_Btn.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_EXPIRED_DATE)));
}
else{
expired_Date_Btn.setText(
new StringBuilder()
.append(mDay).append("/")
//month is 0 based. Then add 1
.append(mMonth + 1).append("/")
.append(mYear).append(" "));
}
}
//create dialog for taking image
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(item==0)
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, PICK_FROM_CAMERA);
}
catch(ActivityNotFoundException e)
{
e.printStackTrace();
}
}
else
{
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
//image chooser
startActivityForResult(Intent.createChooser(galleryIntent, "Complete action using"), PICK_FROM_GALLERY);
}
}
});
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
//set alarm with expiration date
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
Toast.makeText(fridgeDetails.this, "Alarm automatic set", Toast.LENGTH_SHORT).show();
saveState();
setResult(RESULT_OK);
finish();
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case PICK_FROM_CAMERA:
Bundle extras = data.getExtras();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage = Bitmap.createScaledBitmap(selectedImage, 200, 200, false);
mImageView.setImageBitmap(selectedImage);
break;
case PICK_FROM_GALLERY:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
Bitmap bt=Bitmap.createScaledBitmap(bitmap, 200, 200, false);
mImageView.setImageBitmap(bt);
break;
}
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
saveState();
}
#Override
protected void onPause()
{
super.onPause();
saveState();
}
#Override
protected void onResume()
{
super.onResume();
populateFields();
}
private void saveState()
{
String name = (String) nameEdit.getText().toString();
String category = (String) categoryEdit.getText().toString();
String expired_date = (String) expired_Date_Btn.getText().toString();
byte[] image = ConvertDrawableToByteArray(mImageView.getDrawable());
if(mRowId == null)
{
long id = mDbHelper.insertItem(category, name, expired_date, image);
if(id>0)
{
mRowId = id;
}
}
else
{
mDbHelper.updateItem(mRowId, category, name, expired_date, image);
}
}
public static byte[] ConvertDrawableToByteArray(Drawable drawableResource) {
Bitmap imageBitmap = ((BitmapDrawable) drawableResource).getBitmap();
ByteArrayOutputStream imageByteStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, imageByteStream);
byte[] imageByteData = imageByteStream.toByteArray();
return imageByteData;
}
The location of your image file can be obtained from data.getData() in OnActivityResult method. You can save the location as a string in Sqlite. Then use
imageView.setImageBitmap(BitmapFactory.decodeFile(filename)
to show the image.
The default location is your app folder. If you want to store elsewhere, pass the location as in the foll code
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
For more info see - http://developer.android.com/guide/topics/media/camera.html
Check this to Get the URI of Captured image
Check this for Inserting image to DB as BLOB and Retrieve it back and display.
It includes download image from Server and insert into DB, just change as it as per your requirement.
I have an activity that retrieves images from the device's gallery and uploads to a service. Now, for optimisation purposes, I would like to avoid uploading images that are on Picasa an just store their ID or URL for later retrieval.
So my question is, how do I retrieve that information. My intent code is pasted below and retrieves the URI of the image.
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(galleryIntent, GALLERY_PIC_REQUEST);
I tried to look for the PICASA_ID (MediaStore.Images.Media.PICASA_ID), but by using the method above, it returns null. Any ideas?
Launch an ACTION_GET_CONTENT intent instead of an ACTION_PICK
Provide a MediaStore.EXTRA_OUTPUT extra with an URI to a temporary file.
Add this to your calling activity:
File yourFile;
Now use this code to get Intent:
yourFile = getFileStreamPath("yourTempFile");
yourFile.getParentFile().mkdirs();
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
galleryIntent .setType("image/*");
galleryIntent .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(yourFile));
galleryIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());
startActivityForResult(galleryIntent, GALLERY_PIC_REQUEST);
MAKE SURE THAT yourFile is created
Also in your calling activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case GALLERY_PIC_REQUEST:
File file = null;
Uri imageUri = data.getData();
if (imageUri == null || imageUri.toString().length() == 0) {
imageUri = Uri.fromFile(mTempFile);
file = mTempFile;
//this is the file you need! Check it
}
//if the file did not work we try alternative method
if (file == null) {
if (requestCode == 101 && data != null) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
//check this string to extract picasa id
}
}
break;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
int index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(index);
}
else return null;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dir =new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyImages");
dir.mkdir();
filename = ("Image_" + String.valueOf(System.currentTimeMillis()) + ".poc");
}
protected Uri getTempFile()
{
File file = new File(dir,filename);
muri = Uri.fromFile(file);
return muri;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("Pick Image");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
openOptionsChooseDialog();
return true;
}
private void openOptionsChooseDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(AppActivity.this).setTitle("Select Image").setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
startActivityForResult(intent, SELECT_PICTURE);
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case SELECT_PICTURE : if (resultCode == RESULT_OK)
{
filepath = muri.getPath();
Toast.makeText(this, filepath, Toast.LENGTH_SHORT).show();
//can do bla bla bla...
}
I have used the same approach and it woks.Hope It could help u too..