public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_camera, container, false);
cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
flipCamera = view.findViewById(R.id.flipCamera);
flashCameraButton = view.findViewById(R.id.flash);
captureImage = view.findViewById(R.id.captureImage);
surfaceView = view.findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
flipCamera.setOnClickListener(this);
captureImage.setOnClickListener(this);
flashCameraButton.setOnClickListener(this);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (Camera.getNumberOfCameras() > 1) {
flipCamera.setVisibility(View.VISIBLE);
}
if (!getActivity().getBaseContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
flashCameraButton.setVisibility(View.GONE);
}
return view;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!openCamera(Camera.CameraInfo.CAMERA_FACING_BACK)) {
alertCameraDialog();
}
}
private boolean openCamera(int id) {
boolean result = false;
cameraId = id;
releaseCamera();
try {
camera = Camera.open(cameraId);
} catch (Exception e) {
e.printStackTrace();
}
if (camera != null) {
try {
setUpCamera(camera);
camera.setErrorCallback(new Camera.ErrorCallback() {
#Override
public void onError(int error, Camera camera) {
}
});
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
result = true;
} catch (IOException e) {
e.printStackTrace();
result = false;
releaseCamera();
}
}
return result;
}
private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
switch (rotation) {
case Surface.ROTATION_0:
degree = 0;
break;
case Surface.ROTATION_90:
degree = 90;
break;
case Surface.ROTATION_180:
degree = 180;
break;
case Surface.ROTATION_270:
degree = 270;
break;
default:
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// frontFacing
rotation = (info.orientation + degree) % 330;
rotation = (360 - rotation) % 360;
} else {
// Back-facing
rotation = (info.orientation - degree + 360) % 360;
}
c.setDisplayOrientation(rotation);
Camera.Parameters params = c.getParameters();
showFlashButton(params);
List<String> focusModes = params.getSupportedFlashModes();
if (focusModes != null) {
if (focusModes
.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
}
params.setRotation(rotation);
}
private void showFlashButton(Camera.Parameters params) {
boolean showFlash = (getActivity().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH) && params.getFlashMode() != null)
&& params.getSupportedFlashModes() != null
&& params.getSupportedFocusModes().size() > 1;
flashCameraButton.setVisibility(showFlash ? View.VISIBLE
: View.INVISIBLE);
}
private void releaseCamera() {
try {
if (camera != null) {
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("error", e.toString());
camera = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.flash:
flashOnButton();
break;
case R.id.flipCamera:
flipCamera();
break;
case R.id.captureImage:
takeImage();
break;
default:
break;
}
}
private void takeImage() {
camera.takePicture(null, null, new Camera.PictureCallback() {
private File imageFile;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
// convert byte array into bitmap
Bitmap loadedImage = null;
Bitmap rotatedBitmap = null;
loadedImage = BitmapFactory.decodeByteArray(data, 0, data.length);
// rotate Image
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(rotation);
rotatedBitmap = Bitmap.createBitmap(loadedImage, 0, 0,
loadedImage.getWidth(), loadedImage.getHeight(),
rotateMatrix, false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(Environment
.getExternalStorageDirectory() + "/Demo");
} else {
folder = new File(Environment
.getExternalStorageDirectory() + "/Demo");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
java.util.Date date = new java.util.Date();
imageFile = new File(folder.getAbsolutePath()
+ File.separator
+ new Timestamp(date.getTime()).toString()
+ "Image.jpg");
imageFile.createNewFile();
Toast.makeText(getActivity().getBaseContext(), "Image Saved", Toast.LENGTH_SHORT).show();
openCamera(cameraId);
} else {
Toast.makeText(getActivity().getBaseContext(), "Image Not saved", Toast.LENGTH_SHORT).show();
return;
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, imageFile.getAbsolutePath());
getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void flipCamera() {
int id = (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK ? Camera.CameraInfo.CAMERA_FACING_FRONT
: Camera.CameraInfo.CAMERA_FACING_BACK);
if (!openCamera(id)) {
alertCameraDialog();
}
}
private void alertCameraDialog() {
Toast.makeText(getActivity(), "Error to open camera", Toast.LENGTH_SHORT).show();
}
private void flashOnButton() {
if (camera != null) {
try {
Camera.Parameters param = camera.getParameters();
param.setFlashMode(!flashmode ? Camera.Parameters.FLASH_MODE_TORCH
: Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(param);
flashmode = !flashmode;
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
This is my camera fragment code. When i give permission at runtime the surfaceview does not show camera. It show camera at onResume() or on any Button click in that fragment.How to solve this issue. How to set When i click on Allow button in permission it shows camera in surface view automatically.
In onCreate set visibilty of surfaceView as INVISIBLE.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
if (checkCameraHardware(this) == false) {
showDialogForExit();
}
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.setVisibility(View.INVISIBLE);
infoTextview = (TextView) findViewById(R.id.info_text);
askForPermissions();
}
Then after attaching cameraSource to surfaceView,set visibilty of surfaceView to VISIBLE again.
surfaceView.setVisibility(View.VISIBLE);
Use this class
public class RunTimePermission extends Activity
{
private Activity activity;
private ArrayList<PermissionBean> arrayListPermission;
private String[] arrayPermissions;
private RunTimePermissionListener runTimePermissionListener;
public RunTimePermission(Activity activity)
{
this.activity = activity;
}
public class PermissionBean
{
String permission;
boolean isAccept;
}
public void requestPermission(String[] permissions, RunTimePermissionListener runTimePermissionListener)
{
this.runTimePermissionListener = runTimePermissionListener;
arrayListPermission = new ArrayList<PermissionBean>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
for (int i = 0; i < permissions.length; i++)
{
PermissionBean permissionBean = new PermissionBean();
if (ContextCompat.checkSelfPermission(activity, permissions[i]) == PackageManager.PERMISSION_GRANTED)
{
permissionBean.isAccept = true;
}
else
{
permissionBean.isAccept = false;
permissionBean.permission = permissions[i];
arrayListPermission.add(permissionBean);
}
}
if (arrayListPermission.size() <= 0)
{
runTimePermissionListener.permissionGranted();
return;
}
arrayPermissions = new String[arrayListPermission.size()];
for (int i = 0; i < arrayListPermission.size(); i++)
{
arrayPermissions[i] = arrayListPermission.get(i).permission;
}
activity.requestPermissions(arrayPermissions, 10);
}
else
{
if (runTimePermissionListener != null)
{
runTimePermissionListener.permissionGranted();
}
}
}
public interface RunTimePermissionListener
{
void permissionGranted();
void permissionDenied();
}
private void callSettingActivity()
{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivity(intent);
}
private void checkUpdate()
{
boolean isGranted = true;
int deniedCount = 0;
for (int i = 0; i < arrayListPermission.size(); i++)
{
if (!arrayListPermission.get(i).isAccept)
{
isGranted = false;
deniedCount++;
}
}
if (isGranted)
{
if (runTimePermissionListener != null)
{
runTimePermissionListener.permissionGranted();
}
}
else
{
if (runTimePermissionListener != null)
{
setAlertMessage();
runTimePermissionListener.permissionDenied();
}
}
}
public void setAlertMessage()
{
AlertDialog.Builder adb;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
adb = new AlertDialog.Builder(activity, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
adb = new AlertDialog.Builder(activity);
}
adb.setTitle(activity.getResources().getString(R.string.app_name));
String msg = "<p>Dear User, </p>" +
"<p>Seems like you have <b>\"Denied\"</b> the minimum requirement permission to access more features of application.</p>" +
"<p>You must have to <b>\"Allow\"</b> all permission. We will not share your data with anyone else.</p>" +
"<p>Do you want to enable all requirement permission ?</p>" +
"<p>Go To : Settings >> App > " + activity.getResources().getString(R.string.app_name) + " Permission : Allow ALL</p>";
adb.setMessage(Html.fromHtml(msg));
adb.setPositiveButton("Allow All", new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
callSettingActivity();
dialog.dismiss();
}
});
adb.setNegativeButton("Remind Me Later", new AlertDialog.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
if (!((Activity) activity).isFinishing() && msg.length() > 0)
{
adb.show();
}
else
{
Log.v("log_tag", "either activity finish or message length is 0");
}
}
private void updatePermissionResult(String permissions, int grantResults)
{
for (int i = 0; i < arrayListPermission.size(); i++)
{
if (arrayListPermission.get(i).permission.equals(permissions))
{
if (grantResults == 0)
{
arrayListPermission.get(i).isAccept = true;
}
else
{
arrayListPermission.get(i).isAccept = false;
}
break;
}
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
for (int i = 0; i < permissions.length; i++)
{
updatePermissionResult(permissions[i], grantResults[i]);
}
checkUpdate();
}
}
Write this code in your activity onCreate() Method
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
runTimePermission = new RunTimePermission(this);
runTimePermission.requestPermission(new String[]{Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, new RunTimePermission.RunTimePermissionListener() {
#Override
public void permissionGranted() {
// First we need to check availability of play services
initControls();
identifyOrientationEvents();
//create a folder to get image
folder = new File(Environment.getExternalStorageDirectory() + "/Media");
if (!folder.exists()) {
folder.mkdirs();
}
//capture image on callback
captureImageCallback();
//
if (camera != null) {
Camera.CameraInfo info = new Camera.CameraInfo();
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
imgFlashOnOff.setVisibility(View.GONE);
}
}
}
#Override
public void permissionDenied() {
}
});
then write this code out of onCreate()
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (runTimePermission != null) {
runTimePermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
Sorry for late answer, but maybe it will be useful to someone. Just call start camera method in your onRequestPermissionsResult like this:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Utils.log(TAG, "onRequestPermissionsResult call");
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Utils.log(TAG, "Permission granted - show camera");
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The default way to show camera might look like this:
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSource.start(surfaceView.getHolder());
Utils.log(TAG, "Check permission: granted - start camera");
} else {
Utils.log(TAG, "Check permission: restricted - request");
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
It worked for me:
before get permission or show any dialogs set surface visibility to GONE
surfaceView.setVisibility(View.GONE);
then after get permission or dismiss dialogs set surface visibility to VISIBLE
surfaceView.setVisibility(View.VISIBLE);
you have to receive your permission details here
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Here call or Open your camera;
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
for more information :
link 1: https://developer.android.com/training/permissions/requesting.html
link 2: https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
for (int result : grantResults) {
if (result == PackageManager.PERMISSION_GRANTED) {
surfaceView.setVisibility(View.VISIBLE); // <----there u go
return;
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
CODE_REQUESTED_1);
}
}
}
}
}
Related
I am using a library implementation com.github.iamutkarshtiwari:Ananas:1.2.3. Everything is working fine but I am facing two errors sourceImagePath, outputFilePath. How can I solve it and remove log e and use camera to run app?
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_PERMISSON_SORAGE = 1;
public static final int REQUEST_PERMISSON_CAMERA = 2;
public static final int SELECT_GALLERY_IMAGE_CODE = 7;
public static final int TAKE_PHOTO_CODE = 8;
public static final int ACTION_REQUEST_EDITIMAGE = 9;
private ImageView imgView;
private Bitmap mainBitmap;
private Dialog loadingDialog;
private int imageWidth, imageHeight;
private String path;
private Uri photoURI = null;
private final int PHOTO_EDITOR_REQUEST_CODE = 123;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private Object BaseActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
#Override
protected void onPause() {
compositeDisposable.clear();
super.onPause();
}
#Override
protected void onDestroy() {
compositeDisposable.dispose();
super.onDestroy();
}
private void initView() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
imageWidth = metrics.widthPixels;
imageHeight = metrics.heightPixels;
imgView = findViewById(R.id.img);
View selectAlbum = findViewById(R.id.select_album);
View editImage = findViewById(R.id.edit_image);
selectAlbum.setOnClickListener(this);
editImage.setOnClickListener(this);
View takenPhoto = findViewById(R.id.take_photo);
takenPhoto.setOnClickListener(this);
loadingDialog = BaseActivity.getLoadingDialog(this, R.string.iamutkarshtiwari_github_io_ananas_loading,
false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_photo:
takePhotoClick();
break;
case R.id.edit_image:
editImageClick();
break;
case R.id.select_album:
selectFromAblum();
break;
}
}
protected void takePhotoClick() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
requestTakePhotoPermissions();
} else {
launchCamera();
}
}
private void requestTakePhotoPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_CAMERA);
return;
}
launchCamera();
}
public void launchCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
Uri outputFileUri = Uri.fromFile(FileUtils.genEditFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
} else {
File file = FileUtils.genEditFile();
Uri photoUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getApplicationContext().getPackageManager()) != null) {
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
}
Facing Problem Here
private void editImageClick() {
File outputFile = FileUtils.genEditFile();
try {
Intent intent = new ImageEditorIntentBuilder(this, sourceImagePath, outputFilePath)
.withAddText() // Add the features you need
.withPaintFeature()
.withFilterFeature()
.withRotateFeature()
.withCropFeature()
.withBrightnessFeature()
.withSaturationFeature()
.withBeautyFeature()
.withStickerFeature()
.forcePortrait(true) // Add this to force portrait mode (It's set to false by default)
.build();
EditImageActivity.start(BaseActivity, intent, PHOTO_EDITOR_REQUEST_CODE);
} catch (Exception e) {
Log.e("Demo App", e.getMessage()); // This could throw if either `sourcePath` or `outputPath` is blank or Null
}
}
private void selectFromAblum() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
openAblumWithPermissionsCheck();
} else {
openAlbum();
}
}
private void openAlbum() {
MainActivity.this.startActivityForResult(new Intent(
MainActivity.this, SelectPictureActivity.class),
SELECT_GALLERY_IMAGE_CODE);
}
private void openAblumWithPermissionsCheck() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_SORAGE);
return;
}
openAlbum();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSON_SORAGE
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else if (requestCode == REQUEST_PERMISSON_CAMERA
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchCamera();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_EDITOR_REQUEST_CODE) { // same code you used while starting
String newFilePath = data.getStringExtra(EditImageActivity.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false);
}
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_GALLERY_IMAGE_CODE:
handleSelectFromAblum(data);
break;
case TAKE_PHOTO_CODE:
handleTakePhoto();
break;
case ACTION_REQUEST_EDITIMAGE:
handleEditorImage(data);
break;
}
}
}
private void handleTakePhoto() {
if (photoURI != null) {
path = photoURI.getPath();
loadImage(path);
}
}
private void handleEditorImage(Intent data) {
String newFilePath = data.getStringExtra(ImageEditorIntentBuilder.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IS_IMAGE_EDITED, false);
if (isImageEdit) {
Toast.makeText(this, getString(R.string.save_path, newFilePath), Toast.LENGTH_LONG).show();
} else {
newFilePath = data.getStringExtra(ImageEditorIntentBuilder.SOURCE_PATH);
}
loadImage(newFilePath);
}
private void handleSelectFromAblum(Intent data) {
path = data.getStringExtra("imgPath");
loadImage(path);
}
private void loadImage(String imagePath) {
compositeDisposable.clear();
Disposable applyRotationDisposable = loadBitmapFromFile(imagePath)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscriber -> loadingDialog.show())
.doFinally(() -> loadingDialog.dismiss())
.subscribe(
this::setMainBitmap,
e -> Toast.makeText(
this, R.string.iamutkarshtiwari_github_io_ananas_load_error, Toast.LENGTH_SHORT).show()
);
compositeDisposable.add(applyRotationDisposable);
}
private void setMainBitmap(Bitmap sourceBitmap) {
if (mainBitmap != null) {
mainBitmap.recycle();
mainBitmap = null;
System.gc();
}
mainBitmap = sourceBitmap;
imgView.setImageBitmap(mainBitmap);
}
private Single<Bitmap> loadBitmapFromFile(String filePath) {
return Single.fromCallable(() ->
BitmapUtils.getSampledBitmap(
filePath,
imageWidth / 4,
imageHeight / 4
)
);
}
}
I want to show my image in imageview after click but i don't know why this error occur and i searched a lot on this but i could no find solution of this problem and i tried to implement code after see solution but it doesn't work,so i m confused what's going wrong.This is my code:
package kmsg.com.onetouch.activity;
public class UploadDocumentActivity extends AppCompatActivity {
JSONParser parser;
Bitmap photo;
ImageView mImgDocument;
Button mBtnBill,mBtnPres,mBtnGetFile,mBtnUpload;
EditText mEtBillDate,mEtbillValue,mEtStoreRefID,mEtDoctorID;
LinearLayout mBillLinear,mPresLinear;
String mBillDate,mBillValue,mStoreRefID,mDoctorID;
boolean flag= true;
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_document);
parser = new JSONParser(this);
init();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
private void init() {
mImgDocument=(ImageView)findViewById(R.id.imgDocument);
mBtnBill=(Button)findViewById(R.id.btnBill);
mBtnPres=(Button)findViewById(R.id.btnPres);
mBtnGetFile=(Button)findViewById(R.id.btnGetFile);
mBtnUpload=(Button)findViewById(R.id.btnUpload);
mEtBillDate=(EditText)findViewById(R.id.et_billDate);
mEtbillValue=(EditText)findViewById(R.id.et_billValue);
mEtStoreRefID=(EditText)findViewById(R.id.et_refID);
mEtDoctorID=(EditText)findViewById(R.id.et_doctorID);
mBillLinear=(LinearLayout)findViewById(R.id.bill_linear);
mPresLinear=(LinearLayout)findViewById(R.id.prescription_linear);
}
public void getBill(View view) {
flag= true;
mPresLinear.setVisibility(View.GONE);
mBillLinear.setVisibility(View.VISIBLE);
}
public void getPrescription(View view) {
flag=false;
mBillLinear.setVisibility(View.GONE);
mPresLinear.setVisibility(View.VISIBLE);
}
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureNm = getPictureName();
imageFile = new File(pictureDirectory , pictureNm);
Uri pictureUri = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
/* public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CAMERA_REQUEST);
}
}
*/
private String getPictureName(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "paymentProof" + timestamp + ".jpg";
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_CANCELED){
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImgDocument.setImageBitmap(photo);
}
}
}
private boolean validateFormForBill() {
mBillDate = mEtBillDate.getText().toString().trim();
mBillValue = mEtbillValue.getText().toString().trim();
mStoreRefID = mEtStoreRefID.getText().toString().trim();
mEtBillDate.setError(null);
mEtbillValue.setError(null);
mEtStoreRefID.setError(null);
if (TextUtils.isEmpty(mBillDate.trim())) {
mEtBillDate.setError("Bill Date cannot be blank");
return false;
}
if (TextUtils.isEmpty(mBillValue.trim())) {
mEtbillValue.setError("Bill Value cannot be blank");
return false;
}
if (TextUtils.isEmpty(mStoreRefID.trim())) {
mEtStoreRefID.setError("Ref ID cannot be blank");
return false;
}
return true;
}
private boolean validateFormForPres() {
mDoctorID = mEtDoctorID.getText().toString().trim();
mEtDoctorID.setError(null);
if (TextUtils.isEmpty(mDoctorID.trim())) {
mEtDoctorID.setError("Doctor ID cannot be blank");
return false;
}
return true;
}
public void uploadDocument(View view) {
if (UtilityServices.checkInternetConnection(UploadDocumentActivity.this)) {
if (flag) {
if (UploadDocumentActivity.this.validateFormForBill()) {
new UploadBill().execute();
}
} else {
if (UploadDocumentActivity.this.validateFormForPres()) {
// new UploadPres().execute();
}
}
}else {
Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
}
}
private class UploadBill extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("billAmt", mBillValue));
partList.add(new StringPart("billDate", mBillDate));
partList.add(new StringPart("storeId", mStoreRefID));
System.out.println("Data"+mBillDate+mBillValue+mStoreRefID);
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")));
/* try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
String url = Constants.UPLOAD_BILL;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
private class UploadPres extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("storeId", mDoctorID));
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")+""));
try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String url = Constants.UPLOAD_PRESCRIPTION;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
}
This is my class and i am trying to capture an image on click a button and then save into directory after that show into imageview and then want to send to server,i hope you will help me as a best programmer.
this question may be a duplicate of this.
Basically, when you pass an OutPut file to the intent, you cannot read data from extra, you have to make sure that CameraApplication has access to your files. You are getting this exception, because CameraApplication cannot save the file on your directory, you need to add a file provider...
Please make your code is same as the base android documentation.
Try This
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
I've written an application which should take picture and record video and then show it on the screen. When trying it on phone the camera won't work but works in emulator.
When executing the app this is what exactly happens:
Every time I clicked on the button to open the camera, the app stopped and the error it display is Appname has stopped, Open app again
When I clicked on Open app again it return to normal state
I have granted the camera permission in my program
below is my code:
public class EventActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
public static final String KEY_MENU_TYPE = "menutype";
//public static final String KEY_PREF_USER_DETAILS = "prefUserDetails";
private static final String TAG = EventActivity.class.getSimpleName();
private static final String SERVER_IMAGE_PATH = "http://edo.com/imageupload/";
private static final String SERVER_PATH = "http://edo.com/";
String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private EditText event, eventDescription, name;
private TextView attachmentStatus;
private static final int TAKE_PICTURE = 1;
private static final int PERMISSION_ALL = 3;
private Uri capturedImageUri;
private Uri videoUri;
private String mediaFile;
private String videoFile;
private static final int MY_SOCKET_TIMEOUT_MS = 5000;
private String[] serverData;
private static final int REQUEST_VIDEO_CAPTURE = 300;
private boolean isImage;
private String locationResult;
String menutype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
Intent intent = getIntent();
/* ActionBar mBar = getSupportActionBar();
if(mBar != null){
mBar.setDisplayHomeAsUpEnabled(true);
}*/
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = createLocationRequest();
Button photoVideoButton = (Button)findViewById(R.id.take_image_video);
photoVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showOptionDialog();
}
});
attachmentStatus = (TextView)findViewById(R.id.file_status);
event = (EditText)findViewById(R.id.enter_event);
eventDescription =(EditText)findViewById(R.id.enter_event_description);
name = (EditText)findViewById(R.id.name);
Button cancelUploadButton = (Button) findViewById(R.id.cancel_upload);
assert cancelUploadButton != null;
cancelUploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resetViewControls();
}
});
Button sendToServerButton = (Button) findViewById(R.id.send_to_server);
assert sendToServerButton != null;
sendToServerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String eventValue = event.getText().toString().trim();
String eventDescriptionValue = eventDescription.getText().toString();
String nameValue = name.getText().toString();
String locationValue = "";
if(TextUtils.isEmpty(eventValue) || TextUtils.isEmpty(eventDescriptionValue) || TextUtils.isEmpty(nameValue)){
Toast.makeText(EventActivity.this, getString(R.string.send_to_server_error), Toast.LENGTH_LONG).show();
return;
}
if(locationResult == null || locationResult.equals("")){
locationValue = "";
}else{
locationValue = locationResult;
}
if(TextUtils.isEmpty(mediaFile) && TextUtils.isEmpty(videoFile)){
Toast.makeText(EventActivity.this, "Please attach a photo or video", Toast.LENGTH_LONG).show();
return;
}
if(!TextUtils.isEmpty(mediaFile) && isImage){
// send the information to remote server
Bitmap storeBitmap = BitmapFactory.decodeFile(mediaFile);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(storeBitmap, 640, 420, true);
String imageBasedString = convertBitmapToBaseImageString(resizedBitmap);
serverData = new String[]{eventValue, eventDescriptionValue, nameValue, imageBasedString, locationValue};
sendCapturedImageToServer(serverData);
//move stored video to a new folder
String photoPath = getMovedFilePath(mediaFile, eventValue);
moveFileToNewDestination(mediaFile, photoPath);
}else if(!TextUtils.isEmpty(mediaFile) && !isImage){
//Store the video to your server
uploadVideoToServer(videoFile, eventValue, eventDescriptionValue, nameValue, locationValue);
//move stored video to a new folder
String photoPath = getMovedFilePath(videoFile, eventValue);
moveFileToNewDestination(videoFile, photoPath);
}else{
// Image or video is missing. Show message to user
Toast.makeText(EventActivity.this, getString(R.string.upload_image_or_video), Toast.LENGTH_LONG).show();
}
}
});
this.menutype = intent.getStringExtra(KEY_MENU_TYPE);
if (this.menutype == null) {
this.menutype = "";
}
}
public void goBack(View view) {
Intent intent;
if (this.menutype.equals("PRE")) {
intent = new Intent(this, PreElectionMenuActivity.class);
} else if (this.menutype.equals("ACC")) {
intent = new Intent(this, AccreditationMenuActivity.class);
} else if (this.menutype.equals("ELE")) {
intent = new Intent(this, VotingMenuActivity.class);
} else if (this.menutype.equals("INC")) {
intent = new Intent(this, IncidentMenuActivity.class);
} else {
intent = new Intent(this, HomeActivity.class);
}
startActivity(intent);
}
private String getMovedFilePath(String filePath, String eventName){
int indexPosition = filePath.lastIndexOf(".");
String fileExtension = filePath.substring(indexPosition, filePath.length());
String newFilename = eventName + fileExtension;
return getFileDestinationPath(newFilename);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == TAKE_PICTURE) {
capturedImageUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = "";
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
Log.d(TAG, "Capture image path" + mediaFile);
attachmentStatus.setText("Image file has been attached");
isImage = true;
}
}
if (requestCode == REQUEST_VIDEO_CAPTURE) {
videoUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else{
videoFile = getRealPathFromURIPath(videoUri, EventActivity.this);
Log.d(TAG, "Captured video path " + videoUri);
Log.d(TAG, "New path " + videoFile);
attachmentStatus.setText("Video file has been attached");
isImage = false;
}
}
}
}
private void resetViewControls(){
event.setText("");
eventDescription.setText("");
name.setText("");
attachmentStatus.setText(R.string.attached_file);
}
#Override
protected void onResume() {
super.onResume();
if(capturedImageUri != null){
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
}
}
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
private String convertBitmapToBaseImageString(Bitmap bitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
return Base64.encodeToString(byte_arr, 0);
}
private void sendCapturedImageToServer(String[] photoDetails){
Map<String, String> params = new HashMap<String,String>();
params.put("EVENT", photoDetails[0]);
params.put("EVENT_DESCRIPTION", photoDetails[1]);
params.put("NAME", photoDetails[2]);
params.put("CAPTURE_IMAGE", photoDetails[3]);
params.put("EVENT_LOCATION", photoDetails[4]);
GsonRequest<ServerObject> serverRequest = new GsonRequest<ServerObject>(
Request.Method.POST,
SERVER_IMAGE_PATH,
ServerObject.class,
params,
createRequestSuccessListener(),
createRequestErrorListener());
serverRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(EventActivity.this).addToRequestQueue(serverRequest);
}
private Response.Listener<ServerObject> createRequestSuccessListener() {
return new Response.Listener<ServerObject>() {
#Override
public void onResponse(ServerObject response) {
try {
Log.d(TAG, "Json Response " + response.getSuccess());
if(!TextUtils.isEmpty(response.getSuccess()) && response.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
};
};
}
private Response.ErrorListener createRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
public static void getAddressFromLocation(final double lat, final double lon, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(lat, lon, 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality() + ", " + address.getCountryName() ;
Log.d(TAG, "The converted Address " + result);
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to GeoCoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
#SuppressLint("HandlerLeak")
private class GeoCoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationResult = bundle.getString("address");
Log.d(TAG, "Location Result " + locationResult);
break;
default:
locationResult = null;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.d(TAG, "Connection method has been called");
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
else{
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
getAddressFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), EventActivity.this, new GeoCoderHandler());
}
}
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_ALL: {
// If request is cancelled, the result arrays are empty.
if(grantResults[0] == PackageManager.PERMISSION_DENIED){
Toast.makeText(EventActivity.this, "Sorry!!!, you can't use this app without granting this permission", Toast.LENGTH_LONG).show();
finish();
}
if (grantResults[1] == PackageManager.PERMISSION_DENIED || grantResults[2] == PackageManager.PERMISSION_DENIED) {
// permission was denied, show alert to explain permission
showPermissionAlert();
}else{
//permission is granted. Get current location values
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
}
}
}
}
private void showPermissionAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permission_request_title);
builder.setMessage(R.string.app_permission_notice);
builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(EventActivity.this, R.string.permission_refused, Toast.LENGTH_LONG).show();
}
});
builder.show();
}
protected LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private boolean isLocationEnabled(){
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
return false;
}
return true;
}
private void showLocationAlert(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_enable));
dialog.setPositiveButton(getResources().getString(R.string.network_location), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
EventActivity.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private void moveFileToNewDestination(String fromPath, String toPath){
File fromFile = new File(fromPath);
File toFile = new File(toPath);
if(!toFile.exists()){
try {
toFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fromStream = null;
FileOutputStream toStream = null;
try {
fromStream = new FileInputStream(fromFile);
toStream = new FileOutputStream(toFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] sourceByte = new byte[1024];
int index;
try {
while((index = fromStream.read(sourceByte)) > 0){
if (toStream != null) {
toStream.write(sourceByte, 0, index);
}
}
Log.d(TAG, "Video successfully moved to a new location");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getFileDestinationPath(String filename){
String filePathEnvironment = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
File directoryFolder = new File(filePathEnvironment + "/events/");
if(!directoryFolder.exists()){
directoryFolder.mkdir();
}
Log.d(TAG, "Full path " + filePathEnvironment + "/events/" + filename);
return filePathEnvironment + "/events/" + filename;
}
private void uploadVideoToServer(String pathToVideoFile, String eventName, String eventDescription, String eventCoverage, String eventLocation){
File videoFile = new File(pathToVideoFile);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
RequestBody event = RequestBody.create(MediaType.parse("text/plain"), eventName);
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), eventDescription);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), eventCoverage);
RequestBody location = RequestBody.create(MediaType.parse("text/plain"), eventLocation);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create())
.build();
VideoInterface vInterface = retrofit.create(VideoInterface.class);
Call<ResultObject> serverCom = vInterface.uploadVideoToServer(vFile, event, description, name, location);
serverCom.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
ResultObject result = response.body();
if(!TextUtils.isEmpty(result.getSuccess()) && result.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
Log.d(TAG, "Error message " + t.getMessage());
}
});
}
private void showOptionDialog(){
final Dialog dialog = new Dialog(EventActivity.this);
dialog.setTitle("SELECT ACTION TO COMPLETE");
dialog.setContentView(R.layout.image_video_layout);
final TextView takePhoto = (TextView)dialog.findViewById(R.id.take_photo);
final TextView recordVideo = (TextView)dialog.findViewById(R.id.record_video);
dialog.show();
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Take a picture");
if(isLocationEnabled()){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}else{
showLocationAlert();
}
dialog.dismiss();
}
});
recordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Record a video");
Intent videoCaptureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(videoCaptureIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(videoCaptureIntent, REQUEST_VIDEO_CAPTURE);
}
dialog.dismiss();
}
});
}
private boolean gps_enabled;
private boolean network_enabled;
Im getting this error, when click deny permission in "Allow app to access photos, media and files on your device ? "
FATAL EXCEPTION: main
Process: com.viantti.app, PID: 12349
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
java error line,
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
When user denies the authorization, you cannot access the media files, you should use this code only if the authorization is accepted
Try the following code, since it will proceed only when all the required permissions has been allowed by the user.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
chooseimage();
} else {
finish();
}
break;
}
}
At first read about Android Runtime Permissions here .
If you deny your app from accessing media you won't be able to take photos.
java code here,
Img_profile_pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (!checkAccessFineLocationPermission() || !checkWriteExternalStoragePermission()) {
requestPermission();
} else {
chooseimage();
}
} else {
chooseimage();
}
}
});
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera_FileUri = getOutputMediaFileUri(1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, camera_FileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, galleryRequestCode);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", camera_FileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
camera_FileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == UCrop.REQUEST_CROP) {
try {
if (requestCode == REQUEST_TAKE_PHOTO) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(camera_FileUri.getPath(), options);
Bitmap thumbnail = bitmap;
final String picturePath = camera_FileUri.getPath();
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File curFile = new File(picturePath);
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
// thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
} catch (IOException ex) {
Log.e("TAG", "Failed to get Exif data", ex);
}
System.out.println("edit-----" + Iconstant.Edit_profile_image_url);
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == galleryRequestCode) {
Uri selectedImage = data.getData();
if (selectedImage.toString().startsWith("content://com.sec.android.gallery3d.provider")) {
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
final String picturePath = c.getString(columnIndex);
c.close();
File curFile = new File(picturePath);
Picasso.with(ProfilePage.this).load(picturePath).resize(100, 100).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Bitmap thumbnail = bitmap;
mSelectedFilePath = picturePath;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
} else {
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
final String picturePath = c.getString(columnIndex);
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap thumbnail = bitmap; //getResizedBitmap(bitmap, 600);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File curFile = new File(picturePath);
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
} catch (IOException ex) {
Log.e("TAG", "Failed to get Exif data", ex);
}
thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
c.close();
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
}
}
if ( requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
try {
selectedBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
Img_profile_pic.setImageBitmap(selectedBitmap);
Img_profile_pic.setImageURI(resultUri);
UploadDriverImage(Iconstant.Edit_profile_image_url);
} else if (resultCode == UCrop.RESULT_ERROR) {
final Throwable cropError = UCrop.getError(data);
System.out.println("========muruga cropError==========="+cropError);
}
}
}
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;
}
private void UploadDriverImage(String url) {
dialog = new Dialog(ProfilePage.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loading);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
TextView dialog_title = (TextView) dialog.findViewById(R.id.custom_loading_textview);
dialog_title.setText(getResources().getString(R.string.action_loading));
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
System.out.println("------------- image response-----------------"+response.data);
String resultResponse = new String(response.data);
System.out.println("------------- response-----------------"+resultResponse);
String sStatus = "", sResponse = "",SUser_image="",Smsg="";
try {
JSONObject jsonObject = new JSONObject(resultResponse);
sStatus = jsonObject.getString("status");
if (sStatus.equalsIgnoreCase("1")) {
// JSONObject responseObject = jsonObject.getJSONObject("response");
// SUser_image = jsonObject.getString("image");
Smsg = jsonObject.getString("image_url");
// Img_profile_pic.setImageBitmap(bitMapThumbnail);
session.setuser_image(Smsg);
Picasso.with(ProfilePage.this).load(Smsg).placeholder(R.drawable.no_user_image).into(Img_profile_pic);
NavigationDrawer.navigationNotifyChange();
Locale locale = null;
switch (language_code){
case "en":
locale = new Locale("en");
session.setlamguage("en","en");
break;
case "es":
locale = new Locale("es");
session.setlamguage("es","es");
// session.setlamguage("Ar",language_change.getSelectedItem().toString());
// System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
// Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
// finish();
// startActivity(i);
// Intent bii = new Intent();
// bii.setAction("homepage");
// sendBroadcast(bii);
// finish();
break;
case "ta":
locale = new Locale("ta");
session.setlamguage("ta","ta");
// session.setlamguage("Ar",language_change.getSelectedItem().toString());
// System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
// Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
// finish();
// startActivity(i);
// Intent bii = new Intent();
// bii.setAction("homepage");
// sendBroadcast(bii);
// finish();
break;
default:
locale = new Locale("en");
session.setlamguage("en","en");
break;
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());
Alert(getResources().getString(R.string.action_success),getResources().getString(R.string.edit_profile_success_label));
} else {
sResponse = jsonObject.getString("response");
Alert(getResources().getString(R.string.my_rides_rating_header_sorry_textview), sResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
Toast.makeText(ProfilePage.this,"Something happened , try again",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message + " Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message + " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message + " Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
System.out.println("------------Authkey------cabily---------" + Agent_Name);
System.out.println("------------userid----------cabily-----" + UserID);
System.out.println("------------apptoken----------cabily-----" + gcmID);
System.out.println("------------applanguage----------cabily-----" + language_code);
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authkey", Agent_Name);
headers.put("isapplication",Iconstant.cabily_IsApplication);
headers.put("applanguage",language_code);
headers.put("apptype", Iconstant.cabily_AppType);
headers.put("userid",UserID);
headers.put("apptoken",gcmID);
/* System.out.println("servicereques apptype------------------"+Iconstant.cabily_AppType);
System.out.println("servicereques apptoken------------------"+gcmID);
System.out.println("servicereques userid------------------"+UserID);
Map<String, String> headers = new HashMap<String, String>();
headers.put("User-agent",Iconstant.cabily_userAgent);
headers.put("isapplication",Iconstant.cabily_IsApplication);
headers.put("applanguage",Iconstant.cabily_AppLanguage);
headers.put("apptype",Iconstant.cabily_AppType);
headers.put("apptoken",gcmID);
headers.put("userid",UserID);*/
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("user_id",UserID);
System.out.println("user_id---------------"+UserID);
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
params.put("user_image",new DataPart("cabily_user.jpg", byteArray));
System.out.println("user_image--------edit------"+byteArray);
return params;
}
};
//to avoid repeat request Multiple Time
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
multipartRequest.setRetryPolicy(retryPolicy);
multipartRequest.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
multipartRequest.setShouldCache(false);
AppController.getInstance().addToRequestQueue(multipartRequest);
}
// --------------------Method for choose image to edit profileimage--------------------
private void chooseimage() {
photo_dialog = new Dialog(ProfilePage.this);
photo_dialog.getWindow();
photo_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
photo_dialog.setContentView(R.layout.image_upload_dialog);
photo_dialog.setCanceledOnTouchOutside(true);
photo_dialog.getWindow().getAttributes().windowAnimations = R.style.Animations_photo_Picker;
photo_dialog.show();
photo_dialog.getWindow().setGravity(Gravity.CENTER);
RelativeLayout camera = (RelativeLayout) photo_dialog
.findViewById(R.id.profilelayout_takephotofromcamera);
RelativeLayout gallery = (RelativeLayout) photo_dialog
.findViewById(R.id.profilelayout_takephotofromgallery);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePicture();
photo_dialog.dismiss();
}
});
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
photo_dialog.dismiss();
}
});
}
private boolean checkAccessFineLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkAccessCoarseLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkWriteExternalStoragePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED || grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
chooseimage();
} else {
finish();
}
break;
}
}
Hi I am new for android and in my app I am using Z-bar library for scanning barcode.
For this I am using ZbarScannerActivity class like below, so after scanning the barcode I am getting those barcode results where ever I want using onActivityResult method.
Here my problem is when I am scanning the barcode I want to get this result in my Fragment, but here onActivityResult not calling in my Fragment.
But it's calling in my Activities please help me.
How can I solve this problem?
ZbarScanner Activity:-
public class ZBarScannerActivity extends ActionBarActivity {
private Camera mCamera;
private CameraPreview mPreview;
private Handler autoFocusHandler;
ImageScanner scanner;
ImageView backButton;
private boolean barcodeScanned = false;
private boolean previewing = true;
CustomTextview navigation_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner_view_layout);
ActionBar actionBar = getSupportActionBar();
String header = "<font color=\"#ffffff\">" + "BarCode Scanner"
+ " </font>";
CommonUtils.actionbarHeader(this, actionBar, header);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
autoFocusHandler = new Handler();
mCamera = getCameraInstance();
/* Instance barcode scanner */
scanner = new ImageScanner();
scanner.setConfig(0, Config.X_DENSITY, 3);
scanner.setConfig(0, Config.Y_DENSITY, 3);
mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
preview.addView(mPreview);
navigation_title = (CustomTextview)findViewById(R.id.navigationTitle_id);
navigation_title.setText("Barcode Scanner");
backButton = (ImageView)findViewById(R.id.navigationbackbutton_id);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static {
System.loadLibrary("iconv");
}
public void onPause() {
super.onPause();
releaseCamera();
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
private void releaseCamera() {
if (mCamera != null) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
private Runnable doAutoFocus = new Runnable() {
public void run() {
if (previewing)
mCamera.autoFocus(autoFocusCB);
}
};
PreviewCallback previewCb = new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Size size = parameters.getPreviewSize();
Image barcode = new Image(size.width, size.height, "Y800");
barcode.setData(data);
int result = scanner.scanImage(barcode);
if (result != 0) {
previewing = false;
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
SymbolSet syms = scanner.getResults();
for (Symbol sym : syms) {
System.out.println("------->"+sym.getData());
barcodeScanned = true;
finishActivivtyWithResult(sym.getData());
}
}
}
};
// Mimic continuous auto-focusing
AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
autoFocusHandler.postDelayed(doAutoFocus, 1000);
}
};
/**
*
* #param barCodeResult
*/
private void finishActivivtyWithResult(String barCodeResult){
if (barCodeResult.contains("//b")) {
String replacedString = barCodeResult.replace("//b", "");
System.out.println("One========>" + replacedString);
barCodeResult = replacedString;
}
if (barCodeResult.contains("/t")) {
String replacedString = barCodeResult.replace("/t", "-");
System.out.println("After========>" + replacedString);
barCodeResult = replacedString;
}
Bundle conData = new Bundle();
conData.putString("barCodeResult", barCodeResult);
Intent intent = new Intent();
intent.putExtras(conData);
setResult(RESULT_OK, intent);
finish();
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
my fragment:-
//Camera Button Action Event:-
/**
* #return
*/
private View.OnClickListener cameraDetails() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
BAR_CODE_SCANNER_CODE = 100;
checkCameraPermission();
}
};
}
//BarCode Scanner Result:-
private void checkCameraPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkManifestPermissionSets();
} else {
scanProductCode();
}
}
#TargetApi(23)
private void checkManifestPermissionSets() {
int cameraPermission = ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA);
List<String> permissions = new ArrayList<String>();
if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (!permissions.isEmpty()) {
requestPermissions(
permissions.toArray(new String[permissions.size()]),
REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
} else {
scanProductCode();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
//Log.d("Permissions", "Permission Granted: "+ permissions[i]);
scanProductCode();
break;
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
//Log.d("Permissions", "Permission Denied: " + permissions[i]);
//CommonUtils.showToastMessage(StockTransfer.this, "You've disabled the App required Permissions");
break;
}
}
}
break;
default: {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
}
private void scanProductCode() {
if (isCameraAvailable()) {
CommonUtils.showToastMessage(getActivity(),
"Please Scan Your Product BarCode");
callThreadScannerActivity();
} else {
Toast.makeText(getActivity(), "Rear Facing Camera Unavailable",
Toast.LENGTH_SHORT).show();
}
}
private void callThreadScannerActivity() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// dialog.dismiss();
callScannerActivity();
}
}, 700);
}
// Call Scanner Activity:-
private void callScannerActivity() {
Intent intent = new Intent(getActivity(), ZBarScannerActivity.class);
startActivityForResult(intent, BAR_CODE_SCANNER_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("result code------>" + requestCode);
}
private boolean isCameraAvailable() {
PackageManager pm = getActivity().getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
}
Simple logic connected to general life
activity : father(parent)
fragment : child
if child wanna money than he ask to him/ her father.
technical way if fragment(child) wanna data from onActivityResult it always VIA Activity(father).
ohk .. lets look on code side
stuff at
yourActivity (Parent)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
this list of fragment(child) of activity said to him activity(father) for data
when activity received data it gives as fragments(childs) demands.
In fragment whenever we start activity for any result then that result in received in onActivityResult of activity then we have to pass this result to fragment's onActivityResult
Write this to your activitys's onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logg.e("RESULT ", " " + resultCode);
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case 100:
Fragment YourRfargment= getFragmentManager().findFragmentByTag("Your Fragment TAG");
updateproFragment.onActivityResult(requestCode, resultCode, data);
break;
}
}
by this you will get your result in fragment's onActivityresult.