There is a function, adding user image to my app, but I need image to use again, so I chose SQLite Database to save path to image, my database works correctly. So in OnClick method, app show DialogWindow, where user choose image from gallery:
choosePath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Type - image:
photoPickerIntent.setType("image/*");
//Start activity, waiting for result
startActivityForResult(photoPickerIntent, Pick_image);
}
});
Then onActivityResult is called:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode){
case Pick_image:
if(requestCode == RESULT_OK){
try {
final Uri imageUri = imageReturnedIntent.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
Log.e("mLog", "onActivityResult: " + imageStream + " " + imageReturnedIntent + " " + imageUri);
pathToImage = imageUri.toString();
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
}
But when I save path in SQlite:
ContentValues cv = new ContentValues();
cv.put("description", description);
cv.put("image_link", pathToImage);
cv.put("category", category[0]);
long res = mDb.insert("favourites", null, cv);
if (res > -1) {
Toast.makeText(getApplicationContext(), "Шаблон добавлен в любимые", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Ошибка", Toast.LENGTH_SHORT).show();
}
I get exception:
E/SQLiteDatabase: Error inserting description=dog image_link=null category=
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: favourites.image_link (code 1299 SQLITE_CONSTRAINT_NOTNULL)
I used debugger, but it didnt help me.
Please help me to solve this problem!
Correct your if condition, that causes your code not running inside if condition and getting pathToImage object null
// you are matching here request code with result status
if(requestCode == RESULT_OK)
//It should be
if(resultCode == RESULT_OK)
Related
I have created this app based on tutorials, ATM it successfully open the camera and displays it as imgOriginal on the screen. When i press the compress button I get a error relating to '.compressToFile(imageBitmap);
Error Message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.photocompressor, PID: 11123
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getName()' on a null object reference
at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
at com.example.photocompressor.MainActivity$3.onClick(MainActivity.java:149)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if (resultCode == RESULT_OK) {
// if (resultCode == RESULT_IMAGE && resultCode == RESULT_OK ) {
if (resultCode == RESULT_OK && resultCode != RESULT_IMAGE) {
btnCompress.setVisibility(View.VISIBLE);
final Uri imageUri = data.getData();
try {
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imgOriginal.setImageBitmap(selectedImage);
////originalImage = new File(imageUri.getEncodedPath().replace("raw/", ""));
long size = DocumentFile.fromSingleUri(this, imageUri).length();
//txtOriginal.setText("Size: " + Formatter.formatShortFileSize(this, originalImage.length()));
txtOriginal.setText("Size: " + Formatter.formatShortFileSize(this, size));
Toast.makeText(MainActivity.this, "Size: " + size, Toast.LENGTH_LONG).show();
//Toast.makeText(MainActivity.this, "Size: " + Formatter.formatShortFileSize(this, originalImage.length()), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Something went Wrong", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
// }
Below is the compress button, error appears in '.compressToFile'. I would ideally like to have the option to replace the original file or to save as a new file, but havent even got the replace file to work yet.
btnCompress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int quality = seekBar.getProgress();
int width = Integer.parseInt(txtWidth.getText().toString());
int height = Integer.parseInt(txtHeight.getText().toString());
Toast.makeText(MainActivity.this, "Quality " + quality, Toast.LENGTH_SHORT).show();
try {
compressedImage = new Compressor(MainActivity.this)
.setMaxWidth(width)
.setMaxHeight(height)
.setQuality(quality)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(filepath)
//.compressToFile(originalImage);
.compressToFile(imageBitmap);
File finalFile = new File(filepath, originalImage.getName());
Bitmap finalBitmap = BitmapFactory.decodeFile(finalFile.getAbsolutePath());
imgCompressed.setImageBitmap(finalBitmap);
//long newsize = DocumentFile.fromSingleUri(this, image);
//txtCompressed.setText("size: " + Formatter.formatShortFileSize(MainActivity.this,newsize));
//Toast.makeText(MainActivity.this, filepath + " Something went Wrong", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error while Compressing", Toast.LENGTH_SHORT).show();
}
}
});
I am new here and learning about android development. I want to crop image to set profile pic. when i used below codes its not done its jump to catch(something went wrong). kindly please help me solve this problem. used Image view on xml and got permission read and write on mainfest. And used ArthurHub/Android-Image-Cropper for cropping function
enter code here select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
premission();
if (pre == 2) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
Log.d("pp", "pp");
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{ super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && null != data)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
Uri selectedImage = data.getData();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
Uri selectedImage = result.getUri();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
profileimage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
Drawable myDrawable = profileimage.getDrawable();
profileimage.buildDrawingCache();
Bitmap bmap = profileimage.getDrawingCache();
BitmapDrawable bitmapDrawable = ((BitmapDrawable) myDrawable);
Bitmap bitmap1 = bitmapDrawable.getBitmap();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, stream);
imageInByte = stream.toByteArray();
encoded = Base64.encodeToString(imageInByte, Base64.DEFAULT);
} else
{
Toast.makeText(this, "You have not picked Image",
Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
I'm having trouble using the camera when there's no sdcard present.
When there is an sdcard, using the camera is trivial, e.g.
http://www.vogella.com/articles/AndroidCamera/article.html + a plethora of other examples.
However, I need to make my app available to devices which don't have SD cards, (e.g. the Sony Xperia series.) I've tried modifying the code such that I'm using the internal storage (I think):
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(getDir("myDirec", Context.MODE_WORLD_WRITEABLE), "tmp_photo_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
file.createNewFile();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
However, upon result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentReturn) {
if (resultCode != RESULT_OK)
return;
String path = mImageCaptureUri.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(path);
...
bitmap is null.
Which leads me to believe that there's some permissions issue....maybe?
I've tried some of the other internal storage options, http://developer.android.com/guide/topics/data/data-storage.html#filesInternal e.g. getFilesDir() but the same result: null bitmap.
Has anyone had any success in using the camera without an sdcard?
Try this. It works..
private Uri imageUri;
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File dir = context.getDir("directory", Context.MODE_PRIVATE);
File photo = new File(dir, "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, OPEN_CAMERA);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case OPEN_CAMERA:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
}
}
I'm trying to launch an Android camera intent and a choose-photo intent (two buttons, one for take photo, one for choose from gallery) and both need a crop intent launched after them then have the cropped photo returned to my app's activity. I've gone through a bunch of the examples posted elsewhere, but I'm getting strange reults with my implementation.
For the take photo event, it appears to work fine, except after taking a photo and going into crop mode, the wrong photo pops up. Instead of cropping the photo you just took it crops an older photo and I can't figure out where it's coming from. Also, sometimes after finishing the crop intent, it crashes with a nullpointerexception after Parcel.readException (can't always reproduce, but I think it haappens more if you take a picture and crop as quickly as possible).
For the choose photo intent, your gallery pops up as expected but upon choosing a photo all that happens is the message "Saved" is toasted instead of returning to my app's activity with the image. I believe I have a misunderstanding of how the choose photo intent works (I pretty much reused the code for the take photo intent).
In both cases, in crop mode you are still allowed to resize the cropped area despite having specified "scale" = false.
My code is as follows:
public class TestPhotoActivity extends Activity {
private ImageView imageView;
private Uri imageUri;
private int int_Height_crop = 600;
private int int_Width_crop = 600;
public final static int TAKE_PICTURE = 0;
public final static int CHOOSE_PICTURE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_photo);
imageView = (ImageView) findViewById(R.id.photo);
Button take_photo = (Button) findViewById(R.id.take_photo);
take_photo.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
takePhoto(view);
}
});
Button choose_photo = (Button) findViewById(R.id.choose_photo);
choose_photo.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
choosePhoto(view);
}
});
}
public void takePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE", null);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", int_Width_crop);
intent.putExtra("outputY", int_Height_crop);
intent.putExtra("scale", false);
intent.putExtra("return-data", true);
File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, TAKE_PICTURE);
}
public void choosePhoto(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", int_Width_crop);
intent.putExtra("outputY", int_Height_crop);
intent.putExtra("scale", false);
intent.putExtra("return-data", true);
File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, CHOOSE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
Log.d("photo", "requestCode: " + requestCode + "resultCode: " + resultCode + "wanted result: " + Activity.RESULT_OK);
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
Log.w("photo", "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, "No photo picked.", Toast.LENGTH_SHORT);
t.show();
return;
}
final Bundle extras = data.getExtras();
if (extras != null) {
Log.d("photo", "extras is not null");
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
Log.d("photo", "data.getAction() is not null. setting image.");
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.e("photo", e.toString());
}
}
}
case CHOOSE_PICTURE:
Log.d("photo", "requestCode: " + requestCode + "resultCode: " + resultCode + "wanted result: " + Activity.RESULT_OK);
if(resultCode == RESULT_OK){
Log.d("photo", "resultCode is ok");
if (data == null) {
Log.w("photo", "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, "No photo picked.", Toast.LENGTH_SHORT);
t.show();
return;
}
final Bundle extras = data.getExtras();
if (extras != null) {
Log.d("photo", "extras is not null");
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
Log.d("photo", "data.getAction() is not null. setting image.");
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.e("photo", e.toString());
}
}
}
}
}
}
Any help is greatly appreciated!
EDIT: I should also note that I'm testing on an LG Optimus LTE, Android 2.3
I think your problem comes from useing System.currentTimeMillis() in the temp file name. This would explain sometimes getting an older file.
I would suggest just reusing the same temp file.
Hope it helps...
This the code I am using to take picture, display it, then send it in an email:
private void takePicture() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(),
getIntent().getStringExtra("counter"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
savePicture(getIntent().getStringExtra("counter"), bitmap,
getApplicationContext());
setImage();
Toast.makeText(this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
}
}
How I send the email:
final Intent emailIntent = new Intent(
android.content.Intent.ACTION_SEND);
String fileName = null;
try {
fileName = URLEncoder.encode(getIntent().getStringExtra("counter"), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory()+"/"+fileName.trim().toString();
Uri uri = Uri.parse("file://"+path);
emailIntent.setType("image/png");
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, uri);
/* Send it off to the Activity-Chooser */
startActivity(Intent
.createChooser(emailIntent, "Send Email..."));
Notice, my file name should be getIntent().getStringExtra("counter");
When I do this, my email sends a text file rather than an image file. I have no clue why it does this...
I suspect this has happened to more than one person, but the problem was this:
I had to add +".jpg" to the end of the filename, and now it works. This may have been a simple solution but it surely was a distressful problem!
Hope this post still helps those who encounter this issue in the future.