I have two activities, TakePictureActivity and ChoosePicActivity, and they both lead to PuzzleActivity.
As you can see, 1st activity starts an intent to start the camera, allows you to take a picture and starts the PuzzleActivity.
The 2nd activity accesses to the gallery, allows you to choose a picture and starts the PuzzleActivity.
In the PuzzleActivity the method createScaledBitmap is called to generate a bitmap.
Here is TakePictureActivity:
public class TakePictureActivity extends Activity {
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
public static final int DIALOG_PICASA_ERROR_ID = 0;
private static String DEBUG_TAG1 = "TakePictureA";
private Bitmap bitmap;
public static Uri imageUri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.takepicture);
dispatchTakePictureIntent();
}
//TODO createImageFile
/* (non-Javadoc)
* Creates a file for the picture with a collision-resistant name using date-time stamp.
* Additionally, it saves the path to the picture in a member variable, mCurrentPhotoPath.
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(0));
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
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();
Log.d(DEBUG_TAG1,"Current photo Path" + mCurrentPhotoPath);
galleryAddPic();
return image;
}
//TODO dispatchTakePictureIntent
/* (non-Javadoc)
* Starts an intent for the camera application.
*/
private void dispatchTakePictureIntent() {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (i.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
Log.d(DEBUG_TAG1,"try create iamge file");
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d(DEBUG_TAG1,"error");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.d(DEBUG_TAG1,"photo file not null");
i.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(i, REQUEST_TAKE_PHOTO);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
#Override
protected final void onActivityResult(final int requestCode, final int resultCode, final Intent i) {
//super.onActivityResult(requestCode, resultCode, i);
if (resultCode == RESULT_OK) {
Log.d(DEBUG_TAG1,"TakePicture onActivityResult ");
switch (requestCode) {
case REQUEST_TAKE_PHOTO:
imageUri = i.getData();
Log.d(DEBUG_TAG1,"intent take pic: " + i);
Intent i1 = new Intent(this, PuzzleActivity.class);
startActivity(i1);
break;
} // end switch
} // end if
}
}
And here is ChoosePicActivity:
public class ChoosePicActivity extends Activity {
String mCurrentPhotoPath;
public static final int IMAGEREQUESTCODE = 8242008;
static final int REQUEST_TAKE_PHOTO = 1;
public static final int DIALOG_PICASA_ERROR_ID = 0;
private static String DEBUG_TAG1 = "ChoosePicA";
private Bitmap bitmap;
public static Uri imageUri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
selectImageFromGallery();
}
/* (non-Javadoc)
* Will start an intent for external Gallery app.
* Image returned via onActivityResult().
*/
private void selectImageFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, IMAGEREQUESTCODE);
}
//TODO onActivityResult
/* (non-Javadoc)
* Run when Gallery app returns selected image.
*/
#Override
protected final void onActivityResult(final int requestCode, final int resultCode, final Intent i) {
//super.onActivityResult(requestCode, resultCode, i);
if (resultCode == RESULT_OK) {
Log.d(DEBUG_TAG1,"ChoosePic onActivityResult ");
switch (requestCode) {
case IMAGEREQUESTCODE:
imageUri = i.getData();
Log.d(DEBUG_TAG1,"intent choose pic: " + i);
Intent i1 = new Intent(this, PuzzleActivity.class);
startActivity(i1);
break;
} // end switch
} // end if
}
}
And here is the PuzzleActivity:
public final class PuzzleActivity extends Activity implements OnClickListener{
private Bitmap bitmap; // temporary holder for puzzle picture
public static Chronometer chrono;
static TextView tv1;
static EditText et1;
Button button;
private static Context mContext;
//TODO onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.board);
mContext = this;
tv1 = (TextView) findViewById(R.id.movecount_display);
if(DecidePicActivity.choosepic){
try {
bitmap = createScaledBitmap(ChoosePicActivity.imageUri);
} catch (FileNotFoundException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
} catch (IOException e) {
e.printStackTrace();
finish();
} catch (IllegalArgumentException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
}
createGameBoard(getGridSize());
}
else if(DecidePicActivity.takepic){
try {
bitmap = createScaledBitmap(TakePictureActivity.imageUri);
} catch (FileNotFoundException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
} catch (IOException e) {
e.printStackTrace();
finish();
} catch (IllegalArgumentException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
}
createGameBoard(getGridSize());
}
TileView.moveDetector = new GestureDetectorCompat(this, new MyGestureListener());
Button pauseButton = (Button) findViewById(R.id.pause_button);
pauseButton.setOnClickListener(this);
}
The issue is:
I get to ChoosePicActivity, I choose a pic from the gallery, start intent to go to PuzzleActivity and creates the scaled bitmap with the chosen picture.
All good until here.
then, PuzzleActivity gets finished and i get to TakePictureActivity, camera starts, i take a pic, start intent to go PuzzleActivity and THEN the scaled bitmap generated uses the image previously chosen in the ChoosePicActivity, leaving the recently taken picture behind, which is the picture that it should have been used to generate the scaled bitmap.
On the other hand, if TakePictureActivity is started without ChoosePicActivity previously started, the taken picture is used to generate the scaled bitmap, as expected.
I hope I explained myself enough good for you to understand my problem. Could somebody give some light?
I'm not sure if having 2 times the method onActivityResult is correct, or if there are different threads conflicting, or maybe the method i.getdata() is having trouble to get the proper Intent id... I'm a bit lost.
The problem was caused by DecidePicActivity.choosepic and DecidePicActivity.takepic.
Previously, DecidePicActivity activity was like this:
public class DecidePicActivity extends Activity implements OnClickListener{
static boolean takepic = false;
static boolean choosepic = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.decidepic);
findViewById(R.id.take_pic_button).setOnClickListener(this);
findViewById(R.id.choose_pic_button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.take_pic_button:
takepic = true;
Intent i1 = new Intent(this, TakePictureActivity.class);
startActivity(i1);
break;
case R.id.choose_pic_button:
choosepic = true;
Intent i2 = new Intent(this, ChoosePicActivity.class);
startActivity(i2);
break;
}
}
}
takepic and choosepic they were not properly reinitialized.
Now onClick in DecidePicActivity activity is like this:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.take_pic_button:
takepic = true;
choosepic = false;
Intent i1 = new Intent(this, TakePictureActivity.class);
startActivity(i1);
break;
case R.id.choose_pic_button:
choosepic = true;
takepic = false;
Intent i2 = new Intent(this, ChoosePicActivity.class);
startActivity(i2);
break;
}
}
and problem solved!
Related
I have a tabLayout with ImageView and when I Pick A image from the gallery and display it to Imageview then when I close the app the selected image is gone then I need to pick an image again.
And I know this one looks the same as my question but still not working
saving image picked from gallery for future use
I tried this code but the image still disappeared
https://github.com/martinsing/Image-Save-And-Retrieve-App
I also Read this other question but no one works
Image in ImageView disappear
public class FirstFragment extends Fragment implements View.OnClickListener{
ImageView imageButton1;
ImageButton imageButton2;
private Uri mImageUri;
private File mSnapFile;
private static final String ARG_URI_IMAGE_1 = "image1Uri";
private static final String ARG_URI_IMAGE_2 = "image2Uri";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_first, container, false);
imageButton1 = (ImageView) v.findViewById(R.id.firstimagebtn);
imageButton2 = (ImageButton)v.findViewById(R.id.secondimagebtn);
imageButton1.setOnClickListener(this::onClick);
imageButton2.setOnClickListener(this::onClick);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
imageButton2.setImageURI(Uri.parse(mImageUri));
} else {
imageButton2.setImageResource(R.mipmap.ic_launcher);
}
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.firstimagebtn:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,0);
break;
case R.id.secondimagebtn:
Intent intent2 = new Intent(Intent.ACTION_PICK);
intent2.setType("image/*");
startActivityForResult(intent2,1);
break;
}
}
private void handleImageSelect(#Nullable Intent intent) {
if (saveContentLocally(intent)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(mSnapFile));
imageButton1.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
throw new IllegalStateException("Saved the image file, but it doesn't exist!");
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 0:
if(resultCode == Activity.RESULT_OK){
handleImageSelect(data);
}
break;
case 1:
if(resultCode == Activity.RESULT_OK){
mImageUri = data.getData();
// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(mImageUri));
editor.commit();
// Sets the ImageView with the Image URI
imageButton2.setImageURI(mImageUri);
imageButton2.invalidate();
}
break;
}
}
/**
* Saves the file from the ACTION_PICK Intent locally to {#link #mSnapFile} to be accessed by our FileProvider
*/
private boolean saveContentLocally(#Nullable Intent intent) {
if (intent == null || intent.getData() == null) {
return false;
}
InputStream inputStream;
try {
inputStream = getActivity().getContentResolver().openInputStream(intent.getData());
} catch (FileNotFoundException e) {
Toast.makeText(getActivity(), "Could not open file", Toast.LENGTH_SHORT).show();
return false;
}
if (inputStream == null) {
Toast.makeText(getActivity(), "File does not exist", Toast.LENGTH_SHORT).show();
return false;
}
try {
copyFile(inputStream, mSnapFile);
} catch (IOException e) {
Toast.makeText(getActivity(), "Failed save file locally", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private static void copyFile(InputStream inputStream, File file) throws IOException {
byte[] buffer = new byte[1024];
int length;
try (FileOutputStream outputStream = new FileOutputStream(file)) {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
}
Do not use ACTION_PICK as then the obtained uri is not valid anymore after restart.
Instead use ACTION_OPEN_DOCUMENT and take persistable uri permissions in onActivityResult.
I'm now making a simple android app. It's just allow user to take an Photo and then show it.
When i test it in Virtual device, it's ok. But when i download apk to my android device, after i take a photo in Back camera, the app has stopped and return to main menu. Just problem in Back Camera.
In addition, in virtual device, after taking photo, the photo will show successfully. But it's empty in my phone
In MainActivity, i click on "Take Photo", it will start the camera and same my image to folder. Then it send the path of Photo to the next activity and show it.
This is my MainActivity
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ID_IMAGE_CAPTURE = 100;
Button TakePhoto, InsertPhoto, Exit;
String mCurrentPhotoPath;
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,".jpg",storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TakePhoto = (Button) findViewById(R.id.button);
InsertPhoto = (Button) findViewById(R.id.button3);
Exit = (Button) findViewById(R.id.button2);
//Start Camera
TakePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
System.out.println(ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = Uri.fromFile(photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent,REQUEST_ID_IMAGE_CAPTURE);
}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ID_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
//Bitmap bp = (Bitmap)data.getExtras().get("data");
//ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bp.compress(Bitmap.CompressFormat.PNG, 100, stream);
// byte[] images = stream.toByteArray();
File imgFile = new File(mCurrentPhotoPath);
if(imgFile.exists()){
System.out.println("This is file"+mCurrentPhotoPath.toString());
Intent Show = new Intent(MainActivity.this, ShowPhoto.class);
Show.putExtra("image",imgFile);
startActivity(Show);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Action canceled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Action Failed", Toast.LENGTH_LONG).show();
}
}
}
}
This is The ShowPhoto Activity
public class ShowPhoto extends Activity {
private LinearLayout Image;
Button Back,Next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_photo);
Image=(LinearLayout)findViewById(R.id.linearLayout);
//Get Image from previous Activity
File image = (File)getIntent().getExtras().get("image");
Bitmap bmp = BitmapFactory.decodeFile(image.getAbsolutePath());
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, bmp.getWidth()*2, bmp.getHeight()*2, true));
Image.addView(imageView);
}
}
This is what's in my logcat when i run app
enter image description here
enter image description here
Use should ask for the permission at runtime and declare the permission in Manifest
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)
getContext(), Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
For your Manifest
<uses-permission android:name="android.permission.CAMERA"/>
I am making an app in which a feature that user can upload images and video to server
it was working well on activity but now I want to use it in a fragment. I try to code effectively, efficiently and I am not getting any error during compiling and my app runs successfully but when I click on fragment it shows "unfortunately app has stopped " and in log cat I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
and its points this line:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this line ➦ fileUri = savedInstanceState.getParcelable("file_uri");
}
i don't know whats wrong
my code:
public class TabFragment4 extends Fragment implements View.OnClickListener{
View parentHolder;
private static final String TAG = MainActivity.class.getSimpleName();
int req_code = 100;
int video_code = 20;
String path;
Uri selectedImageUri;
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 10;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Context mContext;
private Uri fileUri; // file url to store image/video
private ImageButton btnCapturePicture, btnRecordVideo,gallerybtn , videobtn,b1,location;
public TabFragment4() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentHolder = inflater.inflate(R.layout.fragment_tab_fragment4, container, false);
final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use Location Service ?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
// Call your Alert message
}
btnCapturePicture = (ImageButton)parentHolder.findViewById(R.id.btnCapturePicture);
btnRecordVideo = (ImageButton)parentHolder. findViewById(R.id.btnRecordVideo);
gallerybtn=(ImageButton)parentHolder.findViewById(R.id.imagegallery);
videobtn = (ImageButton)parentHolder.findViewById(R.id.videogallery);
location=(ImageButton)parentHolder.findViewById(R.id.location);
videobtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
video();
}
});
gallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
galleryimage();
}
});
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
captureImage();
}
});
/**
* Capture image button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
return parentHolder;
}
public void video(){
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), video_code);
}
public void galleryimage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), req_code);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
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);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
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
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == req_code) {
selectedImageUri = data.getData();
if (resultCode ==Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(true);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == video_code) {
selectedImageUri = data.getData();
if (resultCode == Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(false);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
//successfully captured the image
// launching upload activity
launchUploadActivity(true);
//Intent intent = new Intent(this,UploadActivity.class);
//startActivity(intent);
} else if (resultCode ==Activity. RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getActivity(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getActivity(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
private void launchUpload(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", path);
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.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 if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public void onClick(View v) {
}
}
Uri imageUri = data.getData();
Bitmap bitmap= null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
Seems savedInstanceState == null so use something like this:
if (savedInstanceState != null) {
fileUri = savedInstanceState.getParcelable("file_uri");
} else {
fileUri = ??? - what You want do to in else case;
}
This is my code i capture image and share successfully but can't upload video
public class CaptureActivity extends AppCompatActivity {
ShareButton shareButton;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapture;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
private static final String IMAGE_DIRECTORY_NAME = "CityApp";
static File mediaFile;
static File mediaStorageDir;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
imgPreview = (ImageView) findViewById(R.id.imageView);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapture = (Button) findViewById(R.id.btn_Capture);
shareButton = (ShareButton) findViewById(R.id.fb_share_button);
// shareButton.setFragment(this);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishImage();
// publishVideo();
}
});
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Tack Video", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CaptureActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
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);
} else if (options[item].equals("Tack Video")) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren 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");
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
public static File getOutputMediaFile(int type) {
// External sdcard location
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! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void publishImage() {
// statusUpdates= new ContactsContract.StatusUpdates(getActivity().getApplicationContext());
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("Testing with android")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
shareButton.setShareContent(content);
}
public void publishVideo() {
Uri videoFileUri = fileUri;
ShareVideo shareVideo = new ShareVideo.Builder()
.setLocalUrl(videoFileUri)
.build();
ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(shareVideo)
.build();
shareButton.setShareContent(content);
}
}
i want use compile 'com.facebook.android:facebook-android-sdk:4.1.0' this library thanks in advance
i want to load image that taken from galllery and camera, when user click on capture button, image will be capture from camera phone device, when user click on add_gallery button, image will be taken from gallery, my problem is when i choose an image from gallery, it is not display on my activity (on My ImageView named by foto_dp).
this is my code :
#Override
public void onClick(View arg0) {
switch (arg0.getId()){
break;
case R.id.capture_dp:
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, TAKE_PHOTO_CODE);
break;
case R.id.add_galery_dp:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(i, PICK_FROM_GALLERY);
break;
case R.id.delete_image_dp:
break;
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() +"/android/data/spaj_foto/spaj_foto("+counter+").png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == TAKE_PHOTO_CODE) {
selectedImagePath = getImagePath();
foto_dp.setImageBitmap(decodeFile(selectedImagePath));
if (requestCode == PICK_FROM_GALLERY) {
selectedImagePath = getImagePath();
foto_dp.setImageBitmap(decodeFile(selectedImagePath));
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
is there anywrong with my code? and how to delete image with a button on my activity? i hope someone can help me to solve my problem, thank you
You do not need to decode file. Try following code
private final int REQUEST_CODE_CAMERA_IMAGE = 1000;
private final int REQUEST_CODE_EXTERNAL_IMAGE = 2000;
//select picture from external storage
btnChoosePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// choose picture from gallery
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,
REQUEST_CODE_EXTERNAL_IMAGE);
}
});
//take picture from camera
btnTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// start camera to take picture
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent,
REQUEST_CODE_CAMERA_IMAGE);
}
});
Display image like this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// get image from camera
case REQUEST_CODE_CAMERA_IMAGE:
if (resultCode == Activity.RESULT_OK) {
imageView.setImageUri(setImageUri());
}
break;
// get image from external storage
case REQUEST_CODE_EXTERNAL_IMAGE:
if (resultCode == Activity.RESULT_OK) {
imageView.setImageUri(data.getData());
}
break;
default:
break;
}
}
To delete image
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(imagePath);
if(file.exist())
file.delete();
}
});
When you get image url from gallery, just delete it like file
button.setOnClickListener(deleteListener);
OnClickListener deleteListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File file = new File(imagePath);
file.delete();
}
};
Show image use imageview