I am trying to show Camera capture images and gallary images in Recyclerview. It works fine but when I capture a second image or select from gallary it replaces the first image in Recyclerview. I want to show all images in Recyclerview that I have selected or captured from camera.
Activity code:
public void ShowDialog() {
final Dialog dialog = new Dialog(AttachDisputeDocActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.rc_img_dialog_layt);
WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.BOTTOM;
layoutParams.dimAmount = 0.5f;
dialog.getWindow().setAttributes(layoutParams);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
RelativeLayout UploadImage = dialog.findViewById(R.id.rela_upload);
RelativeLayout TakeCamera = dialog.findViewById(R.id.rela_camera);
UploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(AttachDisputeDocActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AttachDisputeDocActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, DspConstant.REQUEST_GALLARY_IMAGE);
} else {
gallaryintent();
}
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
TakeCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(AttachDisputeDocActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AttachDisputeDocActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, DspConstant.REQUEST_CAPTURE_IMAGE);
} else {
openCameraIntent();
}
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
}
private void openCameraIntent() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
pictureIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID+".fileprovider", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(pictureIntent, DspConstant.REQUEST_CAPTURE_IMAGE);
}
}
}
private void gallaryintent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent .setType("image/*");
startActivityForResult(galleryIntent, DspConstant.REQUEST_GALLARY_IMAGE);
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
imagefilepath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DspConstant.REQUEST_GALLARY_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
loadRecyclerView(picturePath);
} else if (requestCode == DspConstant.REQUEST_CAPTURE_IMAGE && requestCode == RESULT_OK && null != data) {
loadRecyclerView(imagefilepath);
}
}
private void loadRecyclerView(String image) {
documentlist.add(image);
attachDocAdapter = new AttachDocAdapter(this, documentlist);
recyclerView.setAdapter(attachDocAdapter);
attachDocAdapter.updateList(documentlist);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case DspConstant.REQUEST_GALLARY_IMAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
gallaryintent();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
break;
case DspConstant.REQUEST_CAPTURE_IMAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCameraIntent();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
Adapter Code:
public class AttachDocAdapter extends RecyclerView.Adapter<AttachDocAdapter.MyViewHolder> {
private ArrayList<String> imageslist=new ArrayList<>();
private Activity activity;
public AttachDocAdapter(Activity activity,ArrayList<String> imageslist)
{
this.activity=activity;
this.imageslist=imageslist;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView img_document;
CitiTextView txt_deleteimage;
public MyViewHolder(View itemView) {
super(itemView);
img_document=itemView.findViewById(R.id.img_document);
txt_deleteimage=itemView.findViewById(R.id.txt_delete);
}
}
#Override
public AttachDocAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemview= LayoutInflater.from(parent.getContext()).inflate(R.layout.rc_img_attach_layout,parent,false);
return new MyViewHolder(itemview);
}
#Override
public void onBindViewHolder(AttachDocAdapter.MyViewHolder holder, int position) {
Glide.with(activity).load(imageslist.get(position)).into(holder.img_document);
holder.txt_deleteimage.setOnClickListener(view -> removeItem(holder.getAdapterPosition()));
}
#Override
public int getItemCount() {
if (imageslist==null)
{
return 0;
}return imageslist.size();
}
public void updateList(ArrayList<String> imageslist) {
this.imageslist = imageslist;
notifyDataSetChanged();
}
public void removeItem(int position) {
imageslist.remove(position);
notifyItemRemoved(position);
}
}
And when I click on TakeCamera nothing happens on the Samsung S5.
Related
Having the following error:
android.os.FileUriExposedException: file:///storage/emulated/0/temp.jpg exposed beyond app through ClipData.Item.getUri()
when I choose Option Camera from chosen AlertDialog
And the following error when I try to choose a photo from Gallery:
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0 (Is a directory)
The Gallery opens up, but I can't choose an image to set it to my ImageView
Here is the code:
public class MainActivity extends AppCompatActivity {
private Button contactsButton, galleryButton;
public static final int Gallery_Code = 100;
public static final int Contacts_Code = 101;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsButton = findViewById(R.id.buttonContacts);
galleryButton = findViewById(R.id.buttonGallery);
imageView = findViewById(R.id.imageView);
contactsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkPermission(Manifest.permission.READ_CONTACTS, Contacts_Code);
}
});
galleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
}
private void uploadImage() {
final String[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Upload Photo");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
File[] files = f.listFiles();
if (files != null) {
for (File temp : files) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
imageView.setImageBitmap(thumbnail);
}
}
}
private void checkPermission(String readContacts, int contacts_code) {
if (ContextCompat.checkSelfPermission(MainActivity.this, readContacts)
== PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{readContacts},
contacts_code);
} else {
Toast.makeText(MainActivity.this,
"Permission already granted",
Toast.LENGTH_SHORT)
.show();
if (contacts_code == Contacts_Code) {
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super
.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == Gallery_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Gallery Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 1);
} else {
Toast.makeText(MainActivity.this,
"Gallery Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == Contacts_Code) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,
"Contacts Permission Granted",
Toast.LENGTH_SHORT)
.show();
Intent i = new Intent(MainActivity.this, ContactsActivity.class);
startActivity(i);
} else {
Toast.makeText(MainActivity.this,
"Contacts Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
}
} }
I have an application for recording a screen, it does not work on android version 10. As I understand it, this is due to privacy changes in force in Android 10. Now for any application using MediaProjection api, must specify an attribute android:foregroundServiceType= in the service tag under the manifest, but my application uses MediaProjection in the fragment, not the service. Is it possible to make MediaProjection work from a fragment, or do I need to redo it?
Sorry for my bad english
Here is a mistake
Caused by java.lang.SecurityException
Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
com.example.screen_recording.screens.main_record.MainFragment.onActivityResult (MainFragment.java:321)
Here is the snippet code
public class MainFragment extends Fragment {
SharedPreferences p;
TimerViewModel model;
private static final int REQUEST_CODE = 1000;
private static final int REQUEST_PERMISSION = 1001;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private boolean isRecord = false;
private boolean isPause = false;
private boolean isNightTheme = false;
private String videoUri = "";
private MediaProjectionManager mediaProjectionManager;
private MediaProjection mediaProjection;
private VirtualDisplay virtualDisplay;
private MediaProjectionCallBack mediaProjectionCallBack;
private MediaRecorder mediaRecorder;
private int mScreenDensity;
private static int DISPLAY_WIDTH;
private static int DISPLAY_HEIGHT;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
//View
private CardView rootLayout;
private VideoView videoView;
private ToggleButton toggleButton;
private TextView textViewTimer;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
p = PreferenceManager.getDefaultSharedPreferences(getActivity());
isNightTheme = p.getBoolean("isNightTheme", false);
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
DISPLAY_WIDTH = metrics.widthPixels;
DISPLAY_HEIGHT = metrics.heightPixels;
mediaRecorder = new MediaRecorder();
mediaProjectionManager = (MediaProjectionManager) getActivity().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
// View
videoView = view.findViewById(R.id.videoView);
rootLayout = view.findViewById(R.id.cardView);
toggleButton = view.findViewById(R.id.toggleButton);
textViewTimer = view.findViewById(R.id.textViewTimer);
// ViewModal
model = new ViewModelProvider(getActivity()).get(TimerViewModel.class);
textViewTimer.setText(model.timeState);
if (isNightTheme) {
rootLayout.setBackgroundResource(R.color.colorBlack);
textViewTimer.setTextColor(Color.WHITE);
}
// Event
//Record Toggle Start and Stop
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
errorRecordAction();
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.RECORD_AUDIO)) {
errorRecordAction();
Snackbar.make(rootLayout, "Разрешения", Snackbar.LENGTH_INDEFINITE)
.setAction("Включить", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
}, REQUEST_PERMISSION);
}
}).show();
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
}, REQUEST_PERMISSION);
}
} else {
toggleScreenShare(toggleButton);
}
}
});
return view;
}
private void toggleScreenShare(View v) {
if (((ToggleButton) v).isChecked()) {
int quality = p.getInt("quality", 480);
boolean micro = p.getBoolean("micro", false);
int fps = p.getInt("FPS", 15);
initRecorder(quality, micro, fps);
recorderScreen();
isRecord = true;
p.edit().putBoolean("isRecord", isRecord).apply();
} else {
mediaRecorder.stop();
mediaRecorder.reset();
stopRecordScreen();
videoView.setVisibility(View.VISIBLE);
videoView.setVideoURI(Uri.parse(videoUri));
videoView.start();
isRecord = false;
p.edit().putBoolean("isRecord", isRecord).apply();
getActivity().stopService(new Intent(getContext(), TimerService.class));
}
}
private BroadcastReceiver uiUpdated = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textViewTimer.setText(intent.getStringExtra("countdown"));
model.timeState = intent.getStringExtra("countdown");
}
};
private void recorderScreen() {
if (mediaProjection == null) {
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
return;
}
virtualDisplay = createVirtualDisplay();
mediaRecorder.start();
}
private VirtualDisplay createVirtualDisplay() {
return mediaProjection.createVirtualDisplay("MainFragment", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mediaRecorder.getSurface(), null, null);
}
private void initRecorder(int QUALITY, boolean isMicro, int fps) {
try {
if (isMicro) {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
if (isMicro) {
mediaRecorder.setAudioSamplingRate(44100);
mediaRecorder.setAudioEncodingBitRate(16 * 44100);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
}
videoUri = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
+ new StringBuilder("/FreeRecord_").append(new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss")
.format(new Date())).append(".mp4").toString();
mediaRecorder.setOutputFile(videoUri);
mediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoEncodingBitRate(40000);
mediaRecorder.setCaptureRate(fps);
mediaRecorder.setVideoFrameRate(fps);
int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mediaRecorder.setOrientationHint(orientation);
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != REQUEST_CODE) {
Toast.makeText(getActivity(), "Unk error", Toast.LENGTH_SHORT).show();
errorRecordAction();
return;
}
if (resultCode != Activity.RESULT_OK) {
Log.i("Разрешения", "Я зашел");
Toast.makeText(getActivity(), "Доступ запрещен", Toast.LENGTH_SHORT).show();
errorRecordAction();
return;
}
mediaProjectionCallBack = new MediaProjectionCallBack();
if (data != null) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
mediaProjection.registerCallback(mediaProjectionCallBack, null);
virtualDisplay = createVirtualDisplay();
mediaRecorder.start();
} else {
Toast.makeText(getActivity(), "Не удалось запустить запись", Toast.LENGTH_SHORT).show();
Log.i("dataActivity", "data = null");
}
getActivity().startService(new Intent(getContext(), TimerService.class));
getActivity().registerReceiver(uiUpdated, new IntentFilter("COUNTDOWN_UPDATED"));
}
private class MediaProjectionCallBack extends MediaProjection.Callback {
#Override
public void onStop() {
if (toggleButton.isChecked()) {
errorRecordAction();
mediaRecorder.stop();
mediaRecorder.reset();
}
mediaProjection = null;
stopRecordScreen();
super.onStop();
}
}
private void stopRecordScreen() {
if (virtualDisplay == null) {
return;
}
virtualDisplay.release();
destroyMediaProject();
}
private void destroyMediaProject() {
if (mediaProjection != null) {
mediaProjection.unregisterCallback(mediaProjectionCallBack);
mediaProjection.stop();
mediaProjection = null;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSION: {
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
toggleScreenShare(toggleButton);
} else {
errorRecordAction();
Snackbar.make(rootLayout, "Права доступа", Snackbar.LENGTH_INDEFINITE)
.setAction("Включить", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
}, REQUEST_PERMISSION);
}
}).show();
}
return;
}
}
}
private void errorRecordAction() {
getActivity().stopService(new Intent(getContext(), TimerService.class));
isRecord = false;
toggleButton.setChecked(false);
mediaRecorder.reset();
}
}
You should use a foreground service inside the fragment to capture the screen.
Find below links for how to use the foreground service to capture the screen.
How to take a Screenshot from a background-service class using MediaProjection API?
am writing a body measurement app. I have been able to create the camera and it stores the image. I want to use the captured image in another activity where i called the method 'bodyMeasurement'
I really need help in achieving this. Further corrections are also welcomed. Thanks
Here is my Camera Activity;
CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice camera) {
cameraDevice = camera;
createCameraPreview();
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
cameraDevice.close();
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int i) {
cameraDevice.close();
cameraDevice=null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView = (TextureView)findViewById(R.id.textureView);
//From Java 1.4 , you can use keyword 'assert' to check expression true or false
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
btnCapture = (ImageButton)findViewById(R.id.btnCapture);
/* Dexter.withActivity(this)
.withPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (!report.areAllPermissionsGranted()) {
Toast.makeText(MainActivity.this, "You need to grant all permission to use this app features", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
})
.check();*/
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePicture();
}
});
}
private void takePicture() {
if(cameraDevice == null)
return;
CameraManager manager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
try{
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
if(characteristics != null)
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
.getOutputSizes(ImageFormat.JPEG);
//Capture image with custom size
int width = 4608;
int height = 3456;
if(jpegSizes != null && jpegSizes.length > 0)
{
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
final ImageReader reader = ImageReader.newInstance(width,height,ImageFormat.JPEG,1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(reader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
//Check orientation base on device
int rotation = getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));
file = new File(Environment.getExternalStorageDirectory()+"/"+ ".CnatraSamp"+".jpg");
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
try{
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
{
if(image != null)
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream outputStream = null;
try{
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
}finally {
if(outputStream != null)
outputStream.close();
}
}
};
reader.setOnImageAvailableListener(readerListener,mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session, #NonNull CaptureRequest request, #NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(MainActivity.this, "Saved "+file, Toast.LENGTH_SHORT).show();
finish();
Intent i = new Intent(MainActivity.this,BlankActivity.class);
startActivity(i);
finish();
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
try{
cameraCaptureSession.capture(captureBuilder.build(),captureListener,mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
}
},mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void createCameraPreview() {
try{
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(),imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
if(cameraDevice == null)
return;
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Changed", Toast.LENGTH_SHORT).show();
}
},null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if(cameraDevice == null)
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE,CaptureRequest.CONTROL_MODE_AUTO);
try{
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),null,mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
try{
cameraId = manager.getCameraIdList()[1];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[1];
//Check realtime permission if run higher API 23
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId,stateCallback,null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
openCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CAMERA_PERMISSION)
{
if(grantResults[0] != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "You can't use camera without permission", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
startBackgroundThread();
if(textureView.isAvailable())
openCamera();
else
textureView.setSurfaceTextureListener(textureListener);
}
#Override
protected void onPause() {
stopBackgroundThread();
super.onPause();
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try{
mBackgroundThread.join();
mBackgroundThread= null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
the activity i need the image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blank);
height = findViewById(R.id.height);
cancel = findViewById(R.id.cancel);
btnctn = findViewById(R.id.continuebtn);
cmIn = findViewById(R.id.cmIn);
height.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL |
InputType.TYPE_NUMBER_FLAG_SIGNED);
btnctn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (height.getText().toString().trim().isEmpty()){
Toast.makeText(BlankActivity.this,"Please input your height..",Toast.LENGTH_LONG).show();
}else {
final ProgressDialog progressDialog = new ProgressDialog(BlankActivity.this);
progressDialog.setMessage("Getting Your Measurement");
progressDialog.setTitle("Please wait!");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(BlankActivity.this, SettingsActivity.class);
startActivity(i);
progressDialog.dismiss();
}
},5000);
}
//place measurement object
bodyMeasurement();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BlankActivity.this.finish();
Intent i = new Intent(BlankActivity.this, HomeActivity.class);
startActivity(i);
finish();
}
});
cmIn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
num = Double.parseDouble(String.valueOf(height.getText()));
in = 0.3937 * num;
String r = String.valueOf(in);
height.setText(r);
}else {
num = Double.parseDouble(String.valueOf(height.getText()));
cm = num / 0.3937;
String r = String.valueOf(cm);
height.setText(r);
}
}
});
}
private void bodyMeasurement() {
}
}
As mentioned in the comment, you can get the absolute path from the saved image and pass it through an intent to the Activity that it needs it.
To achieve this, you might want to convert your image file to a BitMap first, which will give you the actual path of the image (sometimes .getAbsolutePath() method returns a wrong file path, so it is a better solution to convert your image to a bitmap first).
This can be achieved:
String filePath = file.getPath();
Bitmap imgBitmap = BitmapFactory.decodeFile(filePath);
Then to obtain the real path of the image you saved you need to
1) Obtain the Uri of the created Bitmap:
public Uri getUri(Context context, Bitmap imgBitmap) {
ByteArrayOutputStream bOutputStream = new ByteArrayOutputStream();
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(),
imgBitmap, "Title", null);
return Uri.parse(path);
}
2) Fetch the real path from Uri:
public String getRealPath(Uri uri) {
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
In your first activity you can pass the path of your image through an intent to the other activity, then fetch it and display it/etc.
Intent intent = new Intent(context,OtherActivity.class);
intent.putExtra("PATH",path);
startActivity(intent);
Receive the data you passed:
Intent intent = getIntent();
String path = intent.getStringExtra("PATH");
//convert the path to image/bitmap and display the image
You can also pass the entire Bitmap to the Activity you need it, but I strongly recommend that you don't, because it will use a lot of memory.
I am taking image from camera as well as from gallery,after getting the image, I want to show the image in imageview.
Image that is captured by camera successfully is shown in imageview but when I want to select it from gallery it does not show the image and it also does not show any error. It was working properly but later I add camera feature in activity, it's not working well.
public class DoReport extends AppCompatActivity {
private EditText subject,detail;
private ImageView pic;
private ImageView iv;
private Spinner depart;
private String depat,sub,det;
//for image
private Bitmap selectedImage;
public static String image;
private Uri imageUri;
public final static int PHOTO_FROM_MEMORY_REQUESTED = 10;
static final int REQUEST_IMAGE_CAPTURE = 1;
String userChoosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_report);
subject = (EditText) findViewById(R.id.subject);
detail = (EditText) findViewById(R.id.detail);
depart = (Spinner) findViewById(R.id.Depat_Edit);
iv=(ImageView)findViewById(R.id.ImgView);
}
public void onBackClick(View v) {
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
//to pic the image from galery
//this is new <code>
public void imgBtn(View v) {
selectImage();
}
private void updateSelectedPicture(Uri uri) {
try {
imageUri = uri;
InputStream imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
iv.setImageDrawable(new BitmapDrawable(selectedImage));
image=encode(selectedImage);
} catch(FileNotFoundException ex) {
Log.e("File not found", "Cannot find background file under received URI");
}
}
public static String encode(Bitmap image) {
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public void submit(View v) {
depat=depart.getSelectedItem().toString();
sub=subject.getText().toString();
det=detail.getText().toString();
if(sub.isEmpty()) {
subject.setError("subject is required");
} else if(det.isEmpty()) {
detail.setError("subject is required");
} else {
login_database(depat, sub, det, image);
}
}
private void login_database(final String depat, final String sub,final String det,final String pic) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, Static.user_connect,//changes required
new Response.Listener<String>() {
public void onResponse(String response) {
if ((response.contains("successful"))) {
Toast.makeText(DoReport.this, "Successful Submitted",Toast.LENGTH_LONG).show();
Intent i = new Intent (DoReport.this,UserView.class);
startActivity(i);
finish();
} else {
Toast.makeText(DoReport.this, "Some error occured", Toast.LENGTH_LONG).show();//changes required
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DoReport.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.d("ERROR", toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("key", "3");//changes required
map.put("Depat", depat);
map.put("Detail", det);
map.put("Pic", pic);
map.put("Subject", sub);
map.put("U_id",Static.id);
return map;
}
};
queue.add(request);
}
/*//////////////////////////////////////////////////////////////////////////////////////////
code for selecting image from camera or gallery
*////////////////////////////////////////////////////////////////////////////////////////
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
}
///////////////it will show the dialogue box
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(DoReport.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(DoReport.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
dispatchTakePictureIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
gallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void gallery() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
}
}
only change onActivityResult method remove else if block form id condition like below code...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
selectedImage = BitmapFactory.decodeStream(imageStream);
You should check if selectedImage -the bitmap- is null.
I bet selectedImage==null.
This happens if the bitmap would become too big for available memory.
You should scale it down while loading from stream.
Remember: from the camera you only obtain a thumbnail. Thats the difference.
Here's my code to set a rounding photo from gallery or camera into ImageButton and it works perfectly :
public class EditProfileActivity extends AppCompatActivity {
ImageButton btnValidate,btnCancel,imgProfile;
TextView tvEditPhoto;
RoundImage roundedImage;
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnCancel = findViewById(R.id.toolbar_back_btn);
btnValidate = findViewById(R.id.toolbar_validate_btn);
imgProfile = findViewById(R.id.user_profile_photo_edit);
tvEditPhoto = findViewById(R.id.user_profile_name_edit);
//Rounding image
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.profile);
roundedImage = new RoundImage(bm);
imgProfile.setImageDrawable(roundedImage);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
btnValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
imgProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
tvEditPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PictureUtility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
Toast.makeText(EditProfileActivity.this, "Oups ! vous n'avez pas la permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= PictureUtility.checkPermission(EditProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//resize picture
Bitmap bmw = Bitmap.createScaledBitmap(thumbnail, 120, 120, false);
//rounding picture
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap bmw = Bitmap.createScaledBitmap(bm, 120, 120, false);
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
}
In your code, try to add createScaledBitmap to resize your photo like this:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//add this line and use the new bitmap resized
Bitmap imageBitmapResized = Bitmap.createScaledBitmap(imageBitmap , 120, 120, false);
iv.setImageBitmap(imageBitmapResized );
image = encode(imageBitmapResized );//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
I am a web dev and a couple of weeks ago I started trying to learn android studio and app dev. Im currently using kii cloud for my android app and I am currently trying to figure out how implement the following scenario --
a. I already have user registration, so I am currently working on a "edit profile" page.
b. On the edit profile page Im trying to create a button so that the user clicks on it and it will then open a fragment where the user can upload the image. link
c. Then attach that image to the url, and use the URL where needed such as a view profile page. linkenter link description here
EditUserProfile.java
public class EditUserProfile extends Activity {
Button picbutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
picbutton = (Button) findViewById(R.id.MypicButton);
// Capture button clicks
picbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragcon);
if(fragment == null)
fragment = new ProfilePic();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragcon, fragment);
ft.commit();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
ProfilePic.java (Fragment)
public class ProfilePic extends Fragment {
private static final String TAG = "ProfilePic";
String objectUri = null;
private static final int PICK_IMAGE = 1;
private Activity activity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_attach_file, container,
false);
Bundle args = getArguments();
objectUri = args.getString("object_uri");
Button attachButton = (Button) view
.findViewById(R.id.attach_file_button);
attachButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onAttachFileButtonClicked(v);
}
});
setPageImage(3);
ImageView imageView = (ImageView) view.findViewById(R.id.details);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
}
#Override
public void onDetach() {
super.onDetach();
this.activity = null;
}
public void onAttachFileButtonClicked(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
Uri selectedFileUri = data.getData();
String filePath = getFilePathByUri(selectedFileUri);
Log.v(TAG, "Picture Path : " + filePath);
if (filePath == null) {
showAlert("File not exists, Please select an image that exists locally.");
return;
}
uploadFile(filePath);
} else {
showToast("picking file failed!");
}
}
private void showToast(String message) {
Toast.makeText(this.activity, message, Toast.LENGTH_SHORT).show();
}
private String getFilePathByUri(Uri selectedFileUri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Workaround of retrieving file image through ContentResolver
// for Android4.2 or later
String filePath = null;
FileOutputStream fos = null;
try {
Bitmap bmp = MediaStore.Images.Media.getBitmap(
this.activity.getContentResolver(), selectedFileUri);
String cacheDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "app";
File createDir = new File(cacheDir);
if (!createDir.exists()) {
createDir.mkdir();
}
filePath = cacheDir + File.separator + "upload.jpg";
File file = new File(filePath);
fos = new FileOutputStream(file);
bmp.compress(CompressFormat.JPEG, 95, fos);
fos.flush();
fos.getFD().sync();
} catch (Exception e) {
filePath = null;
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
// Nothing to do
}
}
}
return filePath;
} else {
String[] filePathColumn = { MediaStore.MediaColumns.DATA };
Cursor cursor = this.activity.getContentResolver().query(
selectedFileUri, filePathColumn, null, null, null);
if (cursor == null)
return null;
try {
if (!cursor.moveToFirst())
return null;
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if (columnIndex < 0) {
return null;
}
String picturePath = cursor.getString(columnIndex);
return picturePath;
} finally {
cursor.close();
}
}
}
private void uploadFile(String path) {
KiiObject object = KiiObject.createByUri(Uri.parse(objectUri));
File f = new File(path);
Log.v(TAG, "file can read : " + f.canRead());
KiiUploader uploader = object.uploader(this.activity, f);
uploader.transferAsync(new KiiRTransferCallback() {
#Override
public void onStart(KiiRTransfer operator) {
setFragmentProgress(View.VISIBLE);
}
#Override
public void onTransferCompleted(KiiRTransfer operator, Exception e) {
setFragmentProgress(View.INVISIBLE);
if (e == null) {
} else {
}
}
});
}
public void moveFromDialogFragment(Class<?> clazz) {
if (clazz != null) {
Intent i = new Intent(this.activity, clazz);
startActivity(i);
}
}
void showAlert(String message) {
DialogFragment newFragment = AlertDialogFragment.newInstance(
R.string.operation_failed, message, null);
newFragment.show(getFragmentManager(), "dialog");
}
void setFragmentProgress(int v) {
ProgressFragment fragment = (ProgressFragment) getFragmentManager()
.findFragmentById(R.id.progressFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setProgressBarVisiblity(v);
}
}
void setPageImage(int page) {
ProgressFragment fragment = (ProgressFragment) getFragmentManager()
.findFragmentById(R.id.progressFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setPageImage(page);
}
}
}
Then for things like this, Im trying to find a way to dynamically show the profile pictures associated with the users, and if not use the icon as default.
holder.icon.setImageResource(R.drawable.list_account);
UserListLoader.java
public class UserListAdapter extends AbstractArrayAdapter<IUser> {
private final LayoutInflater inflater;
public UserListAdapter(Context context) {
super(context, R.layout.image_list_item);
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = this.inflater.inflate(R.layout.image_list_item, parent, false);
holder = new ViewHolder();
holder.text = (TextView)convertView.findViewById(R.id.row_text);
holder.icon = (ImageView)convertView.findViewById(R.id.row_icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
IUser user = this.getItem(position);
holder.position = position;
holder.text.setText(user.getUsername());
holder.icon.setImageResource(R.drawable.list_account);
return convertView;
}
}
Also when opening in app, the EditUserProfile crashes at
picbutton.setOnClickListener(new View.OnClickListener()
Any guidance or help on the matter is appreciated. Thanks.
I hope this helped someone...
public void uploadImage() {
UserFields userFields = new UserFields();
userFields.putDisplayName("AllDeals");
KiiUser.registerAsPseudoUser(userFields,
new KiiUserRegisterCallback() {
#Override
public void onRegisterCompleted(KiiUser kiiUser,
Exception exception) {
// TODO Auto-generated method stub
if (exception != null) {
// Error handling
Log.e("Exception", exception.toString());
return;
} else {
String accessToken = kiiUser.getAccessToken();
final KiiObject object = Kii.bucket("AllDeals")
.object();
object.set("placeImage", imageURL);
File localFile = new File(picturePath);
KiiUploader uploader = object.uploader(
getApplicationContext(), localFile);
uploader.transferAsync(new KiiRTransferCallback() {
public void onTransferCompleted(
KiiRTransfer operator,
Exception exception) {
if (exception != null) {
return;
}
object.publishBody(new KiiObjectPublishCallback() {
#Override
public void onPublishCompleted(
String url,
KiiObject object,
Exception exception) {
if (exception != null) {
return;
}
object.set("url", url);
object.save(new KiiObjectCallBack() {
public void onSaveCompleted(
int token,
KiiObject object,
Exception exception) {
if (exception != null) {
return;
}
Toast toast = Toast
.makeText(
MainActivity.this,
"Your image is added successfully",
500);
};
});
}
});
};
});
}
});
}