I need help with my issue of saving a picture . I am using adobe photo sdk to edit my image. Documentation link(https://creativesdk.adobe.com/docs/android/#/articles/imageediting/index.html). They say use .withOutput(Uri) to save the image which i created but get my image with an error.
public class MainActivity extends AppCompatActivity {
private static final int IMG_CODE_EDIT = 263;
private Button mPickbtn;
private Button mCapturebtn;
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPickbtn = (Button) findViewById(R.id.pick_image);
mCapturebtn = (Button) findViewById(R.id.button2);
Intent cdsIntent = AdobeImageIntent.createCdsInitIntent(getBaseContext(), "CDS");
startService(cdsIntent);
}
public void takePicture(View view) {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Gets the gallery image uri
if (requestCode == RESULT_LOAD_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();
editPic(selectedImage);
}
//picture from camera
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Uri mPicTaken = data.getData();
editPic(mPicTaken);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
if (resultCode == RESULT_OK) {
switch (requestCode) {
/* 4) Make a case for the request code we passed to startActivityForResult() */
case 263:
/* 5) Show the image! */
Uri editedImageUri = data.getData();
Intent intent = new Intent("com.ayyogames.photoapp.Share");
intent.putExtra("imageUri", editedImageUri);
startActivity(intent);
break;
}
}
}
public void editPic(Uri uri) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.ayyogames.photoapp.fileprovider",
photoFile);
Intent intent = new AdobeImageIntent.Builder(this)
.setData(uri)
.withOutputSize(MegaPixels.Mp10)
.withOutputQuality(100)
.withOutput(photoURI)
.build();
startActivityForResult(intent, IMG_CODE_EDIT);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Share Class
public class Share extends AppCompatActivity {
private ImageView mEditedImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
mEditedImageView = (ImageView) findViewById(R.id.editedImageView);
Intent intent = getIntent();
Uri uri = intent.getParcelableExtra("imageUri");
mEditedImageView.setImageURI(uri);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu,menu);
return true;
}
}
The Image Editor developer guide currently says that you should pass a Uri to withOutput(), but this is incorrect.
Try passing a File:
/* 1) Change the argument to your desired location */
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
.setData(imageUri)
.withOutput(file) /* 2) Pass the File here */
.build();
Your argument to the File constructor should be altered to whatever location you desire.
Related
I have an app in which I try to capture user images from camera and also from gallery. The image capture works fine and the image is visible in the ImageView but when I restart the app the image disappears as if it wasn't saved.
public class MainActivity extends AppCompatActivity {
ImageView imageView;
int REQUEST_CAMERA =1;
int SELECT_FILE = 0;
public String photoFileName;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = findViewById(R.id.imageView);
final FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
selectImage();
}
});
}
public void selectImage(){
final CharSequence [] items = {"Camera","Gallery","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#SuppressLint("IntentReset")
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_CAMERA);
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
"Photo file can't be created, please try again",
Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
"com.example.android.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
}else if (items[i].equals("Gallery")){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent,"Select File"),SELECT_FILE);
galleryAddPic();
}else if (items[i].equals("Cancel")){
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA && resultCode == Activity.RESULT_OK){
Bundle bundle = null;
if (data != null) {
bundle = data.getExtras();
}
Bitmap bitmap = null;
if (bundle != null) {
bitmap = (Bitmap) bundle.get("data");
}
imageView.setImageBitmap(bitmap);
}else if (requestCode == SELECT_FILE){
Uri uri = data.getData();
imageView.setImageURI(uri);
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(String.valueOf(photoFile));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
photoFileName = image.getAbsolutePath();
return image;
}
}
While restart the app image is not showing becuase of all variable initialize again, for showing that you have to store it path locally.
In my activity onCreate I set a onCheckedChangeListener to a radio group.
At some point I need to programmatically uncheck any checked radio button within the radio group so I unset the listener, uncheck the button, and set the listener back to prevent it from firing when programmatically unchecking the button.
When first checking the radio button, it takes a photo trough an intent. In the onActivityResult part, I uncheck the button if the user didn't take a photo. After doing this, the radio button unchecks itself whenever it's checked. How can I fix this problem?
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_vestuarios);
instanciar_objetos();
instanciar_listeners();
}
private void instanciar_objetos(){
ctx = getApplicationContext();
rg_1 = findViewById(R.id.radio_1_1);
}
private void instanciar_listeners(){
listener_radio_groups = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
last_rg = radioGroup;
seleccionar_radio((RadioButton) findViewById(last_rg.getCheckedRadioButtonId()));
}
};
rg_1.setOnCheckedChangeListener(listener_radio_groups);
}
private void seleccionar_radio(RadioButton rb){
String tag = (String) rb.getTag();
String[] s = tag.split("_");
seccion = s[0];
item = s[1];
radio = s[2];
if(radio.equalsIgnoreCase("1")){
//MARCÓ SI, MANDARLE CON LA FOTO
fotografia();
}
else{
//MARCO OTRA OPCION, PEDIR TEXTO
}
}
public void fotografia(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
try{
Uri photoURI = FileProvider.getUriForFile(ctx,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 1);
}
catch (Exception e){
e.printStackTrace();
}
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String imageFileName = timeStamp;
String root = Environment.getExternalStorageDirectory().toString() + "/hrtech/hites/originales";
File storageDir = new File(root, "/"+seccion+"/"+item);
storageDir.mkdirs();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
// Show the thumbnail on ImageView
Uri imageUri = Uri.parse(mCurrentPhotoPath);
final File file = new File(imageUri.getPath());
// ScanFile so it will be appeared on Gallery
MediaScannerConnection.scanFile(ctx,
new String[]{imageUri.getPath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
else{
Toast.makeText(ctx,"Obligatoriamente debe tomar una foto para marcar \"SI\" en este ítem.",Toast.LENGTH_LONG).show();
last_rg.setOnCheckedChangeListener(null);
RadioButton aux = (RadioButton) findViewById(last_rg.getCheckedRadioButtonId());
aux.toggle();
last_rg.setOnCheckedChangeListener(listener_radio_groups);
}
}
i have a radio button. when i click on radio button camera intent is opened after taking a image using camera. image is not updating to image view.
i have used all permissions in my manifest file.
RB_PhotoStatus
.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
switch (checkedId) {
case R.id.yes:
//photoCollected = "Yes";
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
break;
case R.id.no:
photoCollected = "No";
break;
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(bp);
}
Taking Photos Simply!
This answer explains how to capture photos using an existing camera application.
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
</manifest>
Request for camera application.
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
Camera return intent with data on Activity override function onActivityResult as bellow:-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
For more info follows this link given bellow:
http://developer.android.com/training/camera/photobasics.html
It doesn't work because Camera Intent won't return the entire BitMap, but only the reference (Uri) to the created file.
Uri selectedImage = data.getData();
From this Uri you may re-load the BitMap using BitmapFactory.decodeFile
On radiobuttonclick();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
onActivityResult();
Uri originalUri = data.getData();
imageview.setImageURI(originalUri);
And If you want to get bitmap then
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), originalUri);
private String mCurrentPhotoPath;
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
final File image = create_directory();
// Save a file: path for use with ACTION_VIEW intents
try {
mCurrentPhotoPath = image.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (image != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
snackbar = Snackbar.make(findViewById(android.R.id.content), "An error has occurred", Snackbar.LENGTH_SHORT);
snackbar.setAction("Dismiss", clickListener);
snackbar.show();
}
}
}
public File create_directory() {
// Create an image file name
final String imageFileName;
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
final String user_id = "1_";
imageFileName = user_id + timeStamp + "_";
final String proj_name = "test";
final String folder_timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).format(new Date());
final String path = "/TEST/" + proj_name + "/" + folder_timeStamp;
final File dr = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), path);
if (!dr.exists()) {
dr.mkdirs();
}
File image = null;
try {
image = File.createTempFile(imageFileName, ".jpg", dr);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
//do something with the image which is stored in mCurrentPhotoPath
}
}
}
I am having a NullPointerException in my android code on this section
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
The exception is on the line
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
audioRecordPasser is an interface.
The complete code implementation is
public class UploadFragment extends DialogFragment implements AdapterView.OnItemSelectedListener, View.OnClickListener {
Spinner genres;
ImageView photo;
TextView submit;
String fileName = "";
EditText titleEt, descriptionEt;
private static final String KEY = "choice";
public Uri fileUri; // file url to store image/video
OnAudioRecordPass audioRecordPasser;
public UploadFragment(){
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_upload, null);
builder.setView(v);
submit = (TextView) v.findViewById(R.id.upload_textView_submit);
genres = (Spinner) v.findViewById(R.id.upload_spinner_genre);
photo = (ImageView) v.findViewById(R.id.upload_imageView_photo);
titleEt = (EditText) v.findViewById(R.id.upload_edittext_title);
descriptionEt = (EditText) v.findViewById(R.id.upload_editText_description);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.ngoma_spinner, getResources().getStringArray(R.array.genres));
dataAdapter
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
genres.setAdapter(dataAdapter);
genres.setOnItemSelectedListener(this);
submit.setOnClickListener(this);
photo.setOnClickListener(this);
return builder.create();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private static final int INT_CODE = 1;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.upload_textView_submit:
Log.i("URI", fileUri.getPath());
// audioRecordPasser.onAudioRecordPass(titleEt.getText().toString(),"hiphop",descriptionEt.getText().toString(),fileUri.getPath());
if (validateInput()==false){
Toast.makeText(getActivity(),"Fields cannot be blank.",Toast.LENGTH_SHORT).show();
}
else {
String title = titleEt.getText().toString();
String description = descriptionEt.getText().toString();
Log.i("title",title);
Log.i("description",description);
audioRecordPasser.onAudioRecordPass(title, "hiphop", description, fileUri.getPath());
getDialog().dismiss();
}
break;
case R.id.upload_imageView_photo:
UploadPhotoDialog uploadDialog = new UploadPhotoDialog();
uploadDialog.setTargetFragment(this, INT_CODE);
uploadDialog.show(getActivity().getSupportFragmentManager(), "uploadPhoto");
break;
}
}
/**
* **************************************************************************************************
*/
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static int RESULT_LOAD_IMAGE = 1;
/**
* Select image from gallery
*/
private void selectFromGallery() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "ngoma";
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get the file url
//fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity().getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
fileUri = selectedImage;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// String picturePath contains the path of selected Image
previewFromGallery(picturePath);
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
Log.i("previewCapturedImage", fileUri.getPath());
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void previewFromGallery(String picturePath) {
photo.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
fileUri = Uri.fromFile(getOutputMediaFile(type));
Log.i("getOutputMediaFileUri", fileUri.getPath());
return fileUri;
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Error creating "
+ IMAGE_DIRECTORY_NAME + " directory.");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
public void choiceSelector(String data) {
if (data.equalsIgnoreCase("camera")) {
captureImage();
} else if (data.equalsIgnoreCase("gallery")) {
selectFromGallery();
}
}
public interface OnAudioRecordPass {
public void onAudioRecordPass(String title, String genre, String description, String photouri);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
audioRecordPasser = (OnAudioRecordPass) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnAudioRecordPass");
}
}
private boolean validateInput() {
if (titleEt.getText().toString().equalsIgnoreCase("") || descriptionEt.getText().toString().equalsIgnoreCase("")) {
return false;
} else {
return true;
}
}
}
Everything runs fine.In my logcat, I can see the values of title and desription and fileUri.getPath() variables.What could be the issue?
The logcat content
10-31 15:42:44.032 4101-4101/ngoma.android.shimba.com.ngoma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.shimba.android.ngoma.activities.MainActivity.onAudioRecordPass(MainActivity.java:516)
at com.shimba.android.ngoma.fragments.UploadFragment.onClick(UploadFragment.java:101)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4440)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
The problem is with the parameter fileUri.getPath()
May be this is not properly initialized and as a result its value is null
Check the value of fileUri variable value before passing it to the function.
This will solve your problem
hello Friends....
I am currently trying to make a Dialog using Implicit Intent where i want to show my Dialog like whatsApp(Profile Photo Screen) and in this screen whatsApp are using extra field named as "Remove Photo". When i try to make same type of screen Dialog then i am unable to add this extra field("Remove Photo"). i have done all code. its working fine for three option in Dialog like(Gallery,Photo,Camera) and i am unable to handle these all in onActivityResult() . I am sending my all source code i have tried much hard , but i am not able to find the solution to do so. plz..... friends help me out from this.
In this code i am simply create a method named as openFileChooser() in which i have write all the code for creating Dialog Screen and handle this outcomes in onActivityResult()
Here Is my code
ProfilePhotoActivity.java
public class ProfilePhotoActivity extends Activity implements OnClickListener{
ImageButton back, editPhoto, selectAction;
ImageView imgCamera;
private static final int FILECHOOSER_RESULTCODE = 2888;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Uri mCapturedImageURI = null;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_profilephoto);
back=(ImageButton)findViewById(R.id.btn_back);
editPhoto=(ImageButton)findViewById(R.id.ibEditPhoto);
selectAction=(ImageButton)findViewById(R.id.ibSelectAction);
imgCamera=(ImageView)findViewById(R.id.imvProfilePhoto);
editPhoto.setOnClickListener(this);
selectAction.setOnClickListener(this);
back.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_back:
ProfilePhotoActivity.this.finish();
break;
case R.id.ibEditPhoto:
openFileChooser(null, null);
// startDialog();
break;
case R.id.ibSelectAction:
break;
}
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
try{
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_PICK);
// i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Exception:"+e,
Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (requestCode == GALLERY_PICTURE)
{
if (resultCode == RESULT_OK)
{
if (intent != null)
{
// our BitmapDrawable for the thumbnail
BitmapDrawable bmpDrawable = null;
// try to retrieve the image using the data from the intent
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileSrc = cursor.getString(idx);
Bitmap galleryBitmap = BitmapFactory.decodeFile(fileSrc); // load preview image
galleryBitmap = Bitmap.createScaledBitmap(galleryBitmap, 200, 200, true);
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/TimeChat/image/"+System.currentTimeMillis()+".jpg";
//imgCamera.setRotation(0);
imgCamera.setImageBitmap(galleryBitmap);
// writeToFile(filePath, galleryBitmap);
}
else
{
bmpDrawable = new BitmapDrawable(getResources(), intent.getData().getPath());
imgCamera.setImageDrawable(bmpDrawable);
}
}
else
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
else if (requestCode == CAMERA_REQUEST)
{
if (resultCode == RESULT_OK)
{
if (intent.hasExtra("data"))
{
// retrieve the bitmap from the intent
Bitmap cameraBitmap = (Bitmap) intent.getExtras().get("data");
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/TimeChat/image/"+System.currentTimeMillis()+".jpg";
// update the image view with the bitmap
imgCamera.setImageBitmap(cameraBitmap);
// writeToFile(filePath, circleBitmap);
}
else if (intent.getExtras() == null) {
Toast.makeText(getApplicationContext(), "No extras to retrieve!", Toast.LENGTH_SHORT).show();
BitmapDrawable thumbnail = new BitmapDrawable(getResources(), intent.getData().getPath());
// update the image view with the newly created drawable
imgCamera.setImageDrawable(thumbnail);
}
}
else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
ProfilePhotoActivity.this.finish();
}
}
This looks like it will be a problem:
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (requestCode == GALLERY_PICTURE)
unless FILECHOOSER_RESULTCODE and GALLERY_PICTURE are the same ints then statement will never pass.
It may be possible to use request code to distinguish between "types" of photos i.e.
protected static final int MY_FACE_PHOTO = 0;
protected static final int MY_CAR_PHOTO = 1;
protected static final int MY_HOUSE_PHOTO = 2;
And you may use Intent.putExtra(String name, String value) when you create Intents before starting new activity, like:
#NonNls protected static final String STRING_EXTRA = "string_extra";
#NonNls protected static final String CAMERA = "camera";
#NonNls protected static final String GALLERY = "gallery";
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
cameraIntent.putExtra(STRING_EXTRA, CAMERA);
galleryIntent.putExtra(STRING_EXTRA, GALLERY)
startActivityForResult(takePicture,
MY_FACE_PHOTO /* put here your desired request code */)
After that in onActivityResult() method you may use them:
protected void onActivityResult (int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(intent != null)
{
if(resultCode == Activity.RESULT_OK)
{
String extraString = intent.getStringExtra(STRING_EXTRA);
if(extraString.equals(CAMERA))
{
// ... i. e.
switch (requestCode)
{
case MY_FACE_PHOTO:
{
// ...
break;
}
case MY_CAR_PHOTO:
{
// ...
break;
}
case MY_HOUSE_PHOTO:
{
// ...
break;
}
default:
{
// ...
break;
}
}
}
else if(extraString.equals(GALLERY))
{
// ...
}
}
else
{
// ...
}
}
}