How to set sourceImagePath, outputFile in Image Editor - android

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
)
);
}
}

Related

Application crashes every time camera open

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;

Keep getting error when trying to select profile pic for current user Firebase Auth

I keep getting the same error and the app stops working when I try and select an image to upload for user using google firease firebaseAuth on android. Here is the error I keep getting: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzbq"
My code is as follows:
public class StudentAccount extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
public static final int CAMERA_REQUEST_CODE = 10;
public static final int PROFILE_PIC_REQUEST_CODE = 20;
private Button button, signout;
private FirebaseAuth mAuth;
TextView username;
ImageView imageView;
EditText editText;
Uri uriProfileImage;
ProgressBar progressBar;
String profileImageUrl;
ListView listView;
private List<String> userList = new ArrayList<>();
private final int BARCODE_RECO_REQ_CODE = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_account);
mAuth = FirebaseAuth.getInstance();
signout = (Button) findViewById(R.id.SIGNOUT3);
username = (TextView) findViewById(R.id.welcomeText2);
//Check if user i already logged in or not
if (mAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
}
//Fetching display name of current user and setting to activity
FirebaseUser user = mAuth.getCurrentUser();
if (user != null){
username.setText("Welcome " +user.getEmail());
}
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
imageView = findViewById(R.id.imageView);
progressBar = findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
button = findViewById(R.id.VIEW_ATTENDANCE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openViewMyAttendance();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
findViewById(R.id.buttonSave).setOnClickListener( new View.OnClickListener(){
#Override
public void onClick(View view) {
saveUserInformation();
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if (displayName.isEmpty()){
editText.setError("Username required");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if (user != null && profileImageUrl != null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName).setPhotoUri(Uri.parse(profileImageUrl)).build();
user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StudentAccount.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() !=null){
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == BARCODE_RECO_REQ_CODE){
if (resultCode == RESULT_OK){
Bitmap photo = (Bitmap)data.getExtras().get("data");
barcodeRecognition(photo);
}
}
}
private void barcodeRecognition(Bitmap photo) {
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Task<List<FirebaseVisionBarcode>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> barcodes) {
for (FirebaseVisionBarcode barcode: barcodes) {
Rect bounds = barcode.getBoundingBox();
Point[] corners = barcode.getCornerPoints();
String rawValue = barcode.getRawValue();
int valueType = barcode.getValueType();
Toast.makeText(StudentAccount.this, rawValue, Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StudentAccount.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private void uploadImageToFirebaseStorage() {
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference
("profilepics/"+System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null){
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(StudentAccount.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void loadUserInformation() {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
updateProfilePermissions();
} else {
String[] permissionRequested = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissionRequested, PROFILE_PIC_REQUEST_CODE);
}
}
private void updateProfilePermissions() {
FirebaseUser user = mAuth.getCurrentUser();
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl().toString()).into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
}
private void showImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"),CHOOSE_IMAGE);
}
#Override
protected void onPause(){
super.onPause();
}
public void barcodeReco(View v) {
if(checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
callsCamera();
} else {
String[] permissionRequested = {Manifest.permission.CAMERA};
requestPermissions(permissionRequested, CAMERA_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_CODE){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
callsCamera();
} else {
Toast.makeText(this, getString(R.string.unable_to_invoke_camera), Toast.LENGTH_LONG).show();
}
} else if (requestCode == PROFILE_PIC_REQUEST_CODE){
if (grantResults [0] == PackageManager.PERMISSION_GRANTED){
loadUserInformation();
} else {
Toast.makeText( this, getString(R.string.Unable_to_update_profile), Toast.LENGTH_LONG).show();
}
}
}
private void callsCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,BARCODE_RECO_REQ_CODE);
}
public void openViewMyAttendance () {
Intent intent = new Intent(this, ViewMyAttendance.class);
startActivity(intent);
}
}

GoogleMapSnapshot NullPointerException

I am trying to take a screenshot of google maps android and pass the image to a new activity but I keep getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.snapshot(com.google.android.gms.maps.GoogleMap$SnapshotReadyCallback)' on a null object reference
at com.jjoey.transportr.activities.BookRideActivity.initViews(BookRideActivity.java:480)
at com.jjoey.transportr.activities.BookRideActivity.onCreate(BookRideActivity.java:101)
at android.app.Activity.performCreate(Activity.java:5990)
I have tried writing the code in onResume and onMapReady methods of activity but still error persists.
Here's my code for activity:
public class BookRideActivity extends FirebaseUtils implements OnMapReadyCallback {
private static final String TAG = BookRideActivity.class.getSimpleName();
private static final int LOC_REQ_CODE = 2035;
private Toolbar toolbar;
private ImageView backIV;
private SharedPrefsHelper prefsHelper;
private SupportMapFragment mapFragment;
private GoogleMap mGmap;
private LocationRequest locationRequest;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback callback;
private Location mCurrLocation;
private Marker marker;
private Bitmap locnImg;
private EditText startET, dropET, et_coupon, et_payment_options, et_rider;
private TextView estimatedPUTimeTV;
private Button bookNowBtn, cancelBtn;
private double lat = 0f, lon = 0f;
private String start = null, drop = null;
private boolean isValid = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_ride);
initViews();
start = getIntent().getStringExtra("start_addr");
drop = getIntent().getStringExtra("dest_addr");
if (start != null && drop != null) {
startET.setText(start);
dropET.setText(drop);
} else {
clearInputs();
}
setSupportActionBar(toolbar);
prefsHelper = new SharedPrefsHelper(this);
prefsHelper.setLoggedOut(false);
backIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(BookRideActivity.this, ClientHomeActivity.class));
}
});
et_coupon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Coupon Clicked");
showCouponDialog();
}
});
checkPerms();
handlePlacesInput();
}
private void checkPerms() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
} else {
startLocationListener();
}
}
private void reqPerms() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOC_REQ_CODE);
}
private void startLocationListener() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setInterval(UPDATE_INTERVAL);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest settingsRequest = builder.build();
SettingsClient client = LocationServices.getSettingsClient(this);
client.checkLocationSettings(settingsRequest);
drawLocationOnMap();
}
private void drawLocationOnMap() {
callback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrLocation = locationResult.getLastLocation();
if (marker != null && mCurrLocation != null) {
marker.remove();
lat = mCurrLocation.getLatitude();
lon = mCurrLocation.getLongitude();
}
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lon));
options.title("You");
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_marker));
marker = mGmap.addMarker(options);
mGmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 18.0f));
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.myLooper());
//mGmap.setMyLocationEnabled(true);
} else {
reqPerms();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case LOC_REQ_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationListener();
}
break;
}
}
private void handlePlacesInput() {
startET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startET.setText("");
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(BookRideActivity.this);
startActivityForResult(intent, START_PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
}
}
});
dropET.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dropET.setText("");
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(BookRideActivity.this);
startActivityForResult(intent, DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
Log.d(TAG, "Play-Services-Repairable Err:\t" + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d(TAG, "Play-Services-Unavailable Err:\t" + e.getMessage());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case START_PLACE_AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String txt = place.getAddress().toString();
startET.setText(txt);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
Log.d(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
}
break;
case DROP_PLACE_AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String txt = place.getAddress().toString();
dropET.setText(txt);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
Log.d(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
}
break;
}
}
private boolean validate() {
String startAddr = startET.getText().toString();
String destAddr = dropET.getText().toString();
if (TextUtils.isEmpty(startAddr) && TextUtils.isEmpty(destAddr)) {
isValid = false;
} else if (!TextUtils.isEmpty(startAddr) && !TextUtils.isEmpty(destAddr)) {
isValid = true;
}
return true;
}
private void clearInputs() {
startET.setText("");
dropET.setText("");
}
private void initViews() {
toolbar = findViewById(R.id.toolbar);
backIV = findViewById(R.id.backIV);
dropET = findViewById(R.id.dropLocationET);
startET = findViewById(R.id.startLocationET);
bookNowBtn = findViewById(R.id.bookNowBtn);
cancelBtn = findViewById(R.id.cancelBtn);
GoogleMap.SnapshotReadyCallback snapshotReadyCallback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
locnImg = bitmap;
Log.d(TAG, "Snapshot Ready");
}
};
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
mGmap.snapshot(snapshotReadyCallback);
Log.d(TAG, "Snapshot Taken");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
View mapBtn = (View) ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mapBtn.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 30, 30);
}
}
I have tried following this tutorial but it doesn't work in my case.The error occurs when I try mGmap.snapshot(snapshotReadyCallback);. I have initialized the map in the lines above and gotten the location using FusedLocationProviderClient api.
Can anyone help me understand why it's throwing this error? Thanks

