I am Developing a that takes a video from Storage via intent. So i am Facing this problem
Problem:-
java.lang.illegalArgumentException:inputFile not exists:/document/video:105065
Code:-
Intent
public void videotext( View v ) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/*");
startActivityForResult(i, request);
}
On Activity Result
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == request) {
uri = data.getData();
mSurfaceView.setVideoURI(uri);
//MediaController media1=new MediaController(this);
media.setAnchorView(mSurfaceView);
mSurfaceView.setMediaController(media);
mSurfaceView.start();
inputFile=new File(uri.getPath());
inputFile=inputFile.getAbsoluteFile();
VideoCompress(inputFile,OutputFile);
}
}
}
VideoCompress is a method to Compress video..
public void VideoCompress(File inputFile,File OutputFile)
{
GiraffeCompressor.create() //two implementations: mediacodec and ffmpeg,default is mediacodec
.input(inputFile) //set video to be compressed
.output(OutputFile) //set compressed video output
.bitRate(2073600)//set bitrate 码率
.resizeFactor(Float.parseFloat(String.valueOf(1.0)))//set video resize factor 分辨率缩放,默认保持原分辨率
// .watermark("/sdcard/videoCompressor/watermarker.png")//add watermark(take a long time) 水印图片(需要长时间处理)
.ready()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GiraffeCompressor.Result>() {
#Override
public void onCompleted() {
Toast.makeText(UploadVideo.this,"Compressing",Toast.LENGTH_LONG).show();
}
#Override
public void onError(Throwable e) {
Toast.makeText(UploadVideo.this,e.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onNext(GiraffeCompressor.Result s) {
Toast.makeText(UploadVideo.this,"Compressed",Toast.LENGTH_LONG).show();
}
});
}
Use this Method to get Path for your Uri :
public static String getPath(Context context,Uri uri) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
use it like mSurfaceView.setVideoURI(data.getData());
Related
I need to ask the user to select a media file from his SD card for playing. The following code doesn't work:
edit:
after I choose a mp3 file from the sd card folder I can't start him (play him). I think that the problem is that it doesn't entering to the "onActivityResult" function.
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, RESULT_OK);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==RESULT_OK)
{
Uri uri =data.getData();
if(uri!=null) {
try {
song.setDataSource(getApplicationContext(), uri);
song.prepare();
pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
song.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
Your question doesn't include definitions of some variables so I added my own and it played. Try this:-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Uri uri = data.getData();
if (uri != null) {
try {
MediaPlayer song = new MediaPlayer();
song.setDataSource(getApplicationContext(), uri);
song.prepare();
song.start();
} catch (Exception e) {
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
MediaPlayer Docs here
I am trying to attach video file in my app. I tried the following code to get video from Android device. After attaching the video, if I try to play it using the MediaController class, the screen becomes blank. Please help me with this.
void pickVideo() {
Intent videoIntent = new Intent(Intent.ACTION_GET_CONTENT);
videoIntent.setType("video/*");
startActivityForResult(videoIntent, PICK_VIDEO_FILE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_VIDEO_FILE:
Uri videoUri = data.getData();
if (mChooseFileDialogListener != null) {
mChooseFileDialogListener.onVideoClick(videoUri, ViewModel.FILE_TYPE_VIDEO);
}
break;
}
}
ChooseFileDialogFragment.ChooseFileDialogListener mChooseFileDialogListener = new ChooseFileDialogFragment.ChooseFileDialogListener() {
#Override
public void onVideoClick(Uri videoUri, int fileType) {
mPath = videoUri.toString();
}
}
AttachmentAdapter.ItemClickListener = new AttachmentAdapter.ItemClickListener() {
#Override
public void onClick(String path) {
playVideo(path);
}
}
private void playVideo(String path) {
MediaController mediaControls = new MediaController(getActivity());
try {
//set the media controller in the VideoView
mBinding.videoPlayer.setMediaController(mediaControls);
//set the uri of the video to be played
if (file != null) {
mBinding.videoPlayer.setVideoPath(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Right Now I am getting my files using a particular piece of code which is working fine but in some of cell phones where there is no software like google drive I am getting message like no application installed for request. So I have searched and found that We can get files using Media.Files but not enough documentation is present to carry out the task.
Code:
warantyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf,application/msword");
Intent i = Intent.createChooser(intent, "File");
getActivity().startActivityForResult(i, FILE_REQ_CODE);
//Toast.makeText(getContext(),"Files",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_REQ_CODE) {
if (resultCode == RESULT_OK) {
String path="";
Uri uri = data.getData();
if (uri != null) {
try {
file = new File(getPath(getContext(),uri));
if(file!=null){
ext = getMimeType(uri);
sendFileToServer(file,ext);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
gallery.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class gallery extends Fragment {
private static final int PICK_FROM_GALLERY = 1;
RelativeLayout gallerylayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mainfragment, container, false);
gallerylayout = (RelativeLayout) v.findViewById(R.id.gallery_layout);
gallerylayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fireGallery();
}
});
return v;
}
private void fireGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_GALLERY:
String[] all_path = data.getStringArrayExtra("all_path");
System.out.println("all_path " + all_path); //Returns null
System.out.println("Data " + data.getExtras()); //Returns null
break;
}
}
}
The data in onActivityResult is always null, please correct me if anything wrong with my code. As mentioned both logs inside onActivityResult returns null. Note i am extending Fragment not activity.
Try this, you may get data from it:
#Override
protected void onActivityResult (int requestCode,int resultCode,Intent data){
super.onActivityResult (requestCode,resultCode,data);
try{
// When an Image is picked
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK
&& null != data){
// Get the Image from data
Uri selectedImage = data.getData ();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver ().query (selectedImage,
filePathColumn,null,null,null);
// Move to first row
cursor.moveToFirst ();
int columnIndex = cursor.getColumnIndex (filePathColumn[0]);
String imgDecodableString = cursor.getString (columnIndex);
cursor.close ();
Log.e ("Image Path",imgDecodableString);
Toast.makeText (this,"You have picked Image" ,
Toast.LENGTH_LONG).show ();
}
else{
Toast.makeText (this,"You haven't picked Image",
Toast.LENGTH_LONG).show ();
}
}
catch (Exception e){
Toast.makeText (this,"Something went wrong",Toast.LENGTH_LONG)
.show ();
Log.e ("Exception",e.toString ());
}
}
you can reading :http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments
Create ActivityResultEvent.java
import android.content.Intent;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultEvent {
private int requestCode;
private int resultCode;
private Intent data;
public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}
Create ActivityResultBus.java
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultBus extends Bus {
private static ActivityResultBus instance;
public static ActivityResultBus getInstance() {
if (instance == null)
instance = new ActivityResultBus();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityResultBus.getInstance().post(obj);
}
});
}
}
// >>>>>>>>>>>>>> override onActivityResult on Activity
public class MainActivity extends ActionBarActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResultBus.getInstance().postQueue(
new ActivityResultEvent(requestCode, resultCode, data));
}
...
}
In fragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Don't forget to check requestCode before continuing your job
if (requestCode == 12345) {
// Do your job
tvResult.setText("Result Code = " + resultCode);
}
}
#Override
public void onStart() {
super.onStart();
ActivityResultBus.getInstance().register(mActivityResultSubscriber);
}
#Override
public void onStop() {
super.onStop();
ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
}
private Object mActivityResultSubscriber = new Object() {
#Subscribe
public void onActivityResultReceived(ActivityResultEvent event) {
int requestCode = event.getRequestCode();
int resultCode = event.getResultCode();
Intent data = event.getData();
onActivityResult(requestCode, resultCode, data);
}
};
if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK && null!=data)
{
Bitmap photo;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
if (picturePath != null) {
Log.v("", picturePath);
cursor.close();
photo = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
photo = Bitmap.createScaledBitmap(photo, 1200, 1200, true);
this.data = baos.toByteArray();
chooseImage.setImageBitmap(photo);
}
else {
Utilities.showToast(getActivity(),
"This image is not on your device");
}
}
if You want to get picture from the gallery then you should use this function
I am developing an application,in which user will select a single audio file and play the audio.
Then I will pass the audio to the next activity.
Here is my code it select the audio but it gives error setDataSource Failed:Status=0X80000000 kindly guide me what should I do
switch(v.getId())
{
case R.id.btnmusic:
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File("file:///sdcard/Music");
intent.setDataAndType(Uri.fromFile(file), "audio/*");*/
Intent pickMedia = new Intent(Intent.ACTION_GET_CONTENT);
pickMedia.setType("audio/*");
startActivityForResult(pickMedia,1);
break;
protected void onActivityResult(int RequestCode,int ResultCode,Intent data)
{
if(RequestCode==1)
{
if(data != null)
{
Uri muri=data.getData();
String uri=muri.getPath();
File track=new File(uri);
if(uri != null)
{
Uri urinew = MediaStore.Audio.Media.getContentUriForPath(track.getAbsolutePath());
//Toast.makeText(this, uri, Toast.LENGTH_SHORT).show();
MediaPlayer md=new MediaPlayer();
try{
md.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
md.setDataSource(AudioSelect.this, urinew);
md.prepare();
md.start();
}
catch(Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
}
else
{
Toast.makeText(this, "No Image Data Recieved", Toast.LENGTH_SHORT).show();
}
}
}
}
1: Use Intent to choose audio file from sd card:
Intent audioIntent = new Intent();
audioIntent.setType("audio/*");
audioIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(audioIntent,PICK_AUDIO_REQUEST);
2: Handle the result in OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null || data.getData() == null) {
// error
return;
}
if (requestCode == PICK_AUDIO_REQUEST) {
try {
Uri uri= data.getData();
String path = getRealPathFromURI(uri);
// play audio file using MediaPlayer
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: getRealPathFromURI is a utility method :
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
md = MediaPlayer.create(this, Uri.parse(track.getAbsolutePath()));
but i want to send this muri to next activity so i can play the song in next activity.please guide me how can i do this.
protected void onActivityResult(int RequestCode,int ResultCode,Intent data)
{
if(RequestCode==1)
{
if(data != null)
{
Uri muri=data.getData();
Intent intent = new Intent(this,NextActivity.class);
intent.putExtra("uriToPlay",muri);
startActivity(intent);
}
else
{
Toast.makeText(this, "No Image Data Recieved",
Toast.LENGTH_SHORT).show();
}
}
}
Rest of the code (like Media player) in the next Activity.