How To Save and Retrieve path image in SQLite android - java

i want to save and retrieve image path in my application
this is my DBhelper
public void insert(String kdstore,String nama, String alamat, String kodepos, String notel,
String lng, String lat ,String Perus,String gambar){
//waktu = new Date().toString();
ContentValues cv = new ContentValues();
cv.put("kdstore", kdstore);
cv.put("nama", nama);
cv.put("alamat", alamat);
cv.put("kodepos", kodepos);
cv.put("notel", notel);
cv.put("lng", lng);
cv.put("lat", lat);
cv.put("Perus", Perus);
cv.put("gambar", df.fileName);
System.out.println();
getWritableDatabase().insert("alfamapp", "name", cv);
}
and this is my startCameraActivity
_path=Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
fileName = String.format(System.currentTimeMillis()+".jpg");
File file = new File(_path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, IMAGE_CAPTURE);
how can i save path from cameraActivity in my database??
please help me :)
i put code to inserting on startCamera method,,this code like this
public void startCamera()
{
Cursor c = helper.getById(almagId);
c.moveToFirst();
file = new File(_path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
file1 = new File(_path, fileName);
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
finishActivity(IMAGE_CAPTURE);
Uri outputFileUri1 = Uri.fromFile(file1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri1);
startActivityForResult(intent, IMAGE_CAPTURE);
System.out.println(file1);
Dbhelper helper = new Dbhelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update alfamapp set gambar ='"+file+"',gambar1 ='"+file1+"' " +
"where kdstore='"+helper.getKdStore(c)+"'");
db.execSQL("insert into image (kdstore,image1) values ('"+helper.getKdStore(c)+"','"+file+"')");
db.execSQL("update image set image2 ='"+file1+"' where kdstore='"+helper.getKdStore(c)+"'");
db.close();
helper.close();
load();
System.out.println(db);
}
and then this code to retrieve this image
if(helper.getGamb(c).equals("")){
System.out.println("gamb kosong");
detGam.setImageResource(R.drawable.gambarnf);
}else detGam.setImageDrawable(Drawable.createFromPath(helper.getGamb(c)));
you have solution to my code??thank you very much :)

You can use onActivityResult for saving path after capturing photo.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if( requestCode == IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase sql = dbHelper.getWritableDatabase();
sql.execSQL("insert statement for inserting path to database");
sql.close();
dbHelper.close();
}
}

Use this code for getting the image path...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_IMAGE:
String imagePath = getPath(data.getData());
Savingimagepath(imagePath);
img.setImageDrawable(Drawable.createFromPath(imagePath));
break;
}
}
}
and this is the sample method for saving the path in database
private void Savingimagepath(String imagePath) {
testDatabase testDB = new testDatabase(contact.this);
testDB.open();
try {
testDB.getexecute("delete from ctoffice");
testDB.getexecute("insert into ctoffice (idnt1)Values('"
+ imagePath + "')");
} catch (Exception e) {
System.out.println(e);
}
testDB.close();
}

Related

Cannot upload image file using retrofit2

Problem with old code, image sending to server is thumbnail image (so small). So with new code, Android has changed the way to get real size image. However, new code not working upload file to the server. It says filename is empty and when I do log body request not the same result as the old code. Any help, I really appreciate because almost one week I still couldn't found what is the problem with the new code.
///////// This is old cold//////////////////////////////////
///////////////////////////////////////////////////////////
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
switch (resultCode) {
case Activity.RESULT_CANCELED: {
break;
}
case Activity.RESULT_OK: {
if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, bytes);
if (typePhoto.equals("ftCarLol")) {
carLoL = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + "ftLol.png");
FileOutputStream fo = null;
try {
carLoL.createNewFile();
fo = new FileOutputStream(carLoL);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ftCar.setImageBitmap(thumbnail);
}
if (typePhoto.equals("sdcarLol")) {
sdCad = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + "sdCars.png");
FileOutputStream fo = null;
try {
sdCad.createNewFile();
fo = new FileOutputStream(sdCad);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sdCar.setImageBitmap(thumbnail);
}
}
break;
}
}
}
}
// in retrofit
MultipartBody.Part[] imageUserList = new MultipartBody.Part[2];
RequestBody propertyImage = null;for(
int i = 0;i<2;i++)
{
if (i == 0) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), carLoL);
imageUserList[i] = MultipartBody.Part.createFormData("car", carLoL.getName(), propertyImage);
}
if (i == 1) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), sdCad);
imageUserList[i] = MultipartBody.Part.createFormData("sd", sdCad.getName(), propertyImage);
}
}
// Call function interface retrofit
Call<JsonObject> clientreq = client.submitReport(imageUserList);
// interface retrofit
#Multipart
#POST("TestReport")
Call<JsonObject>submitReport(#Part MultipartBody.Part[] files);
/////////////////////// new code////////////////////////////////////
File tempFile = new File(Environment.getExternalStorageDirectory(), "tmp.png");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri photoURI = FileProvider.getUriForFile(this, "cntsb.com.rodeo.fileprovider", tempFile);
// result activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
if (typeChoose.equals("sdcarLol")) {
sdCad = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() +"sdCars.png");
try {
sdCad.createNewFile();
if(tempFile.renameTo(sdCad)) {
Glide.with(context).load(sdCad).into(sdCar);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (typeChoose.equals("ftCarLol")){
carLoL = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + "ftLol.png");
try {
carLoL.createNewFile();
if(tempFile.renameTo(carLoL)) {
Glide.with(context).load(carLoL).into(ftCar);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// attach file into retrofit
MultipartBody.Part[] imageUserList = new MultipartBody.Part[2];
RequestBody propertyImage = null;for(
int i = 0;i<2;i++)
{
if (i == 0) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), carLoL);
imageUserList[i] = MultipartBody.Part.createFormData("car", carLoL.getName(), propertyImage);
}
if (i == 1) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), sdCad);
imageUserList[i] = MultipartBody.Part.createFormData("sd", sdCad.getName(), propertyImage);
}
}
// Call function interface retrofit
Call<JsonObject> clientreq = client.submitReport(imageUserList);
Expected result: after log request body
�PNG
������IHDR��������������������}��������s��O����� ��IDATx�\�k�d�q%�wĹ7���h4��B$%R�F������|�G�k��g$��z-{F=H�C
$�#t��g>�9��f������2o�s"b��;��/�o�&�Hp��)��4�l��gs�� � ��I#FdN�'l9�ۭ��� �� ejb�H�q��,��':Jw�D)`�4�"ő 3#9��Lg���d LF���f:߸5O��L�bhn��HN�$) !�$�dDЍ�� -F���e0E)�� ��[r$DP���6� �����߼T��4���1�`��+4�$M���%s�sR�L�� ��B�D2�������$Ѥ$������RRԚ.cDv����[(3����R�Df�9:"a23R!����"!)��BL�dfRQ[��C��jl����{}�e9�
e�0���s(d�T��H)QR(���H#fX����)���Hm2(Aa�C��$��i6��"�%q������LfI(�F���Zf�$
�d2If�0���Y�LF����`��D$pGI����(364��6�eO���#dD$֣�Ӻ�0�$IA����[I!���'LI��9�#i֤>ƨ?���0��ʡ��&��4$��DMn�.�ljH���IR��
4 �9���PH��ƒ#D�4��͐��#�Y��]Rf���1s�� $�"I�� ��c����7)3��f���xR�C)i$���U�X�}u�ZSw�il��H��`��吹�:��mM +����m�z���S(�XX'֜Z�f�3#!�)I�"�#��ެ>�c���i�����E��S��d(33"�9���tw%ͽ��H2I�9J)�C���$Ț�2�L$��ȔxX��K
�<7��4�S��H&epI�j�Բ�1z��L���b����\c��`��\?�H�jM�0� R# ��|<Q� QI���6ײ$է����j�"S�,��?u���D���zI8��f����ˈTD�ߎr��_=�`��3��H��˼2���I!����5nͥ�+�Y�uְnF=���~`�B��״�`մ�����̬MDssw�%2s�NfBf(qJ
ID�2S\�HV�!����R�Z��Hef�H�8��z�ua���4��:H�Q{��t�Uj�I1���_V����#!AEJ
[��CffHO������jwk�!���5�CT؀��E���,c�/���:��rN��`����#B���<������ʢ���썭��YYE�)V��9�R6�f��4�$ dB0�U3SF��f�����X���FV
��1tJ5\��tk���VxT�S��������&V4��I�H4d��LO���.h*#�))���M-s���&#33���$d3I$�m=�`m�d�/��{�`)���
=��F���L3�H$��4��gIt��Ar#f03�G�q%Y�N#~ʼv�1�̯���I2��HZq2m�me��!i2.�RI�S$h(�5��R�����5���wP�ҪC8�^>��S�]SY�##��i�TbG�g2bT:�F Ɍ��&o�H`>��pnI�Ԛ(��
4dk�"N�i$�4{%h"Sn�Ќ��D�ZkUN��{���z�#����4k
dB��[Y(C��I��if ������tx%n���kMO�I��Lr�(�=�ehHLA9F0*��V(\�����2S^�B��$�.)B�QHiD׊�(�*kם�4M����H�9�fNfV+r
���(�16�R���.<ǪRF�,�d$92��aP��.#����ښ"ift0:�)�ܽ���G�&�(d_�H+df���j�)��7���$Vk���(#9MS5v�d�zP�� ��BdJ�1����D���ٚ�����z�2�#��c��UxQh6R˲��N�iE�nS��s��Tݵ��#DdF��C'��D�<��$��܎J0��׏��^ߨ�s��ڒ��C�bD�y������I��֚Y�#�� ���������" #LU!Y����53W�!L2m����U�Y��(xM2�R�A�jg�v*���6W:�r��jX$�6RZѝ5�t��)��<G��BM(Y����y��7��c���2N��R�1WT`�٦*�IV�è����D�Ĝ���2��^ �8U�GkE�$��N8
(���hk/�#��3�nS�5�g��r<���ՙ����0�<���}D�,�Wi#�P�t�$ִ����0"j����D��
error from new code:
����A2Exif����MM��*�����������������������������������������������������������������������������������������������������������������������������(��������������1���������������2������������������������������i����������������!8HUAWEI����DUK-L09��������H������������H������DUK-L09 9.0.1.176(C636E2R1P5)�����2019:07:04 10:46:13����.��������������������������������P�������������� ʈ"���������������'������������������������0210������������� ڐ������������ ������������������������ ��
����������X������������� Ғ��
����������#���
����������H������������� ������������������������������� ���������������
������������0�|��������d���� N�|����������� ��|��������/�������|�����������`�|������������ H��������������!��������������!
��������������!�����������0100��������������������������������������������������������!�������������������������������������������������������������������������������������������������������������8������������������������������������������������������������������ �����������������
����������������������������������������������������������d������d����������������������������
����;������������'#*#*201709272016::76������/��`����������DLBB8�}N�������������������::76������/��`����������DLBB8�}N�������������������::76������/��`����������DLBB8�}N�������������������::54������/��`�����#����AIBB8�wN�������������������::54����/����`�����#����AIBB8�wN�������������������::54����/����`�����#����AIBB8�wN�������������������::2����.����`�����#����=EBB8�rN�������������������::0/������-��`�����#����:CBB8�oN��������������������� ��4����B������������������������������������������275��h����� ��+����j^SJC>93+$m_TKD?:4,%o`ULE?:4-%qbVME?:5.&sdWMF#;7/' ueXMFA=70( vfXNGA=81)!vfYNGB=81)"ufYOGB>92*"teZOHB>:3+#tfZPIC>:4+$tfZQIC>:4,$sfZRJD>:4,%qdZRJD?:4-%odZQJD?:5-&mcYQJD?:5.&������������������������������������������������������������������������������������:�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������J���#�������������������������������������������x�� �������F��F��������������������������������������� ����������������������*������:����������������������*������:������(��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

Get image from storage not working in Android

I am capturing an image and store it in storage in mobile but when I get this image it cannot show any thing in Image View. I have tried a lot of code to get images from file but none of them are working in my emulator or real Samsung device.
enter code here
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap getImageFileFromSDCard(String filename){
/* Bitmap bitmap = null;
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap; */
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
// File imgFile = new File(filename);
//("/sdcard/Images/test_image.jpg");
Bitmap myBitmap;
if(imageFile.exists()){
myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
// myImage.setImageBitmap(myBitmap);
return myBitmap;
}
return null;
}
First of All make sure you have declared the "Access External Storage" and "Access Hardware Camera" permissions in "AndroidManifest" and if you are using Android version 23 or 23+ then you have to take permissions on run-time.
If this is not the problem then use this code given below, it's working fine for me.
For Camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, ACTION_REQUEST_CAMERA);
For Gallery:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent.createChooser(intent, "Choose a Picture");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
OnActivityResultMethod:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
Uri galleryImageUri = data.getData();
try{
Log.e("Image Path Gallery" , getPath(getActivity() , galleryImageUri));
selectedImagePath = getPath(getActivity() , galleryImageUri);
} catch (Exception ex){
ex.printStackTrace();
Log.e("Image Path Gallery" , galleryImageUri.getPath());
selectedImagePath = galleryImageUri.getPath();
}
break;
case ACTION_REQUEST_CAMERA:
// Uri cameraImageUri = initialURI;
Uri cameraImageUri = data.getData();
Log.e("Image Path Camera" , getPath(cameraImageUri));
selectedImagePath = getPath(cameraImageUri);
break;
}
}
}
Method to get path of Image returned from Camera:
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}

Android Video Image intent return value

I have one intent that should allow users to pick either a picture or a video from the gallery. The problem is that I cant find other method than checking the extension type to know the file type and display it in one way or another
public void pickMedia(View View) {
Intent intent = new Intent();
intent.setType("image/* audio/* video/*");
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 == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (intent type == video)
A;
if (intent type == audio)
B;
if (intent type == image)
C;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
How should I proceed?
i usually create a method similar to this:
public static File getFileFromUri(Uri uri, Activity activity){
File f = null;
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
if(cursor.getString(column_index)!=null){
f = new File(cursor.getString(column_index));
}else{
InputStream is =null;
try {
is = activity.getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
f= stream2file(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return f;
}
and :
public static String getMimeType(String url)
{
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
in your onActivityResult you can get the file chosen like so:
Uri fileUri = data.getData();
File f = getFileFromUri(fileUri, this);
String filePath = f.getAbsolutePath();
String type = getMimeType(filePath);

How do I save an image after modifying it

I can load the picture to the background then I have also been able to "sketchify" it but when I try to save it so that I can email it as an attachment I can only figure out haw to grab the original image and what I have here makes the activity close
public void startCamera(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
seek.setVisibility(View.GONE);
if (takePicture.resolveActivity(getPackageManager()) != null) {
picSpot = new File(Environment.getExternalStorageDirectory(),
"sketch.png");
outputFileUri = Uri.fromFile(picSpot);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePicture, REQUEST_IMAGE_CAPTURE);
}
}
public void sendPic(View v) {
Intent sharePic = new Intent(Intent.ACTION_SEND);
if (didsketch == false) {
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
} else {
try {
FileOutputStream out = new FileOutputStream(finalSpot);
back.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
outputFileUri = Uri.fromFile(finalSpot);
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
sketchit.setEnabled(true);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;
location = Environment.getExternalStorageDirectory()
+ "/sketch.png";
back = Camera_Helpers.processImage(location, screenHeight,
screenWidth);
taken = true;
sketchit.setEnabled(taken);
shareit.setEnabled(taken);
image.setImageBitmap(back);
}
}
back is the modified bitmap i am trying to eventually attach to the email
Thanks!!!
Create Folder Directory and Save image into it: create directory where you want to save your images. Suppose the folder name is ImageFolder.
String location = Environment.getExternalStorageDirectory() + "/ImageFolder/";
//Creating Folder Directory
File imageDir = new File(location);
dir.mkdirs();
//Creating Image file
String imageName = "sketch.png";
File imageFile = new File(imageDir, imageName);
//If image file already exists then delete it.
if (imageFile.exists()) {
imageFile.delete();
}
//Writing the image to SDCard
try {
FileOutputStream out = new FileOutputStream(imageFile);
back.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Getting a crash when taking a picture on Android. Why?

When I take a picture with my device, this code is crashing on the inputStream = line with an error of java.lang.NullPointerException
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriImage;
InputStream inputStream = null;
ImageView imvCover = (ImageView)this.findViewById(R.id.imvCover);
if ((requestCode == CAPTURE_IMAGE) && resultCode == Activity.RESULT_OK) {
uriImage = data.getData();
try {
inputStream = getContentResolver().openInputStream(uriImage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, null);
imvCover.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
imvCover.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imvCover.setAdjustViewBounds(true);
}
}
Any ideas why?
This is the code I am using to open the camera to take a picture:
Button btnTakePicture = (Button)this.findViewById(R.id.btnTakePicture);
btnTakePicture.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
try this..
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, "newImage.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(i, 1);
and this is onActivity result..
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent)
{
super.onActivityResult(requestCode, resultcode, intent);
File out = new File(Environment.getExternalStorageDirectory(), "newImage.jpg");
if(!out.exists())
{
Log.v("log", "file not found");
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Log.v("log", "file "+out.getAbsolutePath());
File f = new File(out.getAbsolutePath());
try {
ExifInterface exif = new ExifInterface(out.getAbsolutePath());
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
//Toast.makeText(getApplicationContext(), ""+orientation, 1).show();
Log.v("log", "ort is "+orientation);
} catch (IOException e)
{
e.printStackTrace();
}
Bitmap photo =decodeFile(f,400,400);
}
and this is decodeFile Function...
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
This approach may not work for all devices. Instead, you can specify where the new image would be saved, and then you can use that pre-determined file path to work with the new image.
File tempFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/your_folder");
tempFolder.mkdir();
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/your_folder", String.valueOf(System.currentTimeMillis()) + ".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, TAKE_PICTURE);

Categories

Resources