Creating Object: Exception Caught in onSaveCompleted - java

I followed the Kii Cloud tutorial on creating and archieving an object, and tried to implement it to my own app. What it basically does is, when user clicks on the "existingButton", it opens a new activity where user can pick an image from the gallery and upload it. I'm facing no issues on the second activity, yet the uri from the first activity comes as "null" to the second activity and I'm getting a NullPointerException eventually, since I'm trying to parse a null String. I examined this issue through debugger and found out that the problem is in the first activity's "onSaveCompleted" method. The if (exception == null) condition is not met, which basically means that I'm getting some kind of an exception, I guess. Then, if (exception instanceof CloudExecutionException) condition is not met, too. As a result, it shows the Toast of the else condition of my main if. Code is below. Thanks for any help guys.
First Activity:
public class SendNotePreActivity extends AppCompatActivity {
public static final String APP_BUCKET_NAME = "tutorial";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_note_pre);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button existingButton = (Button) findViewById(R.id.existingButton);
existingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
KiiBucket bucket = Kii.bucket(APP_BUCKET_NAME);
KiiObject object = bucket.object();
object.set("deneme", 313131);
object.save(new KiiObjectCallBack() {
#Override
public void onSaveCompleted(int token, #NonNull KiiObject object,
Exception exception) {
if (exception == null) {
final String uri = object.toUri().toString();
SharedPreferences.Editor mEditor = getSharedPreferences("args", MODE_PRIVATE).edit();
mEditor.putString("uri", uri);
mEditor.apply();
Toast.makeText(SendNotePreActivity.this, "SUCCESSFUL", Toast.LENGTH_LONG).show();
} else {
if (exception instanceof CloudExecutionException) {
Toast.makeText(SendNotePreActivity.this, "Please choose an image", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SendNotePreActivity.this, "Please choose an image222", Toast.LENGTH_LONG).show();
}
}
}
});
Intent intent = new Intent(SendNotePreActivity.this, SendNoteActivity.class);
startActivity(intent);
}
});
}
}
Second Activity:
public class SendNoteActivity extends AppCompatActivity {
ImageView imagePreview;
private static final int PICK_IMAGE = 1;
String filePath = null;
String objectUri = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imagePreview = (ImageView) findViewById(R.id.imagePreview);
Button chooseButton = (Button) findViewById(R.id.chooseButton);
chooseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Note"), PICK_IMAGE);
}
});
Button sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (filePath == null) {
Toast.makeText(SendNoteActivity.this, "Please choose an image", Toast.LENGTH_LONG).show();
} else {
uploadFile(filePath);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedFileUri = data.getData();
imagePreview.setImageURI(selectedFileUri);
filePath = getFilePathByUri(selectedFileUri);
if (filePath == null) {
Toast.makeText(SendNoteActivity.this, "File does not exist", Toast.LENGTH_LONG).show();
return;
}
} else {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(SendNoteActivity.this, "Picking failed", 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(
SendNoteActivity.this.getContentResolver(), selectedFileUri);
String cacheDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "tutorialapp";
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(Bitmap.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 = SendNoteActivity.this.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) {
SharedPreferences prefs = getSharedPreferences("args", MODE_PRIVATE);
objectUri = prefs.getString("uri", "OLMADI AQ");
KiiObject object = KiiObject.createByUri(Uri.parse(objectUri));
File f = new File(path);
KiiUploader uploader = object.uploader(SendNoteActivity.this, f);
uploader.transferAsync(new KiiRTransferCallback() {
#Override
public void onStart(KiiRTransfer operator) {
}
#Override
public void onTransferCompleted(KiiRTransfer operator, Exception e) {
if (e == null) {
Toast.makeText(SendNoteActivity.this, "Successful", Toast.LENGTH_LONG).show();
} else {
Throwable cause = e.getCause();
if (cause instanceof CloudExecutionException)
Toast.makeText(SendNoteActivity.this, "Error", Toast.LENGTH_LONG).show();
else
Toast.makeText(SendNoteActivity.this, "Error2", Toast.LENGTH_LONG).show();
}
}
});
}
}
log:
FATAL EXCEPTION: main
Process: com.theoc.proto, PID: 8050
java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:470)
at android.net.Uri$StringUri.<init>(Uri.java:460)
at android.net.Uri.parse(Uri.java:432)
at com.theoc.proto.SendNoteActivity.uploadFile(SendNoteActivity.java:163)
at com.theoc.proto.SendNoteActivity.access$000(SendNoteActivity.java:44)
at com.theoc.proto.SendNoteActivity$2.onClick(SendNoteActivity.java:82)
at android.view.View.performClick(View.java:4763)
at android.view.View$PerformClick.run(View.java:19821)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

Move startActivity into onSaveCompleted, because now you start the 2nd activity before save is finishec

Related

