I have the following code and want to save the data in the internal storage such as photo/gallery but unable to do with the following code. How will I able to save the data to the internal storage? Some sample or tips would be great! Love to hear from you!
I'm using the current code to save the data.
#SuppressLint("MissingPermission")
private void saveImage() {
if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showLoading("Saving...");
File file = new File(getBaseContext().getFilesDir()
+ File.separator + ""
+ System.currentTimeMillis() + ".png");
try {
file.createNewFile();
SaveSettings saveSettings = new SaveSettings.Builder()
.setClearViewsEnabled(true)
.setTransparencyEnabled(true)
.build();
mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
#Override
public void onSuccess(#NonNull String imagePath) {
hideLoading();
showSnackbar("Image Saved Successfully");
mPhotoEditorView.getSource().setImageURI(Uri.fromFile(new File(imagePath)));
}
#Override
public void onFailure(#NonNull Exception exception) {
hideLoading();
showSnackbar("Failed to save Image");
}
});
} catch (IOException e) {
e.printStackTrace();
hideLoading();
showSnackbar(e.getMessage());
}
}
}
private void saveImage() {
if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showLoading("Saving...");
filename = String.valueOf(System.currentTimeMillis()) + ".png";
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/" + getResources().getString(R.string.app_name));
try {
if (!file.exists())
file.mkdir();
file.createNewFile();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mPhotoEditor.saveAsFile(file.getAbsolutePath() + "/" + filename, new PhotoEditor.OnSaveListener() {
#Override
public void onSuccess(#NonNull String imagePath) {
hideLoading();
showSnackbar("Image Saved Successfully");
MediaScannerConnection.scanFile(EditImageActivity.this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Log.e(".provider", " : " + getPackageName() + ".provider");
Log.e("filepath", " : " + imagePath);
if (imagePath != null && !imagePath.isEmpty()) {
File file1 = new File(imagePath);
Log.e("file1", " : " + file1);
if (file1 != null) {
Uri imageUri = FileProvider.getUriForFile(
EditImageActivity.this,
getPackageName() + ".fileprovider", //(use your app signature + ".provider" )
file1);
mPhotoEditorView.getSource().setImageURI(imageUri);
Log.e("imageUri", " : " + imageUri);
}
}
}
#Override
public void onFailure(#NonNull Exception exception) {
hideLoading();
showSnackbar("Failed to save Image");
}
});
} catch (IOException e) {
e.printStackTrace();
hideLoading();
showSnackbar(e.getMessage());
}
}
Related
I went through the solution here.
Android FFMpeg No such file or directory error but it doesn't work for me.
The file is present in the location and I am still getting this error.
Here is the code snippet
private void spliceSong(AudioObject audioObject) {
File folder = new File("/sdcard/roboscreen/TempAudio");
if (!folder.exists()) {
folder.mkdir();
}
String fileName = new File(audioObject.path).getName();
File dest = new File(folder, fileName);
Log.d(TAG, "Destination Filename is " + fileName);
if (!dest.exists()){
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String path = new File(audioObject.path).getPath();
Log.d(TAG, "File created " + dest.getAbsolutePath() + " " + audioObject.endDate + " " + audioObject.startDate);
String[] command = {"-ss", "2", "-i", "root/"+path, dest.toString()};
Log.d(TAG, "spliceSong: " + (this.context==null));
FFmpeg ffmpeg = FFmpeg.getInstance(this.context);
// // to execute "ffmpeg -version" command you just need to pass "-version"
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler(){
#Override
public void onSuccess() {
super.onSuccess();
Log.d(TAG, "onSuccess: bruhhhhh");
}
});
} catch (FFmpegNotSupportedException e) {
// Log.d(TAG, "Kaam Tamaam");
e.printStackTrace();
}
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {
Log.d(TAG, "Work Started done");
}
#Override
public void onProgress(String message) {
Log.d(TAG, "Doing some work");
}
#Override
public void onFailure(String message) {
Log.d(TAG, "Conversion failure " + message);
}
#Override
public void onSuccess(String message) {
Log.d(TAG, "Conversion Successful");
}
#Override
public void onFinish() {
Log.d(TAG, "Work Dome");
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
// Log.d(TAG, "spliced");
// return File
}
and the context is coming through a different class
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ScreenRecorder(RoboTutor activity, Context context) throws Exception {
if (isInstantiated){
// raise Error and quit
throw new Exception("One instance already instantiated");
}
this.activity = activity;
this.context = context;
this.isInstantiated = true;
this.videoTimeStamp = new Date();
}
A solution would be really appreciated.
Thanks in advance.
Figured it out. There were no issues with the library. I was referring to the wrong paths.
I'm setting download manager to download PDF file for server URL.
file is download completely but Broadcast Receiver doesn't call to open file .
I use AsyncTask and doInBackground class for downloading and set permission.INTERNET,permission.WRITE_EXTERNAL_STORAGE,permission.WRITE_INTERNAL_STORAGE ,permission.READ_EXTERNAL_STORAGE in manifest.
i checked my directory in real device and PDF file is completely download without any crash .
in OnCreate
registerReceiver(onComplete, filter);
in onClick Button
downloadPdf(v);
} else {
requestStoragePermission(v);
}
and also set onDestroy
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onComplete);
}
and downloading file
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0];
String fileName = strings[1];
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, DIRECTORY_PDF_NAME);
if (!folder.exists()) {
folder.mkdir();
}
// File pdfFile = new File(folder, fileName);
file_download(fileUrl);
return null;
}
public void file_download(String fileUrl) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DIRECTORY_PDF_NAME + "/" + "au.pdf");
if (file.exists()) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "انتخاب برنامه");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(LoginActivity.this, "عدم موفقیت در نمایش فایل", Toast.LENGTH_SHORT).show();
}
} else {
mgr = (DownloadManager) LoginActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(fileUrl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("راهنمای ثبت نام")
.setDescription(" در حال دانلود..." + "فایل راهنمای ثبت نام")
.setDestinationInExternalPublicDir("/" + DIRECTORY_PDF_NAME + "/", "au.pdf");
try {
refid = mgr.enqueue(request);
Log.d(TAG, "Checking download status for id: " + refid);
} catch (ActivityNotFoundException e) {
Toast.makeText(LoginActivity.this, "عدم موفقیت در دانلود فایل", Toast.LENGTH_SHORT).show();
}
}
}
}
and at the end
public void onReceive(Context ctxt, Intent intent) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DIRECTORY_PDF_NAME + "/" + "au.pdf");
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intentPdf = Intent.createChooser(target, "انتخاب برنامه");
try {
startActivity(intentPdf);
} catch (ActivityNotFoundException e) {
}
}
I solve this problem with this solution
I create a a PDF Class and transfer my downloading code in it.
public Pdf(Context context, String url, String fileName) {
this.context = context;
this.url = url;
this.fileName = fileName;
init();
}
private void init() {
downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Download_Uri = Uri.parse(url);
}
public void checkAndDownload() {
if (isStoragePermissionGranted()) {
if (isExistPdfFile()) {
openGeneratedPDF();
}else{
downloadPdf();
}
}
}
public void permissionGranted(int[] grantResults) {
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
downloadPdf();
}
}
private boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else {
return true;
}
}
public BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
isCompeleted = true;
openGeneratedPDF();
}
};
private boolean isExistPdfFile() {
File target = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File(target, DIRECTORY_PDF_NAME + "/" + fileName + ".pdf");
if (file.exists()) {
return true;
}else{
return false;
}
}
private void openGeneratedPDF() {
if (isExistPdfFile()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
Log.e("uri is",uri.toString());
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "برنامهای برای نمایش فایل PDF وجود ندارد", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(context,"فایل مورد نظر یافت نشد",Toast.LENGTH_LONG).show();
}
}
private void downloadPdf() {
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(true);
request.setVisibleInDownloadsUi(true);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, Constant.DIRECTORY_PDF_NAME + "/" + fileName + ".pdf");
refid = downloadManager.enqueue(request);
Log.e("OUT", "" + refid);
}
public boolean getIsCompeleted() {
return isCompeleted;
}
and call it in my requirement Activity ,also i use file provider such as
Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
I would like to save/create a file in the directory of my Emulator but i cant do that and i dont understand what is wrong with my code. So everytime i try to run the code it says that android cant create the file in such directory.
Can someone please explain to me how i make it. Here is the code of my Application:
public class MainActivity extends AppCompatActivity {
private int STORAGE_PERMISSION_CODE = 1;
private File csvFile;
SimpleDateFormat TIME;
private static final String CSV_DIRECTORY = "NameOfTheDirectory";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if((ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)){
Toast.makeText(MainActivity.this, "You have already granted this permission",
Toast.LENGTH_SHORT).show();
}else {
requestStoragePermission();
}
}
public void makeFile(View view) {
File csvDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY);
if(!csvDirectory.exists()) {
try{
csvDirectory.mkdir();
Log.d("StateMakeFile","Directory created");
} catch(Exception e) {
e.printStackTrace();
Log.d("StateMakeFile","Directory not created");
}
}
File categoryDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory");
if(!categoryDirectory.exists()){
try{
categoryDirectory.mkdir();
Log.d("StateMakeFile","CategoryDirectory created");
}catch (Exception e){
e.printStackTrace();
Log.d("StateMakeFile","CategoryDirectory not created");
}
}
TIME = new SimpleDateFormat("yyyyMMdd-hh:mm:ss:SSS", Locale.getDefault());
String uniqueFileName = TIME.format(new Date());
csvFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory" +
File.separator + uniqueFileName + ".csv");
if(!csvFile.exists()){
try{
csvFile.createNewFile();
Log.d("StateMakeFile","File created");
}catch (IOException e){
e.printStackTrace();
Log.d("StateMakeFile","File not created");
}
if(csvFile.exists()) {
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true)));
out.write("Something" + "\n");
out.flush();
out.close();
Log.d("StateMakeFile","File was writed with success");
}catch (IOException e){
e.printStackTrace();
Log.d("StateMakeFile","File wasnt writed with success");
}
}
}
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed to save and load files into ssd")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
}
I don‘t know if it is in your manifest, but your are working here with
READ_EXTERNAL_STORAGE
Try it with the permission
WRITE_EXTERNAL_STORAGE
Hope this helps you
When the service starts, I call startRecording() from onStartCommand(), and when the service ends, onDestroy() is called, from which I call stoprecording(). But recorder.stop() gives me an IllegalStageException
void startRecording() {
recordList = new ArrayList<>();
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
recordListString = mSharedPreferences.getString("RecordList", null);
if(recordListString!=null){
recordList = new ArrayList(Arrays.asList(TextUtils.split(recordListString, ",")));
}
currentFormat = Integer.parseInt(mSharedPreferences.getString("PREF_REC_LIST", "1"));
tempRecNum = mSharedPreferences.getString("TempRecNum", null);
audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
recorder = new MediaRecorder();
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),0);
if (error){
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
}else {
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
}
cleanDate = System.currentTimeMillis();
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
/**recorder.setAudioEncodingBitRate(16);
recorder.setAudioSamplingRate(96000);**/
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
mSharedPreferences.edit().putBoolean("isRecording", true).apply();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (RuntimeException e) {
File filepath = Environment.getExternalStorageDirectory();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
String tempPath = file.getAbsolutePath();
if(contactExists) {
boolean err = new File(tempPath + "/" +
getContactDisplayNameByNumber(tempRecNum, this)+"___"+
tempRecNum+"|__"+recCount+file_exts[currentFormat]).delete();
recordList.remove(recordList.size()-1);
}else{
boolean err = new File(tempPath + "/" +
"___"+tempRecNum+"|__"+recCount+file_exts[currentFormat]).delete();
recordList.remove(recordList.size()-1);
}
error = true;
startRecording();
}
}
private String getFilename() {
File filepath = Environment.getExternalStorageDirectory();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdir();
}
path = file.getAbsolutePath() + "/";
if(contactExists(this, tempRecNum, getContentResolver())) {
contactExists = true;
fileName = getContactDisplayNameByNumber(tempRecNum, this)+
"___"+tempRecNum+"|__"+recCount+file_exts[currentFormat];
recordList.add(fileName);
return (path + "/" + fileName);
}else {
contactExists = false;
fileName = "___"+tempRecNum+"|__"+recCount+file_exts[currentFormat];
recordList.add(fileName);
return (path + "/" + fileName);
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
edit().putBoolean("isRecording", false).apply();
Toast.makeText(RecorderService.this,
"Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(RecorderService.this,
"Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
.show();
}
};
#Override public void onDestroy(){
stopRecording();
super.onDestroy();
}
void stopRecording(){
try{
if (recorder != null) {
mSharedPreferences.edit().putString("RecordList", TextUtils.join(",", recordList)).apply();
mSharedPreferences.edit().putInt("RecCount", recCount+1).apply();
recorder.stop(); //This is where the error is thrown.
recorder.release();
recorder = null;
}
}catch(RuntimeException stopException){
stopException.printStackTrace();
}
}
I am trying to implement a pause and play function to some text using tts and MediaPlayer. However, I can't seem to be able to create a .wav file using the synthesizeToFile function.
I already added the required permission to the xml file:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is the file creation method I am currently using:
private String envPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Download";
private Uri fileUri;
public void fileCreate() {
String inputText = output.getText().toString();
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, inputText);
Log.d(TAG, "successfully created hashmap");
String destFileName = envPath + "/" + "tts_file.wav";
int sr = tts.synthesizeToFile(inputText, myHashRender, destFileName);
Log.d(TAG, "synthesize returns = " + sr);
File fileTTS = new File(destFileName);
if (fileTTS.exists()) {
Log.d(TAG, "successfully created fileTTS");
}
else {
Log.d(TAG, "failed while creating fileTTS");
}
fileUri = Uri.fromFile(fileTTS);
Log.d(TAG, "successfully created uri link: " + fileUri.getPath());
}
This is how I create the mediaPlayer:
fileCreate();
mp = MediaPlayer.create(this, fileUri);
Log.d(TAG, "successfuly created mediaplayer");
btnRead.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
mp.pause();
Log.d(TAG, "successfully paused");
} else {
mp.start();
Log.d(TAG, "successfully started");
}
}
});
Any ideas?
The method synthesizeToFile is asynchronous thus you should do the checking
File fileTTS = new File(destFileName);
if (fileTTS.exists()) {
Log.d(TAG, "successfully created fileTTS");
}
else {
Log.d(TAG, "failed while creating fileTTS");
}
in onUtteranceCompletedListener or UtteranceProgressListener