Issue with AirLocation library - android

I have a project and i am using airlocation library for one activity to fetch the location. App is working fine at my end but the playstore reports show some frequent crashes and i am trying to debug it.
Here is my activity code
public class Selfie extends AppCompatActivity {
private AirLocation airLocation;
public static final String TAG = "SelfieAct";
private static final int REQUEST = 1856;
private TextView Time, location;
Button time_stamp, lcn_btn, Atten_btn;
private static final String TIME_STAMP = null;
NetworkController networkController;
private Button cptrm_btn;
private ImageView imgview;
private static final int CAMERA_REQUEST = 1888;
SharedPreferences prefs;
Gson gson = new Gson();
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
private SharedPreferences.Editor editor;
CheckBox checkBox;
Bitmap lesimg;
private LocationManager locationManager;
private String locationText;
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
File photoFile;
boolean facelocationset = false;
TextView textView;
Uri photoUri;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selfie_activity);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
swipeRefreshLayout = findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
networkController = RetrofitClientInstance.getRetrofitInstance().create(NetworkController.class);if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};
if (!hasPermissions(Selfie.this, PERMISSIONS)) {
Toast.makeText(this, "Please allow location permission", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(Selfie.this, PERMISSIONS, REQUEST );
} else {
//do here
}
} else {
//do here
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(this, "Cannot Continue Without Location Permission", Toast.LENGTH_SHORT).show();
finish();
return;
}
Time = findViewById(R.id.time);
prefs = getSharedPreferences(getResources().getString(R.string.prefs), MODE_PRIVATE);
editor = getSharedPreferences(getResources().getString(R.string.prefs), MODE_PRIVATE).edit();
Atten_btn = findViewById(R.id.mark_Attendence);
cptrm_btn = findViewById(R.id.cptr_btn);
imgview = findViewById(R.id.imageView10);
textView=findViewById(R.id.Waitmsg);
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationText = addresses.get(0).getAddressLine(0);
textView.setText(locationText);
facelocationset = true;
}
#Override
public void onFailed(#NotNull AirLocation.LocationFailedEnum locationFailedEnum) {
// do something
}
});
cptrm_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
ex.printStackTrace();
Log.d(TAG, "onClick: " + ex.getMessage());
Log.d(TAG, "onClick: " + ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoUri = FileProvider.getUriForFile(Selfie.this, BuildConfig.APPLICATION_ID + ".provider", photoFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Atten_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(facelocationset && mImageBitmap != null) {
Date dt = new Date(System.currentTimeMillis());
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
RequestBody requestFile = RequestBody.create(
MediaType.parse(getContentResolver().getType(FileProvider.getUriForFile(Selfie.this, BuildConfig.APPLICATION_ID + ".provider", photoFile))),
photoFile
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", photoFile.getName(), requestFile);
MultipartBody.Part io_time =
MultipartBody.Part.createFormData("io_time", df.format(dt));
MultipartBody.Part user_id =
MultipartBody.Part.createFormData("user_id", prefs.getString("uid", null));
MultipartBody.Part loc =
MultipartBody.Part.createFormData("loc", locationText);
RequestBody enctype = RequestBody.create(
okhttp3.MultipartBody.FORM, "multipart/form-data");
networkController.mark_attendance("Bearer " + prefs.getString("token", null), enctype, body, io_time, user_id, loc).enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.code() == 200) {
if(response.body().get("ok").getAsString().equals("true")){
Log.d(TAG, "onResponse: " + "Done");
Toast.makeText(Selfie.this, "Punch Success", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d(TAG, "onFailure: "+ Log.getStackTraceString(t));
}
});
}
else{
Toast.makeText(Selfie.this, "Waiting for Location or Image" , Toast.LENGTH_SHORT).show();
}
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
airLocation.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
InputStream ims = getContentResolver().openInputStream(photoUri);
mImageBitmap = BitmapFactory.decodeStream(ims);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
Bitmap mImageDisplayBitmap = handleSamplingAndRotationBitmap(getApplicationContext(), photoUri);
imgview.setImageBitmap(mImageDisplayBitmap);
}
catch (IOException io){}
File file = new File (String.valueOf(photoFile));
try {
mImageBitmap = new Compressor(this)
.setMaxHeight(200) //Set height and width
.setMaxWidth(200)
.setQuality(100) // Set Quality
.compressToBitmap(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
OutputStream fOut = new FileOutputStream(file);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
}
catch(FileNotFoundException f){}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
airLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do here
} else {
Toast.makeText(Selfie.this, "The app was not allowed to read your store.", Toast.LENGTH_LONG).show();
}
}
}
}
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(context, img, selectedImage);
return img;
}
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
}
The playstore reports show NullPointerException in this block of code
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationText = addresses.get(0).getAddressLine(0);
textView.setText(locationText);
facelocationset = true;
}
Can anyone please find out which line of code can be the cause this issue and how do i resolve it.

airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
// ***** Changes *****
if (addresses != null) {
locationText = addresses.get(0).getAddressLine(0);
if (locationText != null) {
textView.setText(locationText);
}
facelocationset = true;
}
}
}

Related

how can i compress image size before uploading this is my code

how can I compress image size before uploading this is my code
I want to compress image size before its uploaded to WordPress site
I am using WordPress rest API in my android app
how can I compress image size before uploading this is my code
I want to compress image size before its uploaded to WordPress site
I am using WordPress rest API in my android app
// getting images selected from gallery for post and sending them to server
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case FilePickerConst.REQUEST_CODE_PHOTO:
if (resultCode == Activity.RESULT_OK && data != null) {
imagePaths = new ArrayList<>();
imageRequestCount = 1;
imagePaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
if (SettingsMain.isConnectingToInternet(context)) {
if (imagePaths.size() > 0) {
btnSelectPix.setEnabled(false);
AsyncImageTask asyncImageTask = new AsyncImageTask();
asyncImageTask.execute(imagePaths);
}
}
} else {
btnSelectPix.setEnabled(true);
Toast.makeText(context, settingsMain.getAlertDialogMessage("internetMessage"), Toast.LENGTH_SHORT).show();
}
break;
}
}
private void adforest_uploadImages(List<MultipartBody.Part> parts) {
Log.d("info image parts", parts.toString());
String ad_id = Integer.toString(addId);
RequestBody adID =
RequestBody.create(
okhttp3.MultipartBody.FORM, ad_id);
Log.d("info SendImage", addId + "");
final Call<ResponseBody> req = restService.postUploadImage(adID, parts, UrlController.UploadImageAddHeaders(context));
req.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Log.v("info Upload", response.toString());
JSONObject responseobj = null;
try {
responseobj = new JSONObject(response.body().string());
Log.d("info UploadImage object", "" + responseobj.getJSONObject("data").toString());
if (responseobj.getBoolean("success")) {
adforest_updateImages(responseobj.getJSONObject("data"));
int selectedImageSize = imagePaths.size();
int totalSize = currentSize + selectedImageSize;
Log.d("info image2", "muImage" + totalSize + "imagePaths" + totalUploadedImages);
if (totalSize == totalUploadedImages) {
adforest_UploadSuccessImage();
imagePaths.clear();
paths.clear();
if (allFile.size() > 0) {
for (File file : allFile) {
if (file.exists()) {
if (file.delete()) {
Log.d("file Deleted :", file.getPath());
} else {
Log.d("file not Deleted :", file.getPath());
}
}
}
}
}
} else {
adforest_UploadFailedImage();
Toast.makeText(context, responseobj.get("message").toString(), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
adforest_UploadFailedImage();
e.printStackTrace();
} catch (IOException e) {
adforest_UploadFailedImage();
e.printStackTrace();
}
btnSelectPix.setEnabled(true);
} else {
adforest_UploadFailedImage();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("info Upload Image Err:", t.toString());
if (t instanceof TimeoutException) {
adforest_UploadFailedImage();
// adforest_requestForImages();
}
if (t instanceof SocketTimeoutException) {
adforest_UploadFailedImage();
// adforest_requestForImages();
//
} else {
adforest_UploadFailedImage();
// adforest_requestForImages();
}
}
});
}
private void adforest_UploadFailedImage() {
progress_bar.setVisibility(View.GONE);
loadingLayout.setVisibility(View.GONE);
Gallary.setVisibility(View.VISIBLE);
Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_black_24dp, 0, 0, 0);
Gallary.setText("" + 0);
Gallary.setTextColor(Color.parseColor("#a0a0a0"));
tv_done.setVisibility(View.VISIBLE);
tv_done.setTextColor(Color.parseColor("#ff0000"));
tv_done.setText(progressModel.getFailMessage());
btnSelectPix.setEnabled(true);
Toast.makeText(context, progressModel.getFailMessage(), Toast.LENGTH_SHORT).show();
}
private void adforest_UploadSuccessImage() {
progress_bar.setVisibility(View.GONE);
Gallary.setVisibility(View.VISIBLE);
loadingLayout.setVisibility(View.GONE);
Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_green_24dp, 0, 0, 0);
Gallary.setText(totalFiles + "");
tv_done.setText(progressModel.getSuccessMessage());
Toast.makeText(context, progressModel.getSuccessMessage(), Toast.LENGTH_SHORT).show();
btnSelectPix.setEnabled(true);
tv_done.setTextColor(Color.parseColor("#20a406"));
}
private MultipartBody.Part adforestst_prepareFilePart(String fileName, Uri fileUri) {
File finalFile = new File(SettingsMain.getRealPathFromURI(context, fileUri));
allFile.add(finalFile);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
finalFile
);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(fileName, finalFile.getName(), requestFile);
}
private File adforest_rotateImage(String path) {
File file = null;
Bitmap bitmap = BitmapFactory.decodeFile(path);
ExifInterface ei = null;
try {
ei = new ExifInterface(path);
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap rotatedBitmap = null;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = bitmap;
}
file = new File(getRealPathFromURI(getImageUri(rotatedBitmap)));
allFile.add(file);
return file;
}
public Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private class AsyncImageTask extends AsyncTask<ArrayList<String>, Void, List<MultipartBody.Part>> {
ArrayList<String> imaagesLis = null;
boolean checkDimensions = true, checkImageSize;
#SafeVarargs
#Override
protected final List<MultipartBody.Part> doInBackground(ArrayList<String>... params) {
List<MultipartBody.Part> parts = null;
imaagesLis = params[0];
totalFiles = imaagesLis.size();
for (int i = 0; i < imaagesLis.size(); i++) {
parts = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
Log.d("info image", currentDateandTime);
checkDimensions = true;
checkImageSize = true;
if (adPostImageModel.getDim_is_show()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imaagesLis.get(i), options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
if (imageHeight > Integer.parseInt(adPostImageModel.getDim_height()) &&
imageWidth > Integer.parseInt(adPostImageModel.getDim_width())) {
checkDimensions = true;
} else {
checkDimensions = false;
runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getDim_height_message(), Toast.LENGTH_SHORT).show());
}
}
File file = new File(imaagesLis.get(i));
long fileSizeInBytes = file.length();
Integer fileSizeBytes = Math.round(fileSizeInBytes);
if (fileSizeBytes > Integer.parseInt(adPostImageModel.getImg_size())) {
checkImageSize = false;
runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getImg_message(), Toast.LENGTH_SHORT).show());
} else {
checkImageSize = true;
}
if (checkImageSize && checkDimensions) {
File finalFile1 = adforest_rotateImage(imaagesLis.get(i));
// File finalFile1 =new File(imaagesLis.get(i));
Uri tempUri = SettingsMain.decodeFile(context, finalFile1);
parts.add(adforestst_prepareFilePart("file" + i, tempUri));
adforest_uploadImages(parts);
}
}
return parts;
}
You can use this scale down function
public static Bitmap scaleDown(Bitmap your_image, float YOUR_SIZE,boolean filter) { //filter false = Pixelated, true = Smooth
float ratio = Math.min( YOUR_SIZE/ your_image.getWidth(),
YOUR_SIZE/ your_image.getHeight());
int width = Math.round( ratio * your_image.getWidth());
int height = Math.round( ratio * your_image.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(your_image, width, height,
filter);
return newBitmap;
}
You already have the mechanism for compressing in your code:
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
See the documentation:
https://developer.android.com/reference/android/graphics/Bitmap.html#public-methods_1
Basically you need to change 100 to a lower number in order to compress the image.

How to make custom camera layout in Android?

I am trying to develop some kind of OCR application with Text Recognizing feature. I wrote and found some codes which is working properly but my problem is I want make some customization in the camera layout. I want to add my own capture button and add a frame. I actually did it on a different project with "surface view/holder". But I cannot implement my project because it works so differently.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private Uri imageUri;
private TextView detectedTextView; // layouttaki text view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() { // galeriden resim seçme işlemi
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // resim çekme işlemi
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
detectedTextView = (TextView) findViewById(R.id.detected_text);
detectedTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void inspectFromBitmap(Bitmap bitmap) { //kendisine gelen bitmap resimden inspect yapar
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
try {
if (!textRecognizer.isOperational()) {
new AlertDialog.
Builder(this).
setMessage("Text recognizer could not be set up on your device").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
List<TextBlock> textBlocks = new ArrayList<>();
for (int i = 0; i < origTextBlocks.size(); i++) {
TextBlock textBlock = origTextBlocks.valueAt(i);
textBlocks.add(textBlock);
}
Collections.sort(textBlocks, new Comparator<TextBlock>() {
#Override
public int compare(TextBlock o1, TextBlock o2) {
int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
if (diffOfTops != 0) {
return diffOfTops;
}
return diffOfLefts;
}
});
StringBuilder detectedText = new StringBuilder();
for (TextBlock textBlock : textBlocks) {
if (textBlock != null && textBlock.getValue() != null) {
detectedText.append(textBlock.getValue());
detectedText.append("\n");
}
}
detectedTextView.setText(detectedText); // detectedText is a final string
}
finally {
textRecognizer.release();
}
}
private void inspect(Uri uri) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 2;
options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
bitmap = BitmapFactory.decodeStream(is, null, options);
Bitmap rotatedMap = RotateBitmap(bitmap,90);
inspectFromBitmap(rotatedMap);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to find the file: " + uri, e);
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(TAG, "Failed to close InputStream", e);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public static Bitmap RotateBitmap(Bitmap source, float angle) // it rotates the bitmap for given parameter
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
In that case, what should I do ? Thank you guys.
No, you cannot change the layout of the camera app that fulfills ACTION_IMAGE_CAPTURE intent. Actually, different devices will not have same camera apps. Each may have very different look-and-feel. You need a 'custom camera' to control its layout and UX.

POST base64 image using okHTTP, not getting any result

Edit: Ok, this is my last attempt at this, new code same result. I get a image in the ImageView but no sign of any return-string from the server.
This is what the server expects to get (The image can be url or base64 encoded image):
POST /detect HTTP/1.1
Content-Type: application/json
app_id: 4985f625
app_key: aa9e5d2ec3b00306b2d9588c3a25d68e
{
"image":" http://media.kairos.com/kairos-elizabeth.jpg ",
"selector":"ROLL"
}
And this is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
EncodeToBase64 encode = new EncodeToBase64();
String lastPhotoAsBase64;
ImageView mImageView;
String path = Environment.getExternalStorageDirectory().toString() + "/files/Pictures";
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
String mTestPath = "/storage/emulated/0/Android/data/com.example.cliff.camera2/files/Pictures/JPEG_20171209_174301_1623885500.jpg";
String jsonResult;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
Button cameraButton = findViewById(R.id.cameraButton);
textView = findViewById(R.id.textView);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
setPic();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
public void setPic() throws IOException {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
//BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
ExifInterface exif = new ExifInterface(mCurrentPhotoPath);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
//int deg = rotationInDegrees;
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
lastPhotoAsBase64 = encode.encode(bitmap);
if(lastPhotoAsBase64 != null) {
new postData().execute(lastPhotoAsBase64);
}
else{
Toast.makeText(MainActivity.this,"No base64 data found!",Toast.LENGTH_LONG).show();
}
mImageView.setImageBitmap(bitmap);
}
public void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 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 = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
public class postData extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
HttpConnectionActivity hh = new HttpConnectionActivity();
String temp = hh.HttpConnection(strings[0]);
textView.setText(temp);
textView.setVisibility(View.VISIBLE);
return null;
}
}
}
HttpConnectionActivity.java
public class HttpConnectionActivity {
private final static String KAIROS_URL = "https://api.kairos.com/detect";
private final String KEY = "5232cdde7e35d8de7ac78726060d5a01";
private final String ID = "9bd755a1";
String serverResponse;
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
JSONObject postdata = new JSONObject();
public String HttpConnection(String image) {
OkHttpClient client = new OkHttpClient();
try {
postdata.put("image", image);
RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());
final Request request = new Request.Builder()
.url(KAIROS_URL)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("app_id", ID)
.addHeader("app_key", KEY)
.build();
Response response = client.newCall(request).execute();
serverResponse = response.body().string();
} catch (Exception ex) {
ex.getMessage();
}
return serverResponse;
}
}
EncodeToBase64.java
public class EncodeToBase64 {
public String encode(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
}
OnCustomEventListener.java
public interface OnCustomEventListener {
public void onEvent();
}

Upload photo from gallery not work

Hi all when i try to select an image profile if i try to upload a photo from camera all works good, but if i upload a photo from gallery i not show anything. The function for opening the gallery and select the photo works but after selected the photo she should appear but not appear anything.
Hope you help me. Thank you.
Here is the code :
public class UpdateProfileActivity extends AppCompatActivity {
Toolbar toolbar;
ImageView imgProfile;
Button btnSaveProfile,btnMyadd;
EditText edtName,edtEmail,edtNumber,edtWebsite;
TextView txtname,txtEmail,txtNumber,txtWebsite;
ProgressDialog progressBar;
String name,email,number,website;
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
File file;
boolean isphotoselected = false;
private SharedPreferences pref;
Typeface typeface;
String advertId,advertUserName,advertPassword,advertEmail,advertPhone,advertSite,advertImage;
boolean AddFlag= false;
MarshMallowPermission marshMallowPermission;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_updateprofile);
toolbar = (Toolbar) findViewById(R.id.toolbar);
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
if (toolbar != null) {
toolbar.setTitle("Profile Update");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
marshMallowPermission = new MarshMallowPermission(this);
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
}
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
}
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
}
imgProfile = (ImageView)findViewById(R.id.imgProfile);
btnMyadd = (Button)findViewById(R.id.btnMyadd);
btnSaveProfile=(Button)findViewById(R.id.btnSaveprofile);
edtEmail = (EditText)findViewById(R.id.edtEmailid);
edtName = (EditText)findViewById(R.id.edtName);
edtNumber = (EditText)findViewById(R.id.edtphone);
edtWebsite= (EditText)findViewById(R.id.edtwebsite);
txtEmail = (TextView)findViewById(R.id.txtEmail);
txtname = (TextView)findViewById(R.id.txtName);
txtNumber = (TextView)findViewById(R.id.txtPhone);
txtWebsite= (TextView)findViewById(R.id.txtWeb);
btnMyadd.setTypeface(typeface);
btnSaveProfile.setTypeface(typeface);
edtEmail.setTypeface(typeface);
edtName.setTypeface(typeface);
edtNumber.setTypeface(typeface);
edtWebsite.setTypeface(typeface);
txtEmail.setTypeface(typeface);
txtname.setTypeface(typeface);
txtNumber.setTypeface(typeface);
txtWebsite.setTypeface(typeface);
pref = getSharedPreferences("loginpreference", MODE_PRIVATE);
imgProfile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startDialog();
}
});
btnSaveProfile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
name = edtName.getText().toString();
number = edtNumber.getText().toString();
email = edtEmail.getText().toString();
website= edtWebsite.getText().toString();
boolean flag = emailValidator(email);
if(name.equalsIgnoreCase("")){
edtName.setError("Please Enter Name");
}else if(number.equalsIgnoreCase("")){
edtNumber.setError("Please Enter Contact Number");
}else if(flag == false){
edtEmail.setError("Please Enter Email");
}else if(website.equalsIgnoreCase("")){
edtWebsite.setError("Please Enter Website");
}else if(selectedImagePath.equalsIgnoreCase("") || selectedImagePath==null){
Toast.makeText(getApplicationContext(), "Please Select Profile Picture", Toast.LENGTH_SHORT).show();
}else {
new UpdateProfileTask().execute();
}
}
});
btnMyadd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(!AddFlag){
Toast.makeText(UpdateProfileActivity.this, "Please Update Your Profile", Toast.LENGTH_SHORT).show();
}else{
AddFlag = true;
Intent intent =new Intent(UpdateProfileActivity.this, MyAdsActivity.class);
intent.putExtra("advertId", advertId);
startActivity(intent);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
public boolean emailValidator(String s)
{
return Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$").matcher(s).matches();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class UpdateProfileTask extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd= new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(UpdateProfileActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
jsonStr = uploadFile();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
cd.dismissdialog();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String responce = jsonObj.getString(Constants.LOGIN_TAG);
String msg = jsonObj.getString(Constants.REG_TAG);
if(responce.equalsIgnoreCase("success")){
JSONArray jArray = jsonObj.getJSONArray("data");
if(jArray.length()>0){
JSONObject j1 = jArray.getJSONObject(0);
advertId = j1.getString("advertId");
advertUserName = j1.getString("advertUserName");
advertPassword = j1.getString("advertPassword");
advertEmail = j1.getString("advertEmail");
advertPhone = j1.getString("advertPhone");
advertSite = j1.getString("advertSite");
advertImage = j1.getString("advertImage");
AddFlag = true;
}
Toast.makeText(UpdateProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(UpdateProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
}
edtEmail.setText("");
edtName.setText("");
edtNumber.setText("");
edtWebsite.setText("");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.WEBURL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
}
});
if(isphotoselected){
file = new File(selectedImagePath);
//entity.addPart("userfile",selectedImagePath.toString();
entity.addPart("avtar", new FileBody(file));
//entity.addPart("filesArray[]",new FileBody(file));
isphotoselected = false;
}
String advartid = pref.getString("advertId", "");
entity.addPart("action", new StringBody("updateAccount"));
entity.addPart("advertId", new StringBody(advartid));
entity.addPart("username", new StringBody(name));
entity.addPart("email", new StringBody(email));
entity.addPart("phone", new StringBody(number));
entity.addPart("site", new StringBody(website));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE)
onSelectFromGalleryResult(data);
else if (requestCode == CAPTURE_IMAGE)
onCaptureImageResult(data);
else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
}
//onCaptureFromCamera
private void onCaptureImageResult(Intent data) {
beginCrop(data.getData());
}
//onSelectFromGalleryResult()
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
beginCrop(selectedImageUri);
}
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = handleSamplingAndRotationBitmap(this, Crop.getOutput(result));
saveToInternalStorage(bitmap);
mUserProfilePhoto.setImageBitmap(readFromInternalStorage("profile.png"));
}catch (IOException e){ /* do nothing here */}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
Handle cropping in this method:
private static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage) throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
//save to internal storage
private boolean saveToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("profile.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
//read from storage
private Bitmap readFromInternalStorage(String filename){
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
return BitmapFactory.decodeStream(fi);
} catch (Exception ex) { /* do nothing here */}
return null;
}
//inside onResume
#Override
public void onResume(){
super.onResume();
Bitmap savedProfilePhoto = readFromInternalStorage("profile.png");
if (savedProfilePhoto != null){
mUserProfilePhoto.setImageBitmap(savedProfilePhoto);
}
}
private void startDialog()
{
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Upload Pictures Option");
builder.setMessage("How do you want to set your picture?");
builder.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""),PICK_IMAGE);
}
});
builder.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
builder.show();
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
Add this to build.gradle dependencies:
dependencies{
compile 'com.soundcloud.android:android-crop:1.0.1#aar'
}
Then add this to your AndroidManifest file:
<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>
Try this:
Since you have already done the selecting from your Gallery:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
}
Now, the method onSelectFromGalleryResult(data):
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
beginCrop(selectedImageUri);
}
If you are going to crop your images;
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = handleSamplingAndRotationBitmap(this, Crop.getOutput(result));
saveToInternalStorage(bitmap);
mUserProfilePhoto.setImageBitmap(readFromInternalStorage("profile.png"));
}catch (IOException e){ /* do nothing here */}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
Then if you need to rotate it automatically,
private static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage) throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
To save your image in your device internal storage:
private boolean saveToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("profile.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
To read from storage:
private Bitmap readFromInternalStorage(String filename){
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
return BitmapFactory.decodeStream(fi);
} catch (Exception ex) { /* do nothing here */}
return null;
}
To set on ImageView:
#Override
public void onResume(){
super.onResume();
Bitmap savedProfilePhoto = readFromInternalStorage("profile.png");
if (savedProfilePhoto != null){
mUserProfilePhoto.setImageBitmap(savedProfilePhoto);
}
}
To finish things up, if you want to add cropping,
Almost done here:
Add this to your dependencies (build.gradle)
dependencies{
compile 'com.soundcloud.android:android-crop:1.0.1#aar'
}
Finally, in your android manifest file, for cropping library to work, add this:
<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>
That is all you need to enable selecting image from gallery or taking photo using your camera inside your app!