surface view does not show camera after i gave permission

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);
}
}
}
}
}

Is disappearing after going to another activity but showing uploading to server Glide and volley

I have created two functionality for photo uploading in my app. The first one is for capture image and the second one is for pick image from gallery. Now I have a photo API as URL. By using this API I have to upload the image at first to server and from server it will be available throught the app. Now I can successfully uploaded the picture in server and in the server side shows the picture. But in the imageview of app does not show that image. Whenever I go to another activity and then come back to image activity the imageview is empty. I have used shared preference to keep the image at image view, but that does not work.
Here is my code for photo activity
public class ViewProfileFragment extends Fragment implements
View.OnClickListener{
private static final int CODE_GALLERY_REQUEST =999 ;
private static final int MY_CAMERA_REQUEST_CODE = 100;
private ImageView image;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
Bitmap bm;
private String UPLOAD_URL = Constants.HTTP.PHOTO_URL;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_view_profile,
container, false);
.........
image=(ImageView)rootView.findViewById(R.id.profile_pic);
saveData();
return rootView;
}
public void saveData(){
Log.d( "----ViewProfile-Email", "mEmail" );
GlobalClass globalClass = new GlobalClass();
String mEmail = globalClass.getEmail_info();
Realm profileRealm;
profileRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results =
profileRealm.where(MyColleagueModel.class).equalTo("mail",
mEmail).findAll();
//fetching the data
results.load();
if (results.size() > 0) {
......
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
image.setImageURI(Uri.parse(mImageUri));
} else {
Glide.with( this )
.load(Constants.HTTP.PHOTO_URL+mail)
.thumbnail(0.5f)
.override(200,200)
.diskCacheStrategy( DiskCacheStrategy.ALL)
.into( image);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
galleryIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
if(requestCode==MY_CAMERA_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
cameraIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
super.onRequestPermissionsResult( requestCode, permissions,grantResults );
}
public void showDialog(){
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new
AlertDialog.Builder(this.getActivity());
.....
}
});
alertListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListViekw Clicked item index
if (position == 0) {
userChoosenTask ="Take Photo";
alert.dismiss();
if(isPermissionGrantedCamera()) {
cameraIntent();
}
}
else if (position == 1){
userChoosenTask ="Choose from Library";
alert.dismiss();
if(isPermissionGrantedGallery()) {
galleryIntent();
}
}
}
});
}
public boolean isPermissionGrantedGallery() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
public boolean isPermissionGrantedCamera() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.CAMERA}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
public void cameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if
(takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
{
File cameraFolder;
if
(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cameraFolder = new
File(Environment.getExternalStorageDirectory(), "image/");
} else {
cameraFolder = getActivity().getCacheDir();
}
if (!cameraFolder.exists()) {
cameraFolder.mkdirs();
}
String imageFileName = System.currentTimeMillis() + ".jpg";File photoFile = new File(cameraFolder + imageFileName);
currentPhotoPath = photoFile.getAbsolutePath();
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE && data!=null){
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA ) {
if(!TextUtils.isEmpty(currentPhotoPath)) {
try {
galleryAddPic();
onCaptureImageResult();
}
catch (Exception e){
}
}
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
private void onCaptureImageResult() {
Bitmap bitmap = getBitmapFromPath(currentPhotoPath, 200, 200);
image.setImageBitmap(bitmap);
compressBitMap(bitmap);
}
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(uri,
projection, null, null, null);
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
currentPhotoPath = cursor.getString(column_index);
cursor.close();
} else {
currentPhotoPath = uri.getPath();
}// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(uri));
editor.commit();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
bm = BitmapFactory.decodeFile(currentPhotoPath);
compressBitMap(bm);
}
private void compressBitMap(Bitmap bitmap) {
ImageConversion imageConversion = new ImageConversion();
byte[] bytesArray;
int maxSize = 10 * 1024;
int imageMaxQuality = 50;
int imageMinQuality = 5;
bytesArray = imageConversion.convertBitmapToByteArray(bitmap,
imageMaxQuality, imageMinQuality, maxSize);
File destination = new
File(getContext().getApplicationContext().getFilesDir(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytesArray);
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
currentPhotoPath = destination.getPath();
uploadImage(bytesArray);
}
private void uploadImage(final byte[] bytesArray){
.....
}
}
Please don't use
image.setImageURI(uri);
image.invalidate();
Please use this code below instead of that :
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources