I integrate file picker in my application. so i set below code for that and i use this library for that.
library
public class FileChooserExampleActivity extends Activity {
private static final String TAG = "FileChooserExampleActivity";
private static final int REQUEST_CODE = 6384;
private static final int REQUEST_WRITE_STORAGE = 112;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a simple button to start the file chooser process
Button button = new Button(this);
button.setText(R.string.choose_file);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Display the file chooser dialog
showChooser();
}
});
setContentView(button);
}
private void showChooser() {
// Use the GET_CONTENT intent from the utility class
Intent target = FileUtils.createGetContentIntent();
// Create the chooser Intent
Intent intent = Intent.createChooser(
target, getString(R.string.chooser_title));
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// The reason for the existence of aFileChooser
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE:
// If the file selection was successful
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
final Uri uri = data.getData();
Log.i(TAG, "Uri = " + uri.toString());
try {
// Get the file path from the URI
final String path = FileUtils.getPath(this, uri);
Toast.makeText(FileChooserExampleActivity.this,
"File Selected: " + path, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("FileSelectorTestActivity", "File select error", e);
}
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
permissin:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
When i run above code in Android Marshmallow 6.0 device and i fetch image from sdcard than i get selected file path value as null so any idea how can i solve this ? your all suggestions are appreciable
Related
Issue:
Office is a folder in internal memory of Android.
Clicking a button in screen should always take one to default folder, Office.
Appreciate help as no accepted answers found.
In onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
if (requestCode == viewfilerequestcode){
Uri Fileuri = data.getData();
String DFLocation="/mnt/sdcard/Office/";
String FilePath="";
if (FilePath.trim().equals(DFLocation.concat(GettheFilename(Fileuri))))
{
FilePath = DFLocation.concat(GettheFilename(Fileuri));
}
......
.......
........
}
.........
..........
}
Intent start:
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent;
String[] mimestoview =
{"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx };
fileintent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileintent.setType("*/*");
fileintent.putExtra(Intent.EXTRA_MIME_TYPES, mimestoview );
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
fileintent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
fileintent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivityForResult(fileintent, viewfilerequestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity to handle picking a file. Showing alternatives.");
}
}
});
I need to send an attachment along with some basic information by mail using my app. But the attachment is blank when I'm trying to invoke the mail activity using intent.
Here's the code for getting filepath and then sending the attachment
public class Pickafile extends AppCompatActivity {
TextView textFile;
static String FilePath;
private static final int PICKFILE_RESULT_CODE = 1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Button buttonPick = (Button) findViewById(R.id.buttonpick);
Button bp = (Button) findViewById(R.id.proceed);
textFile = (TextView) findViewById(R.id.textfile);
buttonPick.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);
}
});
bp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
//intent.setType("text/plain");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_SUBJECT, " Report Particulars for " + MainActivity.name);
/*File root = Environment.getExternalStorageDirectory();
File file = new File(root, FilePath);
if (!file.exists() || !file.canRead()) {
return;
}*/
/*if(FilePath!=null)
{
intent.putExtra(Intent.EXTRA_STREAM, FilePath);
}*/
intent.putExtra(Intent.EXTRA_TEXT, MainActivity.testfunc());
intent.putExtra(Intent.EXTRA_STREAM, FilePath);
//startActivity(Intent.createChooser(intent, "Pick an Email provider"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
FilePath = data.getData().getPath();
textFile.setText(FilePath);
}
break;
}
}
}
testfunc() is used to get body of the mail (name, age, phone,etc.)
Thanks in advance!
You should check the log if there is any error.
Possible case:
1. The file is too large, exceed maximum size of email attachment (20Mb for Gmail)
2. Missing READ_EXTERNAL_STORAGE permission if the file is saved in external storage.
3. Missing file_provider in manifest
Am working with android attachments same like whatsapp.I can able to take picture through camera,gallery options,location,record video.I have stucked with two options,
How to record audio?
while clicking on audio button,the following code i have been used,
audioIB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, 6);
}
});
and which is redirecting to recording audio but after file save it is not redirecting to the activity.what is the code in onActivityResult .
How can i restrict the particular file extensions while attaching files,I need to select doc,txt,pdf,audio files.Rest i don't want to attach.I tried so many but i cant able to do.Please help me asp.This is my code after you mentioned link using,
The following code i have been used,
private void showFileChooser()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.setType("application/*");
intent.setType("application/pdf|application/doc|application/docm|application/docx|application/dot|application/mcw|application/rtf" + "|application/pages|application/odt|application/ott");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try
{
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
4);
}
catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
For audio recording , Usually the normal Intent MediaStore.Audio.Media.RECORD_SOUND_ACTION will work to record the audio and return the path back to the activity in onActivityResult() method.
For that this the sample code.
int RQS_RECORDING = 1;
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, RQS_RECORDING);
In your OnActivityResult() your code will be like this,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RQS_RECORDING){
if(resultCode == Activity.RESULT_OK){
// Great! User has recorded and saved the audio file
if(data!=null)
{
String savedUri = data.getData();
Log.d("debug" , "Record Path:" + savedUri);
Toast.makeText(MainActivity.this,
"Saved: " + result,
Toast.LENGTH_LONG).show();
}
}
if (resultCode == Activity.RESULT_CANCELED) {
// Oops! User has canceled the recording
}
}
}
But Nope, It is not working for all the cases and some of the devices ( ex vivo V3 etc) recording is saved but it is not returning any data back i.e ( data is null) and some of the devices some additional options also in the recording ( like delete , retry , play , pause etc) which may also not required for us.
So Instead of the default Intent , you can create the custom Recording by using MediaRecorder like below.
Sample Code.
AudioRecordActivity.Class
public class AudioRecordActivity extends AppCompatActivity {
Button buttonStart, buttonStop ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_record_activity);
buttonStart = (Button) findViewById(R.id.button);
buttonStop = (Button) findViewById(R.id.button2);
buttonStop.setEnabled(false);
random = new Random();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(AudioRecordActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
Toast.makeText(AudioRecordActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",AudioSavePathInDevice);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(AudioRecordActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(AudioRecordActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AudioRecordActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
audio_record_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="40dp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="40dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#mipmap/ic_launcher_round"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="#+id/button"
android:layout_below="#+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="#+id/button2"
android:layout_alignTop="#+id/button"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.STORAGE" />
So where ever you want to record the audio / sound you can simply use the below code and get your saved path back in result activity.
int RQS_RECORDING = 1;
Intent intent = new Intent(MainActivity.this , AudioRecordActivity.class);
startActivityForResult(intent, RQS_RECORDING);
OnActivityResult() will be like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == RQS_RECORDING){
if(resultCode == Activity.RESULT_OK){
// Great! User has recorded and saved the audio file
String result=data.getStringExtra("result");
Toast.makeText(MainActivity.this,
"Saved: " + result,
Toast.LENGTH_LONG).show();
Log.d("debug" , "Saved Path::" + result);
}
if (resultCode == Activity.RESULT_CANCELED) {
// Oops! User has canceled the recording / back button
}
}
}
This is a sample code you can customize for your needs how you want for your requirement.
This is one library which providing the record controlling
For the second question, as i already given the link, you can use like below.
private void browseDocuments(){
String[] mimeTypes =
{"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent,"ChooseFile"), REQUEST_CODE_DOC);
}
I am implementing an MMS application for that i am using camera also.Main theme of main application was take picture using device camera ater that send that image as MMS to specified number.But while attahing the image i am getting error warning like
Unable to attach File not support
Please help to resolve my problem.
Thanks,
public class MMS extends Activity implements OnClickListener {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
EditText preLoc,comeby;
Button ok,capture;
String photo;
String dir;
boolean GPS,flag;
String cityName=null;
String SubThorugh = null;
Intent i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mms);
preLoc = (EditText)findViewById(R.id.etPreLoc1);
comeby = (EditText)findViewById(R.id.etComing1);
ok = (Button)findViewById(R.id.bOK1);
capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(this);
ok.setOnClickListener(this);
i = getIntent();
GPS = i.getBooleanExtra("GPSneed", false);
ok.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.btnCapture:
capturePicture();
break;
case R.id.bOK1:
sendMMS();
preLoc.setText(cityName+SubThorugh);
break;
}
}
private void sendMMS() {
// TODO Auto-generated method stub
try {
Uri uri = Uri.parse(photo);
Intent i = new Intent(Intent.ACTION_SEND);
//i.putExtra("address",etnum.getText().toString());
//i.putExtra("sms_body",etmsg.getText().toString());
i.putExtra(Intent.EXTRA_STREAM,uri);
i.setType("image/*");
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
Toast.makeText(getApplicationContext(), "photo saved as: "+photo, Toast.LENGTH_LONG).show();
}
}
private void capturePicture() {
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
photo = file;
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
I'm currently trying to integrate a camera into my android app and save the picture on my device; however, when I take a picture, I can't proceed (the app works, but the camera shot freezes meaning I can take another picture and go back, but can't confirm). I was wondering if you guys could help. Please explain this as simply as possible because I'm very new at programming for android. Thanks everyone!
public class PhotoCapture extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
public static File newfile;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photocapture);
Button capture = (Button) findViewById(R.id.takepicture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ContextWrapper cw = new ContextWrapper(getBaseContext());
newfile = cw.getDir("test.jpg", Context.MODE_PRIVATE);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
uri = data.getData().toString();
Log.d("CameraDemo", "Pic saved");
Intent myview = new Intent(this, Finalpiece.class);
startActivity(myview);
}
}
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"/>
Use this permission before...
private static final int REQ_CAPTURE_CAPTURE__IMAGE = 0;
private String imagePath;
/**
* Start camera activity.
*/
protected void startCameraActivity() {
String imageDirectory = Environment.getExternalStorageDirectory()
+ File.separator + "surbeyImg";
File imageDirectory = new File(imageDirectory);
if (!(imageDirectory.exists())) {
imageDirectory.mkdir();
}
String imagePath = imageDirectory + File.separator + imgName+".jpg");
File file = new File(imagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
startActivityForResult(intent, REQ_CAPTURE_CAPTURE__IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
switch (requestCode) {
case REQ_CAPTURE_CAPTURE__IMAGE:
if (resultCode == RESULT_OK) {
Intent intentImg = new Intent(CameraDemo.this, ShowImg.class);
intentImg.putExtra("imagePath",imagePath);
startActivity(intentImg);
}
break;
default:
break;
}
}
after this use this code ...thanks