GetApplicationManager giving NullPointerException Error

Below is my Camera Handler:
public class CameraHandler {
public static int IMAGE_PIC_CODE = 1000, CROP_CAMERA_REQUEST = 1001,
CROP_GALLARY_REQUEST = 1002;
private Intent imageCaptureintent;
private boolean isActivityAvailable;
Context context;
private List<ResolveInfo> cameraList;
List<Intent> cameraIntents;
Uri outputFileUri;
Intent galleryIntent;
Uri selectedImageUri;
private String cameraImageFilePath, absoluteCameraImagePath;
Bitmap bitmap;
ImageView ivPicture;
String ivPicture1 = String.valueOf(ivPicture);
public CameraHandler(Context context) {
this.context = context;
setFileUriForCameraImage();
}
public void setIvPicture(ImageView ivPicture) {
this.ivPicture = ivPicture;
}
private void setFileUriForCameraImage() {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "image.jpg";
final File sdImageMainDirectory = new File(root, fname);
absoluteCameraImagePath = sdImageMainDirectory.getAbsolutePath();
outputFileUri = Uri.fromFile(sdImageMainDirectory);
}
public String getCameraImagePath() {
return cameraImageFilePath;
}
private void getActivities() {
imageCaptureintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
PackageManager packageManager = ((Activity) context)
.getPackageManager();
this.cameraList = packageManager.queryIntentActivities(
imageCaptureintent, 0);
if (cameraList.size() > 0) {
isActivityAvailable = true;
} else {
isActivityAvailable = false;
}
}
private void fillCameraActivities() {
getActivities();
if (!isActivityAvailable) {
return;
}
cameraIntents = new ArrayList<Intent>();
for (ResolveInfo resolveInfo : cameraList) {
Intent intent = new Intent(imageCaptureintent);
intent.setPackage(resolveInfo.activityInfo.packageName);
intent.setComponent(new ComponentName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name));
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
}
private void fillGallaryIntent() {
galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_PICK);
}
public void showView() {
fillCameraActivities();
fillGallaryIntent();
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent,
"Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
((Activity) context).startActivityForResult(chooserIntent,
IMAGE_PIC_CODE);
}
private Bitmap getBitmapFromURL(String src) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(src, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 192, 256);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(src, options);
}
private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2
// and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void onResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == IMAGE_PIC_CODE) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Log.v("", "ics");
} else {
Log.v("", " not ics");
}
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action
.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH
&& action != null) {
Log.v("", "action = null");
isCamera = true;
} else {
Log.v("", "action is not null");
}
}
if (isCamera) {
selectedImageUri = outputFileUri;
onResultCameraOK();
} else {
selectedImageUri = data == null ? null : data.getData();
onResultGalleryOK();
}
}
}
if (requestCode == CROP_CAMERA_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfCamera(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
if (requestCode == CROP_GALLARY_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
resultOnCropOkOfGallary(data);
} else if (resultCode == Activity.RESULT_CANCELED) {
resultOnCroppingCancel();
}
}
}
private void doCropping(int code) {
Log.v("", this.cameraImageFilePath);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(selectedImageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
try {
((Activity) context).startActivityForResult(cropIntent, code);
} catch (Exception e) {
}
}
private void onResultCameraOK() {
this.cameraImageFilePath = absoluteCameraImagePath;
this.bitmap = getBitmapFromURL(cameraImageFilePath);
doCropping(CROP_CAMERA_REQUEST);
}
private void onResultGalleryOK() {
this.cameraImageFilePath = selectedImageUri.toString();
this.bitmap = getBitmapFromURL(getRealPathFromURI(context,
selectedImageUri));
doCropping(CROP_GALLARY_REQUEST);
}
private void resultOnCropOkOfCamera(Intent data) {
this.bitmap = data.getExtras().getParcelable("data");
Log.v("", "cameraImageFilePath on crop camera ok => "
+ cameraImageFilePath);
setImageProfile();
}
private void resultOnCropOkOfGallary(Intent data) {
Bundle extras2 = data.getExtras();
this.bitmap = extras2.getParcelable("data");
setImageProfile();
}
private void resultOnCroppingCancel() {
Log.v("", "do cropping cancel" + cameraImageFilePath);
setImageProfile();
}
private void setImageProfile() {
Log.v("", "cameraImagePath = > " + cameraImageFilePath);
if (ivPicture != null) {
if (bitmap != null) {
ivPicture.setImageBitmap(bitmap);
String ivPicture =ConDetTenthFragment.getStringImage(bitmap);
Log.d("byte code -", ivPicture);
/*Intent i = new Intent(context, ImageUpload.class);
String getrec = ivPicture;
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("moin", getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
context.startActivity(i);*/
} else {
Log.v("", "bitmap is null");
}
}
}
public String getVar1() {
return ivPicture1;
}
/*public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}*/
}
Below is my Fragment Code:
public class ConDetTenthFragment extends Fragment {
static String FileByte;
String FileName;
String resultlog;
ImageView ivProfile;
Context context = getActivity();
Button btnUpload, send;
CameraHandler cameraHandler;
private ProgressDialog pDialog;
static String abc;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.con_det_tenth_fragment, container, false);
/*TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));*/
ivProfile = (ImageView) rootView.findViewById(R.id.iv_upload);
btnUpload = (Button) rootView.findViewById(R.id.btn_upload_image);
send = (Button) rootView.findViewById(R.id.btnsend);
cameraHandler = new CameraHandler(context);
cameraHandler.setIvPicture(ivProfile);
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait");
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraHandler.showView();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new async().execute();
}
});
return rootView;
}
public static ConDetTenthFragment newInstance(String text) {
ConDetTenthFragment f = new ConDetTenthFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
public static String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
abc = encodedImage;
//encodedImage = FileByte.setText().toString();
return encodedImage;
}
// Async task to perform login operation
class async extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Get the bundle
/*Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString("moin");*/
SoapObject request = new SoapObject(namespace, method_name);
request.addProperty(parameter, abc);//add the parameters
request.addProperty(parameter2, "moin.jpeg");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//set soap version
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
// this is the actual part that will call the webservice
androidHttpTransport.call(soap_action, envelope);
// SoapPrimitive prim = (SoapPrimitive) envelope.getResponse(); // Get the SoapResult from the envelope body.
SoapObject response = (SoapObject) envelope.bodyIn;
// resultlog=prim.toString();
hideDialog();
} catch (Exception e) {
e.printStackTrace();
}
return resultlog;
}
}
/*#Override
public void onClick(View view) {
if (view == btnUpload) {
cameraHandler.showView();
}
if (view == send) {
new async().execute();
}
}*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
cameraHandler.onResult(requestCode, resultCode, data);
Log.v("", "code = > " + requestCode);
}
// this is used to show diologue
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
// this is used to hide diologue
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Below is my Log Cat:
FATAL EXCEPTION: main
Process: code.meter.securemeter.com.securemeter, PID: 10492
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.app.Activity.getPackageManager()' on a null object reference
at code.meter.securemeter.com.securemeter.helper.CameraHandler.getActivities(CameraHandler.java:72)
at code.meter.securemeter.com.securemeter.helper.CameraHandler.fillCameraActivities(CameraHandler.java:83)
at code.meter.securemeter.com.securemeter.helper.CameraHandler.showView(CameraHandler.java:106)
at code.meter.securemeter.com.securemeter.fragment.ConDetTenthFragment$1.onClick(ConDetTenthFragment.java:76)
at android.view.View.performClick(View.java:5242)
at android.widget.TextView.performClick(TextView.java:10540)
at android.view.View$PerformClick.run(View.java:21185)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6856)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Problem is happening because you are passing a null context to CameraHandler
Change your ConDetTenthFragment as follows:
public class ConDetTenthFragment extends Fragment {
Context context;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getAcitivity();
cameraHandler = new CameraHandler(context);
....
}
}
Also, I think you don't need to Cast a context to Activity.
Just call (in CameraHandler):
PackageManager packageManager = context.getPackageManager();
Issue
Basically, the issue happened because you are creating your context as follows:
public class ConDetTenthFragment extends Fragment {
Context context = getActivity();
...
}
When your Fragment is created, context = getActivity() is created also. However, at this time, your fragment is not attached yet and this way, getActivity() returns null.

Categories

Resources