How to call captured image in another activity{Don't need it to be displayed}

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.

Show Capture images and gallary images in Recyclerview

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.

Class variable not changing in IF or Switch statements

Seems simple, but I can't get it to work. I have a public class string variable that should change within a if or switch statement. I haven't declared the variable inside the statement so it should change given the scope, no? But it only reads "FROM" and when I do go to change it in the if statement that applies, it does change to "TO" but only in that instance and reverts back to "FROM". I would pass it along the methods, but the full code is more cluttered and I don't think it's possible to do so.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String typeOfText = "FROM";
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantRequest) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.faboptions_favorite) {
Toast.makeText(MainActivity.this, "FROM", Toast.LENGTH_SHORT).show();
typeOfText = "FROM";
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else if (view.getId() == R.id.faboptions_textsms) {
Toast.makeText(MainActivity.this, "TO", Toast.LENGTH_SHORT).show();
typeOfText = "TO";
Log.d("VARIABLE","" + typeOfText);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else {
typeOfText = "FROM";
Toast.makeText(MainActivity.this, "Share", Toast.LENGTH_SHORT).show();
createDialogSaveInfo();
}
}
private void createDialogSaveInfo() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.dialog_confirm_address_scan);
//Establish Dialog Views
Button submit = (Button) dialog.findViewById(R.id.button_dialog_scanner_submit);
Button cancel = (Button) dialog.findViewById(R.id.button_dialog_scanner_cancel);
final EditText fromEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_from);
final EditText toEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_to);
//Set text from captured strings in surface view
fromEditText.setText(fromAddress);
toEditText.setText(toAddress);
//Setup listeners
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO save info to realm
saveLabelInfoIntoRealm(fromEditText.getText().toString(), toEditText.getText().toString());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void saveLabelInfoIntoRealm(final String from, final String to) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Package userPackage = realm.createObject(Package.class, 0);
userPackage.setFromAddress(from);
userPackage.setToAddress(to);
}
});
}
private int getPrimaryKey() {
try {
return realm.where(Package.class).max("primaryKey").intValue() + 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private void configureListeners() {
fabOptions.setOnClickListener(this);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
if (path == null) {
Log.d("TAG", "" + path.toString());
}
return Uri.parse(path);
}
private void cropPicFile(Bitmap file) {
Uri imageToCrop = getImageUri(this, file);
CropImage.activity(imageToCrop)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri photo = result.getUri();
readImage(photo);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void readImage(Uri photo) {
StringBuilder stringBuilder = new StringBuilder();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photo);
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
final SparseArray<TextBlock> items = textRecognizer.detect(imageFrame);
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("VARIABLE","" + typeOfText);
if (typeOfText.equals("FROM")) {
fromAddress = stringBuilder.toString();
} else if (typeOfText.equals("TO")){
toAddress = stringBuilder.toString();
}
}
}
The reason the code keeps reverting is because the call to readImage() is in onActivityResult() which recreates the activity when called. So basically, you are getting a fresh object, and the onTypeText() is reinitialized. onActivityResult() is basically a callback from your previous activity.
Your onClick() is not being called due you don't assign clicklistener to R.id.faboptions_favorite and the other View
in onCreate add :
findViewById(R.id.faboptions_favorite).setOnClickListener(this);
and same for the other view.

How to acess image path from onActivityResult method to AsyncTask doInBackground method in Android?

I am selecting an image from gallery in onActivityResult method and I can get image path in this method. Now I want to upload this image in servlet and this uploading task, I want to do in AsyncTask doInBackground method, but I can not access image path from onActivityResult to doInBackGround method.
I don't know how to achieve this. I am putting my code here:
public class Photos extends ActionBarActivity {
private static final int REQUEST_ID = 1;
private static final int HALF = 6;
Button mUpload;
ImageView mPhoto;
Button mDoUpload;
Intent data;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
mPhoto = (ImageView) findViewById(R.id.uploaded_photo);
mUpload = (Button) findViewById(R.id.btn_photoshare);
mDoUpload = (Button) findViewById(R.id.btn_upload);
mUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_ID);
}
});
mDoUpload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
InputStream stream = null;
if(requestCode == REQUEST_ID && resultCode == Activity.RESULT_OK)
{
try
{
stream = getContentResolver().openInputStream(data.getData());
//System.out.println(data.getData());
Bitmap original = BitmapFactory.decodeStream(stream);
((ImageView)findViewById(R.id.uploaded_photo)).setImageBitmap(Bitmap.createScaledBitmap(original, original.getWidth()/HALF,
original.getHeight()/HALF, true));
String path = getRealPathFromURI(getApplicationContext(), data.getData());
System.out.println(path);
}
catch(Exception ex)
{
ex.printStackTrace();
}
if(stream != null)
{
try
{
stream.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
public String getRealPathFromURI(Context context,Uri contentUri)
{
Cursor cursor = null;
try
{
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
// System.out.println(cursor.getString(column_index));
return cursor.getString(column_index);
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
private class sendFile extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
HttpURLConnection httpConn=null;
try
{
File uploadFile = new File(path);
//here I dont know how to access selected image path
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
}
That's because you made path a local variable of onActivityResult(). Make it a variable of your activity. Change String path = getRealPathFromURI(.. to path = getRealPathFromURI(... And declare String path=""; in the activity.

KiiObject Upload Picture to use for profile

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

Categories

Resources