Limit duration of video - java

I am recording a video with MediaStore and I am trying to limit the duration of the video to 30 seconds but I have a problem.
As soon as I click on the record icon the video starts at 30 and then it ends. Does anyone know the problem ?
activity_record_video:
<VideoView
android:id="#+id/video_view"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="recordVideo"
android:backgroundTint="#color/teal_200"
android:text="Record Video"
app:layout_constraintBottom_toTopOf="#+id/video_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
RecordVideo.java:
public class RecordVideo extends Activity {
VideoView videoView;
int REQUEST_CODE_VIDEO_CAPTURE = 2607;
private ListView filter_list;
protected GPUCameraRecorder GPUCameraRecorder;
Button selectVideo, uploadVideo;
ProgressDialog progressDialog;
public static Uri videoUri;
public static final int EXTRA_DURATION_LIMIT = 3;
PostActivity postActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_video);
videoView = findViewById(R.id.video_view);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
filter_list = findViewById(R.id.filter_list);
uploadVideo = findViewById(R.id.uploadVideo);
selectVideo = findViewById(R.id.selectVideo);
selectVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(RecordVideo.this);
chooseVideo();
}
});
uploadVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Code for showing progressDialog while uploading
progressDialog = new ProgressDialog(RecordVideo.this);
uploadUserVideo(videoUri);
}
});
}
public void recordVideo(View view) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//if (intent.resolveActivity(getPackageManager()) != null ) {
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,30); //30Seconds
//intent.putExtra("android.intent.extra.durationLimit", 300000);
intent.putExtra("EXTRA_VIDEO_QUALITY", 0);
startActivityForResult(intent, REQUEST_CODE_VIDEO_CAPTURE);
//}
}
// choose a video from phone storage
private void chooseVideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(intent, 5);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE_VIDEO_CAPTURE && resultCode == RESULT_OK && data.getData() != null) {
if (requestCode > EXTRA_DURATION_LIMIT) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.pause();
}
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
} else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
super.onActivityResult(requestCode, resultCode, data);
}

Related

onActivityResult not being called in activity

