How to get the selected video path? - android-studio

this code below uploads the recorded video to server
All what i want to do is : I just want to upload video from Galery.
I have added new Button to load video from Storage, the code can play the selected video in Viedeoview.
After that I try to get the filePath like below but i did not get it correctly :
public void Load_Video(View view) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 99 );
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case 99:
Uri mVideoCaptureUri = data.getData();
vidPreview.setVideoURI(mVideoCaptureUri);
vidPreview.start();
filePath=mVideoCaptureUri.toString();
Toast.makeText(Main.this, "filePath : " +filePath, Toast.LENGTH_SHORT).show();
break;
}
}
source : Source of complet demo here :
After I have selected a video from gallery, how to get the path ?

Related

Unable to set image in ImageView using fragment

I am developing an app using fragment, I am facing problem in setting the image in ImageView by capturing image from camera. Image is been stored in the location the only problem is image not set on the ImageView. Same code is running in activity but facing problem in fragment. Kindly help
//To capture image on button click
imgAddCameraImageQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if system OS is >= marshmallow, request runtime permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ){
if(ContextCompat.checkSelfPermission(getContext(),Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED ||
ContextCompat.checkSelfPermission(getContext(),Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
//Permission not enable, request it
String [ ] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permission
requestPermissions(permission,PERMISSION_CODE);
}
else{
//Permission is granted
openCamera();
}
}
else{
//System OS < Marshmallow
openCamera();
}
}
});
private void openCamera() {
Context applicationContext = MainActivity.getContextOfApplication();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION,"From the Camera");
image_uri = applicationContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
//Camera Intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,image_uri);
startActivityForResult(cameraIntent,IMAGE_CAPTURE_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//Called when image was captured from camera
if(resultCode == Activity.RESULT_OK){
imgQuestion.setImageURI(image_uri);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//this method is called, when user presses Allow or Deny from permission popup
switch(requestCode){
case PERMISSION_CODE: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//permission from popup was granted
openCamera();
}
else{
//permission from popup denied
StyleableToast.makeText(getContext(),"Permission Denied",R.style.errorToast).show();
}
}
}
}

My app crashes after i try upload image from gallery

I try upload image from gallery with this code:
public void oc_chooseImage(View view) {
Intent intent = new Intent ( );
intent.setType ( "image/*" );
intent.setAction ( Intent.ACTION_GET_CONTENT );
startActivityForResult (intent,1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult ( requestCode, resultCode, data );
if(requestCode == 1 && resultCode==RESULT_OK && data != null && data.getData () != null)
{
imageUri = data.getData ();
mv_logo.setImageURI ( imageUri );
nav_logo.setImageURI ( imageUri );
}
}
What can be the problem? my minimum version in android studio is 19 api, i try run my app with my phone and the gallery just crashes and stops my app.
My app run very slowly or crashes when i try to upload big images.

How to upload file to firebase storage from sd card

This is my code. i tried to upload file from my sd card to firebasae storage but it throwing "An unknown error occurred. Please check the HTTP result code and inner exception for server response." i have checked many solution but nothing worked for me. so please help me to fix this issue.
//upload file
private void uploadFile() throws FileNotFoundException {
if (fileuri != null) {
//displaying a progress dialog while upload is going on
final ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Uploading....");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setCancelable(true);
progress.setProgress(0);
progress.show();
StorageReference riversRef = storageReference.child("path");
riversRef.putFile(fileuri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successfull
//hiding the progress dialog
progress.dismiss();
//and displaying a success toast
Intent intent = new Intent(UploadActivity.this, hanksActivity.class);
startActivity(intent);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successfull
//hiding the progress dialog
progress.dismiss();
//and displaying error message
Toast.makeText(getApplicationContext(), exception.getMessage(),
Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>
() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
#SuppressWarnings("VisibleForTests")
double progresstime = (100.0 * taskSnapshot.getBytesTransferred()) /
taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progress.setProgress((int) progresstime);
}
});
} else {
Toast.makeText(getApplicationContext(), "Choose file",
Toast.LENGTH_LONG).show();
}
}

Image capture with camera & upload to Firebase (Uri in onActivityResult() is null)

So I've got a problem, previously mentioned in the question I've asked: Uploading image (ACTION_IMAGE_CAPTURE) to Firebase storage
I've searched for the issue a bit more, and applied the Android Studio documentation: https://developer.android.com/training/camera/photobasics.html#TaskPhotoView
So, before you read the code, I basically want to say what is needed: I just want to capture a photo with camera and upload it directly to Firebase storage. To do that I need the Uri to contain the picture I just took (Uri.getLastPathSegment()), however I still couldn't succeed doing this.
So now, this is what my code look like (only related parts):
AndroidManifest.xml:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
I have the res/xml/file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.serjardovic.firebasesandbox/files/Pictures" />
</paths>
and finaly the MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Button b_gallery, b_capture;
private ImageView iv_image;
private StorageReference storage;
private static final int GALLERY_INTENT = 2;
private static final int CAMERA_REQUEST_CODE = 1;
private ProgressDialog progressDialog;
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, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
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...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage = FirebaseStorage.getInstance().getReference();
b_gallery = (Button) findViewById(R.id.b_gallery);
b_capture = (Button) findViewById(R.id.b_capture);
iv_image = (ImageView) findViewById(R.id.iv_image);
progressDialog = new ProgressDialog(this);
b_capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
progressDialog.setMessage("Uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Need a solution! Still, the app crashes after I take the picture and press the confirm button and I get the following crash report:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.serjardovic.firebasesandbox/com.serjardovic.firebasesandbox.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference
Try changing mCurrentPhotoPath = image.getAbsolutePath(); to mCurrentPhotoPath = "file:" + image.getAbsolutePath();.
I didnt spot any other differences from my code, which has worked.
So the answer is simple, thanks to #wilkas help in the comments. I just forgot to add the photoURI into filepath.putFile(photoURI), it was just filepath.putFile(uri), so the addition of code simply did nothing until I notices this. Hope this Q&A will help someone else with a similar problem!

Send the cropped image to a folder in server

I want to crop the image which is taken from camera and set that image in ImageView and after that I want to send it to a folder in server.
Currently am able to set the cropped image in ImageView and that image is saving on my sdcard.
But I am not getting how to save it in server when clicked on a button.Please help me.This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop_update);
Button captureBtn = (Button) findViewById(R.id.SelectImageBtn);
captureBtn.setOnClickListener(this);
Button captureBtn1 = (Button) findViewById(R.id.btnCapturePicture);
captureBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchUploadActivity(true);
}
});
}
private void launchUploadActivity(boolean isImage) {
Intent i = new Intent(SaveUpload1.this, UploadActivity.class);
i.putExtra("filePath", picUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
public void onClick(View v) {
if (v.getId() == R.id.SelectImageBtn) {
try {
// use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
picUri = getOutputMediaFileUri();
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
// start the image capture Intent
startActivityForResult(captureIntent, CAMERA_CAPTURE);
// we will handle the returned data in onActivityResult
// startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
/**
* returning image / video
*/
private static File getOutputMediaFile() {
// 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;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
// picUri = data.getData();
performCrop();
}
// user is returning from cropping the image
else if (requestCode == CROP_PIC) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.ProfilePicIV);
picView.setImageBitmap(thePic);
}
}
}
/**
* this function does the crop operation.
*/
private void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}

Resources