I use the following codes to launch the camera from my app:
private void saveFullImage() {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName()
+ File.separatorChar + "Android/data/"
+ RegistrationDetails.this.getPackageName() + "/files/"
+ md5("filedummy") + ".jpg";
File photoFile = new File(path);
try {
if (photoFile.exists() == false) {
photoFile.getParentFile().mkdirs();
photoFile.createNewFile();
}
} catch (IOException e) {
Log.e(TAG, "Could not create file.", e);
}
Log.i(TAG, path);
Uri fileUri = Uri.fromFile(photoFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
} else {
new AlertDialog.Builder(this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState).setCancelable(true)
.create().show();
}
}
And I have the following codes in onActivityResult to show that the picture has been taken, so I can proceed the next step:
} else if (requestCode == TAKE_PICTURE) {
if (data == null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Take Picture finished", 10);
toast.show();
}
And I have defined the following settings in AndroidManifest: android.permission.CAMERA and android.permission.WRITE_EXTERNAL_STORAGE
The launch Camera intent works, but when I make a picture and click on Save, then it does not return to onActivityResult and my app crashes.
Can someone help me with this?
Thanks
I got some problems with Galaxy S version 2.3.4 and camera.
After a little work, it actually work with this code (tested with Galaxy S and Nexus S).
You can try it and say me if it works for you.
private Uri mCapturedImageURI;
private void takePhoto() {
String fileName = "temp.jpg";
if (isGalaxyS()) {
fileName = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
File fileTmp = new File(fileName);
if (fileTmp.exists()) fileTmp.delete();
mCapturedImageURI = Uri.fromFile(fileTmp);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Image prise via XXX :)");
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, PICK_FROM_CAMERA);
}
private boolean isGalaxyS() {
Log.d("Photo", android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
ArrayList<String> devices = new ArrayList<String>();
devices.add("samsung/GT-I9000/GT-I9000");
return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_FROM_CAMERA: {
Bitmap photo = null;
String filenameDest = Repertoires_S.getInstance().Get_Photos_Path() + DateTime_BO_S.getInstance().Date_Courante_AAAAMMJJ_HHMMSS() + ".jpg";
File fDest = new File(filenameDest);
String capturedImageFilePath;
if (data == null) {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" utilisé
try {
if (isGalaxyS()) {
String fileName = "temp.jpg";
capturedImageFilePath = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
} else {
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();
capturedImageFilePath = cursor.getString(column_index_data);
}
File fSrc = new File(capturedImageFilePath);
fSrc.renameTo(fDest);
photo = BitmapFactory.decodeFile(filenameDest);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" non utilisé -> miniature
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
}
}
if (photo != null) {
try {
int tailleMaxPhoto = 800;
double rap;
int newWidth;
int newHeight;
if (photo.getWidth() > tailleMaxPhoto || photo.getHeight() > tailleMaxPhoto) {
// Si c'est plus grand on redimensionne
if (photo.getWidth() > photo.getHeight()) {
rap = (double)tailleMaxPhoto / photo.getWidth();
newWidth = tailleMaxPhoto;
newHeight = (int)((double)photo.getHeight() * rap);
} else {
rap = (double)tailleMaxPhoto / photo.getHeight();
newHeight = tailleMaxPhoto;
newWidth = (int)((double)photo.getWidth() * rap);
}
Bitmap photoSmall = Bitmap.createScaledBitmap(photo, newWidth, newHeight, true);
if (photoSmall != null) {
FileOutputStream out = new FileOutputStream(filenameDest);
if (photoSmall.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
}
} else {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
}
Related
I would like to copy the image from the ACTION_GET_CONTENT and it should copy in Image directory in external storage.
I was getting the toast message but the image couldn't find in folder. Right now I giving permission manually so don't worry about that.
uriImagePath Gallary :content://com.android.providers.media.documents/document/image%3A3934
Destination: Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans"
I also added permission in the manifest file.
Here is my code. Any help much appreciated.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY = 22;
private static final String TAG = MainActivity.class.getSimpleName();
Button btn_copy;
private String imagepath = Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans/a.png";
private Uri uriImagePath;
private String realPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_copy = findViewById(R.id.btn_copy);
}
public void CopyImage(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
imagepath = Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans";
uriImagePath = Uri.fromFile(new File(imagepath));
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriImagePath);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent, REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY);
Toast.makeText(this, "Hi hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
realPath = ImageFilePath.getPath(MainActivity.this, data.getData());
// realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
Log.d("onActivityResult", "Destination imagePath :" + imagepath);
Log.d("onActivityResult", "uriImagePath Gallary :" + data.getData().toString());
Log.i(TAG, "onActivityResult: file path : " + realPath);
File f = new File(imagepath);
if (!f.exists())
{
try {
f.createNewFile();
copyFile(new File(getRealPathFromURI(data.getData())), f);
Log.i(TAG, "Inside if creating new file and call copy function: ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Video.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
I want to upload image to the server. Converted my image as bitmap but still getting error. Bitmap too large to be uploaded into a texture
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
contentURI = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if (l == 0) {
imagePath = cursor.getString(columnIndex);
}
}
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), bitmap);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else if (requestCode == CAMERA) {
//if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
if (data != null) {
contentURI = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
if (l == 0) {
imagePath = cursor.getString(column_index_data);
}
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), thumbnail);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
saveImage(thumbnail);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
If i get picture using gallery means I am getting error as "Bitmap too large to be uploaded into a texture"
and if i get picture using camera means getting error as
"Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=18253, uid=10257 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()"
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress( Bitmap.CompressFormat.JPEG, 90, bytes );
wallpaperDirectory = new File( Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY );
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
f = new File( wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg" );
f.createNewFile();
FileOutputStream fo = new FileOutputStream( f );
fo.write( bytes.toByteArray() );
MediaScannerConnection.scanFile( this, new String[]{f.getPath()}, new String[]{"image/jpeg"}, null );
fo.close();
Log.d( "TAG", "File Saved::--->" + f.getAbsolutePath() );
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
Try this, link to library
https://github.com/Tourenathan-G5organisation/SiliCompressor
/**
* Request Permission for writing to External Storage in 6.0 and up
*/
private void requestPermissions(int mediaType) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (mediaType == TYPE_IMAGE) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID);
}
} else {
if (mediaType == TYPE_IMAGE) {
// Want to compress an image
dispatchTakePictureIntent();
} else if (mediaType == TYPE_VIDEO) {
// Want to compress a video
dispatchTakeVideoIntent();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakeVideoIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
default:
}
}
private File createMediaFile(int type) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = (type == TYPE_IMAGE) ? "JPEG_" + timeStamp + "_" : "VID_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
type == TYPE_IMAGE ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_MOVIES);
File file = File.createTempFile(
fileName, /* prefix */
type == TYPE_IMAGE ? ".jpg" : ".mp4", /* suffix */
storageDir /* directory */
);
// Get the path of the file created
mCurrentPhotoPath = file.getAbsolutePath();
Log.d(LOG_TAG, "mCurrentPhotoPath: " + mCurrentPhotoPath);
return file;
}
private void dispatchTakePictureIntent() {
/*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");*/
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createMediaFile(TYPE_IMAGE);
} catch (IOException ex) {
// Error occurred while creating the File
Log.d(LOG_TAG, "Error occurred while creating the file");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// Get the content URI for the image file
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
photoFile);
Log.d(LOG_TAG, "Log1: " + String.valueOf(capturedUri));
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_CAMERA_PHOTO);
}
}
}
private void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
try {
takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
createMediaFile(TYPE_VIDEO));
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
Log.d(LOG_TAG, "VideoUri: " + capturedUri.toString());
startActivityForResult(takeVideoIntent, REQUEST_TAKE_VIDEO);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method which will process the captured image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//verify if the image was gotten successfully
if (requestCode == REQUEST_TAKE_CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
new ImageCompressionAsyncTask(this).execute(mCurrentPhotoPath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Silicompressor/images");
} else if (requestCode == REQUEST_TAKE_VIDEO && resultCode == RESULT_OK) {
if (data.getData() != null) {
//create destination directory
File f = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/Silicompressor/videos");
if (f.mkdirs() || f.isDirectory())
//compress and output new video specs
new VideoCompressAsyncTask(this).execute(mCurrentPhotoPath, f.getPath());
}
}
}
class ImageCompressionAsyncTask extends AsyncTask {
Context mContext;
public ImageCompressionAsyncTask(Context context) {
mContext = context;
}
#Override
protected String doInBackground(String... params) {
String filePath = SiliCompressor.with(mContext).compress(params[0], new File(params[1]));
return filePath;
/*
Bitmap compressBitMap = null;
try {
compressBitMap = SiliCompressor.with(mContext).getCompressBitmap(params[0], true);
return compressBitMap;
} catch (IOException e) {
e.printStackTrace();
}
return compressBitMap;
*/
}
#Override
protected void onPostExecute(String s) {
/*
if (null != s){
imageView.setImageBitmap(s);
int compressHieght = s.getHeight();
int compressWidth = s.getWidth();
float length = s.getByteCount() / 1024f; // Size in KB;
String text = String.format("Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", "ff", length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
}
*/
File imageFile = new File(s);
compressUri = Uri.fromFile(imageFile);
//FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName()+ FILE_PROVIDER_EXTENTION, imageFile);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), compressUri);
imageView.setImageBitmap(bitmap);
String name = imageFile.getName();
float length = imageFile.length() / 1024f; // Size in KB
int compressWidth = bitmap.getWidth();
int compressHieght = bitmap.getHeight();
String text = String.format(Locale.US, "Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", name, length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
As for loading large bimaps, read docs: https://developer.android.com/topic/performance/graphics/load-bitmap
Basically, you should provide inSampleSize to load load scaled version. Don't try to decode large bitmap without scaling, this will fail.
I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.
// code for the same
// code fro open camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
// on activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA) {
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");
Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));
filePath = destination.toString();
if (filePath != null) {
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
}
}
// send to server code
private void execMultipartPost() throws Exception {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
Log.d("TAG", "file new path: " + file.getPath());
Log.d("TAG", "contentType: " + contentType);
RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);
final String filename = "file_" + System.currentTimeMillis() / 1000L;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("date", "21-09-2017")
.addFormDataPart("time", "11.56")
.addFormDataPart("description", "hello")
.addFormDataPart("image", filename + ".jpg", fileBody)
.build();
Log.d("TAG", "execMultipartPost: "+requestBody);
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://myexample/api/user/lets_send")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.d("TAG", "response of image: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
Try This, it may help
Intent takePhotoIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
String timeStamp = new SimpleDateFormat(pictureNameDateFormat, Locale.US).format(date.getTime());
File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (fileDirectory.exists()) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
new File(Environment.getExternalStorageDirectory() + "/Pictures/picture_"+ timeStamp + ".png")));
takePhotoIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePhotoIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (takePhotoIntent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(takeVideoIntent, captureVideoActivityRequestCode);
}
}
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();
}
Log.e("path",Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
}
Please use below code to capture image by camera and for pick image from gallery and you can crop also.
First of all please add this dependency in your build.gradle
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
In your Activity please add this code :
uploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectImageClick(view);
}
});
/**
* Start pick image activity with chooser.
*/
public void onSelectImageClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_REQUEST_CAMERA);
} else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
CropImage.startPickImageActivity(this);
}
}else {
CropImage.startPickImageActivity(this);
}
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
startCropImageActivity(imageUri);
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
fileUri = result.getUri();
userImage.setImageURI(result.getUri());
Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
CropImage.startPickImageActivity(this);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Start crop image activity for the given image.
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
in manifest please add these permissions and ask for run time permissions also ,this may solve your problem ,Your coding is correct those works for me perfectly after adding permission.
Please go trough the following code
try {
if (imageUri != null) {
photo = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
} else {
photo = (Bitmap) data.getExtras().get("data");
}
Uri tempUri = CommonData.getImageUri(getContext(), photo);
uri = tempUri.toString();
String path = CommonData.convertImageUriToFile(tempUri, getActivity());
// new PreprocessImagesTask().execute(path);
showLoader();
new ProcessingImage(this).execute(path);
} catch (Exception e) {
e.printStackTrace();
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
String imgPath = "";
String Path;
try {
Cursor cursor = null;
int imageID = 0;
try {
/* ********** Which columns values want to get ****** */
String[] proj = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
};
cursor = activity.getContentResolver().query(
imageUri, // Get data for specific image URI
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null // Order-by clause (ascending by name)
);
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int size = cursor.getCount();
/* ****** If size is 0, there are no images on the SD Card. **** */
if (size == 0) {
// imageDetails.setText("No Image");
} else {
int thumbID = 0;
if (cursor.moveToFirst()) {
Path = cursor.getString(file_ColumnIndex);
//String orientation = cursor.getString(orientation_ColumnIndex);
String CapturedImageDetails = " CapturedImageDetails : \n\n"
+ " ImageID :" + imageID + "\n"
+ " ThumbID :" + thumbID + "\n"
+ " Path :" + Path + "\n";
showLog("CapturedImageDetails", CapturedImageDetails);
imgPath = Path;
// Show Captured Image detail on view
// imageDetails.setText(CapturedImageDetails);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return "" + imgPath;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return "";
}
}
Give a try!
private static final int REQUEST_IMAGE = 100;
private static final String TAG = "MainActivity";
TextView imgPath;
ImageView picture;
File destination;
String imagePath;
//onCreate
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();//get your path
imgPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
picture.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
imgPath.setText("Request cancelled");
}
}
How to cancel camera when user will click on left side icon on camera in Android emulator.When i open the camera and capture the image bitmap is send to Image_Cropping for crop the image.When cancel the camera it does not comeback to previous Activity , it goes to Image_Cropping Activity.Can someone help me to resolve it.
Here is my onActivityResult code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST)
{
if (requestCode == 0 && resultCode == 0){
Toast.makeText(getApplicationContext(),"Cancel Image Capture ", Toast.LENGTH_SHORT).show();
}else {
onCaptureImageResult(data);
}
}
if (requestCode == PROFILE_GALLERY && 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 imgDecodableString = cursor.getString(columnIndex);
cursor.close();
editor.putString("profile_picformat", imgDecodableString);
editor.commit();
Intent selfiSrc = new Intent(this, Image_Cropping.class);
finish();
startActivity(selfiSrc);
}
}
btnCamera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String picformat = "IMG_" + 0 + "_" + s.format(new Date()) + ".png";
Log.e(" picformat ", " = " + picformat);
Intent i = new Intent(Filter_Screen.this , Image_Cropping.class );
startActivity(i);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
File myPath = new File(extr, picformat);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(myPath));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
Log.e("Camera", " Open");
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String imageUserProfile_path = baseDir + "/classNKK_ProfilePic/" + picformat;
editor.putString("profile_picformat", imageUserProfile_path);
editor.commit();
}
});
This is my ImageCropping Class
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.img_cropping);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
dbhelper = new MyDbHelper(this);
dbhelper.onOpen(db);
Log.e(" In", " onCreate Method !!!!!!!!!!");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
str_Authentication_Token = sharedPreferences.getString("strAuthentication_Token", "");
str_UserId = sharedPreferences.getString("strUserId", "");
str_UserName = sharedPreferences.getString("strUserName", "");
str_UserRole = sharedPreferences.getString("strUserRole", "");
str_LoginUserName = sharedPreferences.getString("strLogin_UserName" , "" );
Log.e(" ", " str_Authentication_Token= " + str_Authentication_Token + " str_UserId= " + str_UserId + " str_UserName= " + str_UserName + "str_UserRole= " + str_UserRole + " str_LoginUserName= " + str_LoginUserName);
getProfile_PicFormat = sharedPreferences.getString("profile_picformat", "");
Log.e("getImagePath ", " getPicFormat = " + getProfile_PicFormat);
Bitmap bmp = BitmapFactory.decodeFile(getProfile_PicFormat);
if (savedInstanceState == null) {
mCropImageView.setImageBitmap(bmp);
}
mCropImageView.setAspectRatio(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES);
btnCropImage = (Button)findViewById(R.id.button_CropImage);
btnCropImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCropImageView.getCroppedImageAsync(mCropImageView.getCropShape(), 0, 0);
}
});
buttonDone = (Button)findViewById(R.id.button_Done);
buttonDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent i = new Intent(Image_Cropping.this , Filter_Screen.class);
finish();
startActivity(i);
}
});
}
// Saves the state upon rotating the screen/restarting the activity
#Override
protected void onSaveInstanceState(#SuppressWarnings("NullableProblems") Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
}
// Restores the state upon rotating the screen/restarting the activity
#Override
protected void onRestoreInstanceState(#SuppressWarnings("NullableProblems") Bundle bundle) {
super.onRestoreInstanceState(bundle);
mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
}
#Override
protected void onStart() {
super.onStart();
mCropImageView.setOnSetImageUriCompleteListener(this);
mCropImageView.setOnGetCroppedImageCompleteListener(this);
}
#Override
protected void onStop() {
super.onStop();
mCropImageView.setOnSetImageUriCompleteListener(null);
mCropImageView.setOnGetCroppedImageCompleteListener(null);
}
#Override
public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
if (error == null) {
Toast.makeText(mCropImageView.getContext(), "Image load successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mCropImageView.getContext(), "Image load failed: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onGetCroppedImageComplete(CropImageView view, Bitmap bitmap, Exception error) {
if (error == null)
{
croppedImage = bitmap;
int bitMapWidth = croppedImage.getWidth();
int bitmapHeight = croppedImage.getHeight();
Log.e("croppedImage","="+croppedImage + " bitMapWidth="+bitMapWidth + " bitmapHeight="+bitmapHeight);
String[] finalPath = getProfile_PicFormat.split("/");
final String split_CroppedString = finalPath[finalPath.length - 1];
Log.e(" split_CroppedString ", " = " + split_CroppedString);
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
cropped_ImagePath = "Cropped_"+split_CroppedString;
Log.e("cropped_ImagePath "," ======>>" + cropped_ImagePath );
File myPath = new File(extr, cropped_ImagePath);
FileOutputStream fileOutputStream = null;
try
{
fileOutputStream = new FileOutputStream(myPath);
croppedImage.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
editor = sharedPreferences.edit();
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String cropped_UserProfilepath = baseDir + "/classNKK_ProfilePic/" + cropped_ImagePath;
editor.putString("croppedImagePath", cropped_UserProfilepath);
editor.commit();
String str_ProfilePic_UpLoadStatus = "0";
db = dbhelper.getWritableDatabase();
db.execSQL("update Inspector set ProfilePICURL = '" + cropped_ImagePath + "' , ProfilePic_UpLoadStatus='"+0+"', DownLoadStatus='1' where Inspector_Id = '" + str_UserId + "'");
db.execSQL("update ALL_Post set ProfilePICURL = '" + cropped_ImagePath + "' , DownLoad_Status='1' where UserId = '" + str_UserId + "'");
Log.e("Updated ", " Succesfully !!! ImageName = " + cropped_ImagePath);
sendPostRequest(cropped_ImagePath);
Log.e("Cropped ", " Profile Pic UpLoaded SuccesFully !!!!!!!!!!!!!! ");
String delete_cropped_UserProfilepath = baseDir + "/classNKK_ProfilePic/" + split_CroppedString;
File file= new File(delete_cropped_UserProfilepath);
if(file.exists())
{
file.delete();
Log.e("Original "," File is deleted !!!");
}
Intent i = new Intent(Image_Cropping.this , Filter_Screen.class);
startActivity(i);
finish();
} else {
Toast.makeText(mCropImageView.getContext(), "Image Crop failed: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
((CropImageView) findViewById(R.id.CropImageView)).setImageUriAsync(imageUri);
}
}
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}}
Thanks in advanced .
Now just copy this.
No any changes in Imagecropping clsaa.
btnCamera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String picformat = "IMG_" + 0 + "_" + s.format(new Date()) + ".png";
Log.e(" picformat ", " = " + picformat);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
File myPath = new File(extr, picformat);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(myPath));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
Log.e("Camera", " Open");
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String imageUserProfile_path = baseDir + "/classNKK_ProfilePic/" + picformat;
editor.putString("profile_picformat", imageUserProfile_path);
editor.commit();
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST)
{
if (requestCode == 0 && resultCode == 0){
Toast.makeText(getApplicationContext(),"Canceling Image Capture ", Toast.LENGTH_SHORT).show();
}else {
onCaptureImageResult(data);
}
}
if (requestCode == PROFILE_GALLERY && 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 imgDecodableString = cursor.getString(columnIndex);
cursor.close();
editor.putString("profile_picformat", imgDecodableString);
editor.commit();
Intent selfiSrc = new Intent(this, Image_Cropping.class);
finish();
startActivity(selfiSrc);
}
}
private void onCaptureImageResult(Intent data) {
Intent selfiSrc = new Intent(this, Image_Cropping.class);
startActivity(selfiSrc);
finish();
}
I am working on Android chat application. Now I want to send emoji's in my chat module. How can i implement emoji' in chat application? Please guide me for this app. If there is any API for this app then also suggest me. Thanks
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new GetSingleChat(Chat_Detail_Single.this).execute(friend_id);
} catch (NullPointerException e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 1000, 1000);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btncamera:
Dialog_Manager.chooseImage(Chat_Detail_Single.this, "singlechat");
break;
case R.id.img_back:
timer.cancel();
finish();
break;
case R.id.btnsend:
String message_ = edt_mes.getText().toString();
if (message_.replace(" ", "").length() == 0) {
} else {
edt_mes.setText("");
new Send_chat_message(Chat_Detail_Single.this).execute(SharedPref.getUserID(this), friend_id, "mes", message_);
}
break;
}
}
public static void get_chat_data(List<Chat_prop> fetch_chat) {
MyCustomList.clear();
MyCustomList.addAll(fetch_chat);
try {
if (adptor == null) {
adptor = new Single_Chat_Adap(activity,
MyCustomList);
Chat_Detail_Single.listView.setAdapter(adptor);
Chat_Detail_Single.listView.setSelection(MyCustomList
.size() - 1);
lastCount = MyCustomList.size();
} else {
if (lastCount != MyCustomList.size()) {
lastCount = MyCustomList.size();
adptor.notifyDataSetChanged();
Chat_Detail_Single.listView
.setSelection(MyCustomList.size());
}
}
} catch (NullPointerException e) {
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == Dialog_Manager.Gallery_Intent
&& resultCode == RESULT_OK && data != null) {
File direct = new File(
Environment.getExternalStorageDirectory() + "/Fun You");
if (!direct.exists()) {
if (direct.mkdir())
;
}
long time = System.currentTimeMillis();
capturepath1 = direct.getAbsolutePath() + "/" + time + ".jpg";
File file = new File(capturepath1);
Uri outputFileUri = Uri.fromFile(file);
Uri selectedImage = data.getData();
imagePath = getPath(selectedImage);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
Uri contentUri = selectedImage;
cropIntent.setDataAndType(contentUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 1000);
cropIntent.putExtra("outputY", 1000);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 3);
} else if (requestCode == Dialog_Manager.Camera_Intent
&& resultCode == RESULT_OK) {
File direct = new File(
Environment.getExternalStorageDirectory() + "/Fun You");
if (!direct.exists()) {
if (direct.mkdir())
;
}
long time = System.currentTimeMillis();
capturepath1 = direct.getAbsolutePath() + "/" + time + ".jpg";
File file = new File(capturepath1);
Uri outputFileUri = Uri.fromFile(file);
File photos = new File(imagePath);
Uri selectedImage = Uri.fromFile(photos);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
Uri contentUri = selectedImage;
cropIntent.setDataAndType(contentUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 1000);
cropIntent.putExtra("outputY", 1000);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 3);
} else if (requestCode == 3) {
try {
Bitmap thumbnail = null;
Bundle extras = data.getExtras();
if (extras != null) {
thumbnail = extras.getParcelable("data");
Bitmap bm = thumbnail;
bm = ExtraMethods.decodeFile(capturepath1);
bm = ExifUtils.rotateBitmap(capturepath1, bm);
// new Uplaod_image().execute(capturepath1);
new Send_chat_message(Chat_Detail_Single.this).execute(SharedPref.getUserID(this), friend_id, "image", capturepath1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG)
.show();
}
}
public String getPath(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
There is no specific api available to implement and send emojis. You can achieve this using ImageSpan objects. The TextViews and EditTexts use Spanned/Spannable objects to store the entered text content, not just mere Java Strings. On these Spanned/Spannable objects you can define spans for sections on the text that modifies the way that those sections are shown. So you can display images in place of certain sections.
Check the docs:
Also, I found a blog, it might be helpful for you.
This Library is all you need to implement Emojicons. Just don't forget to change your TextViews and EditTexts to this Library's EmojiconTextViews and EmojiconEditTexts respectively.
Hope this helps.
You need to encode emoji before upload.
in this way you encode emoji to UTF code
try {
String mystring = URLEncoder.encode(strComments, HTTP.UTF_8);
param.add(new BasicNameValuePair("comment", mystring));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
for decoding
enter code here
try {
String Title = URLDecoder.decode(comment, "UTF-8");
holder.tvComment.setText(Title);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}