I am recording/selecting a video in my RecordVideo.java activity. Once the video is recorded/selected the I press the upload button and go to the PostActivity.java file. But once I'm in there for some reason onActivityResult isn't being called. I tried to toast and Log.d for some type of error or info but nothing came up.
I checked the answer on here to the same problem I'm having but none of them worked for me.
Can someone please help ?
RecordVideo.java:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE_VIDEO_CAPTURE && resultCode == RESULT_OK && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
} else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadUserVideo(Uri videoUri) {
if (videoUri != null) {
Intent intent = new Intent(RecordVideo.this, PostActivity.class);
intent.putExtra("videoUri", videoUri.toString());
startActivity(intent);
finish();
} else {
Toast.makeText(this, "It's null", Toast.LENGTH_SHORT).show();
}
}
PostActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
Bundle extras = getIntent().getExtras();
if (extras != null) {
//videoUri = extras.getInt(videoUri);
videoUri = Uri.parse(extras.getString("videoUri"));
//Toast.makeText(this, "It's not null", Toast.LENGTH_SHORT).show();
} else {
// handle case
Toast.makeText(this, "Post null", Toast.LENGTH_SHORT).show();
}
videoView = findViewById(R.id.video_added);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
close = findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(PostActivity.this, MainActivity.class));
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.d("TAG3", "I'm here." + requestCode);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
Toast.makeText(this, "No problem.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "A problem.", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}

Upload Image on Firebase Storage

Hi I want to add an image on firebase storage with android studio but firebase doesn't accept my upload. I changed the rule to allow the write and read and my match folder allows all path.Thus I am confused. Here is the part of my code who should put the image in my database.
If you know how to resolve this problem i would be glad to ear a solution
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
image_uri = data.getData();
uploadPicture();
ProfileImage.setImageURI(image_uri);
}
}
private void uploadPicture() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading Image...");
pd.show();
final String randomKey = UUID.randomUUID().toString();
StorageReference riversRef = storageReference.child(("images/" + randomKey + ".jpg"));
Toast.makeText(Create_Profile.this, "Upload success", Toast.LENGTH_SHORT).show();
riversRef.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
name = riversRef.getDownloadUrl().toString();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progressPercent = (100.00 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
pd.setMessage("Percentage: " + (int) progressPercent + "%");
}
});
}
if you don't getting error compare with this simple code
thank you
firebase storage dependency
implementation 'com.google.firebase:firebase-storage:19.1.0'
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<!--Linear Layout with horizontal orientation
and other properties-->
<LinearLayout
android:id="#+id/layout_button"
android:orientation="horizontal"
android:layout_alignParentTop="true"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--Button for choosing image from gallery-->
<Button
android:id="#+id/btnChoose"
android:text="Choose"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<!--Button for uploading image-->
<Button
android:id="#+id/btnUpload"
android:text="Upload"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<!--Image View for showing image choosen from gallery-->
<ImageView
android:id="#+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
in your Activity
public class MainActivity extends AppCompatActivity {
private Button btnSelect, btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 22;
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable
= new ColorDrawable(
Color.parseColor("#0F9D58"));
actionBar.setBackgroundDrawable(colorDrawable);
btnSelect = findViewById(R.id.btnChoose);
btnUpload = findViewById(R.id.btnUpload);
imageView = findViewById(R.id.imgView);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SelectImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
uploadImage();
}
});
}
private void SelectImage()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(
intent,
"Select Image from here..."),
PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent data)
{
super.onActivityResult(requestCode,
resultCode,
data);
if (requestCode == PICK_IMAGE_REQUEST
&& resultCode == RESULT_OK
&& data != null
&& data.getData() != null) {
// Get the Uri of data
filePath = data.getData();
try {
Bitmap bitmap = MediaStore
.Images
.Media
.getBitmap(
getContentResolver(),
filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImage()
{
if (filePath != null) {
ProgressDialog progressDialog
= new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref
= storageReference
.child(
"images/"
+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Image Uploaded!!",
Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Failed " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
})
.addOnProgressListener(
new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(
UploadTask.TaskSnapshot taskSnapshot)
{
double progress
= (100.0
* taskSnapshot.getBytesTransferred()
/ taskSnapshot.getTotalByteCount());
progressDialog.setMessage(
"Uploaded "
+ (int)progress + "%");
}
});
}
}
}
I found a solution by modifying my firebase Rules to match with the bucket directly and not with the ref of my firebase storage

How can I get the URI to the file with 3 different file choosers?

I have 3 different buttons: Upload Profile Picture, Upload Photo ID and Upload Criminal Record Photo, but after I call the openFileChooser() method which I created, I don't know how exactly I have to handle that to get 3 different URls.
I mean I did this
public class SignupCarrier extends AppCompatActivity {
EditText editfullname, editemail, editpassword, editconfirmpassword, editaddress, editcity, editstate, editzipcode, editcountry, editphone, editcardnumber, editexpiredate, editcvc;
Button upProfile, upIDPhoto, upCriminalRecord;
private Uri mProfilePic, mIdPhoto,mCriminalRecord;
FirebaseAuth mFirebaseAuth;
private StorageReference mStorageRef;
private StorageTask mUploadTask;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_carrier);
mFirebaseAuth = FirebaseAuth.getInstance();
upProfile = (Button) findViewById(R.id.profilePic);
upIDPhoto = (Button) findViewById(R.id.idphotoPic);
upCriminalRecord = (Button) findViewById(R.id.criminalRecord);
mStorageRef = FirebaseStorage.getInstance().getReference("carriersPictures");
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upIDPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upCriminalRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
mProfilePic = data.getData();
}
}
}
But this would probably work only for upProfile Button, how can I modify the onActivityResult to get for each buttons the URLs?
Thank you! I'm new to Android.
Add Uri as parameter to your openFileChooser() method.
private void openFileChooser(Uri uri)
and call it like this:
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser(mProfilePic);
}
});
Update your openFileChooser() method to this:
private void openFileChooser(Uri uri) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (uri == mProfilePic) {
startActivityForResult(intent, PICK_IMAGE_REQUEST);
} else if (uri == mIdPhoto) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_ID);
} else if (uri == mCriminalRecord) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_CR);
}
}
You need to declare these constants: PICK_IMAGE_REQUEST_ID, PICK_IMAGE_REQUEST_CR
And in your onActivityResult() method check the requestCode to handle each case

ImageView not showing image selected from gallery

So I have a button that loads the gallery, and selects an image using this code...
public void getGalleryImage(View v){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
But when it goes back to the original activity, the ImageView still doesn't show anything. It doesn't give me any errors, or anything like that. Here the XML for the ImageView...
<ImageView
android:id="#+id/galleryImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
How can I get it to show?
I ended up figuring something out. I just did...
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageURI(selectedImage);
}
This worked for what I was trying to accomplish.
Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri));
}
}
public class MainActivity extends AppCompatActivity{
ImageView image;
Button pick;
int TAG_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
pick = (Button) findViewById(R.id.button);
pick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,"Select Image "),TAG_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAG_IMAGE && resultCode == RESULT_OK )
{
Uri selectedImage = data.getData();
try
{
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String images = cursor.getString(columnIndex);
image.setImageURI(selectedImage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

Replace the original image on a new image in android application

In this MainActivity java class on Android Application Project I can't replace the original image given by the system with the one different selected from the photo gallery of smartphone.
When I select the one different photo I have always the original image.
public class MainActivity extends Activity implements OnClickListener {
Button uploadButton, btnselectpic;
ImageView imageview;
private ProgressDialog dialog = null;
private String imagepath = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button) findViewById(R.id.uploadButton);
btnselectpic = (Button) findViewById(R.id.btnselectpic);
imageview = (ImageView) findViewById(R.id.imageview);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
#Override
public void onClick(View arg0) {
if (arg0 == btnselectpic) {
selectImage();
} else if (arg0 == uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
The problem is that your onActivityResult() will never do anything.
You start this method off with:
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
// ...
}
requestCode cannot be both 1 and 2, so this conditional will always be false.
You are likely looking for something more like this:
if ((requestCode == 1 && resultCode == RESULT_OK) ||
(requestCode == 2 && resultCode == RESULT_OK)) {
// ...
}

Categories

Resources