How to save file in storage on Android 12 - java

In my application I want create screen recorder and I want save it into storage!
For this I create service and write some code!
But after run service, Immediately stop it and show me Recorder stop toast!
I write below code into service :
Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message message) {
Log.e("ServiceErrors","RecorderService - Handler : " + message.getData().toString());
Toast.makeText(RecorderService.this, "Recorder stop", Toast.LENGTH_SHORT).show();
}
};
/* Its weird that android does not index the files immediately once its created and that causes
* trouble for user in finding the video in gallery. Let's explicitly announce the file creation
* to android and index it */
private void indexFile() {
//Create a new ArrayList and add the newly created video file path to it
ArrayList<String> toBeScanned = new ArrayList<>();
toBeScanned.add(SAVEPATH);
String[] toBeScannedStr = new String[toBeScanned.size()];
toBeScannedStr = toBeScanned.toArray(toBeScannedStr);
//Request MediaScannerConnection to scan the new file and index it
MediaScannerConnection.scanFile(this, toBeScannedStr, null, (path, uri) -> {
//Show toast on main thread
Message message = mHandler.obtainMessage();
Log.e("ServiceErrors","RecorderService Index : " + message.toString());
message.sendToTarget();
stopSelf();
});
}
//Stop and destroy all the objects used for screen recording
private void destroyMediaProjection() {
this.mAudioManager.setParameters("screenRecordAudioSource=-1");
try {
mMediaRecorder.stop();
indexFile();
} catch (RuntimeException e) {
if (new File(SAVEPATH).delete())
Toast.makeText(this, "ذخیره ویدیو با مشکل روبرو شد", Toast.LENGTH_SHORT).show();
} finally {
mMediaRecorder.reset();
mVirtualDisplay.release();
mMediaRecorder.release();
if (mMediaProjection != null) {
mMediaProjection.unregisterCallback(mMediaProjectionCallback);
mMediaProjection.stop();
mMediaProjection = null;
}
stopSelf();
}
isRecording = false;
}
UPDATE
Save to storage location code :
public void getValues() {
String res = getResolution();
setWidthHeight(res);
FPS = 25;
//BITRATE = 7130317;
BITRATE = 5530317;
audioRecSource = "1";
//saveLocation = Environment.getExternalStorageDirectory() + File.separator + ConstKeys.APPDIR + APPDIR_ORIGINAL;
saveLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
+ File.separator + ConstKeys.APPDIR + APPDIR_ORIGINAL;
File saveDir = new File(saveLocation);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && !saveDir.isDirectory()) {
saveDir.mkdirs();
}
String saveFileName = getFileSaveName();
SAVEPATH = saveLocation + File.separator + saveFileName + ".mp4";
}
How can I fix it? Please help me <3

On Android 11+ you cannot save video files in a picture directory.
So no .mp4 in public DCIM directory.

Related

How to get PDF File Path In Android 11 and 12

I tried much code for getting pdf path in android 11 or 12 but only working in android 10 or below devices.
Can you please help me? I share my code of lines
Intent calling like this
Intent intent = new Intent();
intent.setType("application/pdf");
statusAdapter = "pdf";
pos = position;
intent.setAction(Intent.ACTION_GET_CONTENT);
someActivityResultLauncher.launch(Intent.createChooser(intent, "Select PDF"));
someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
if (data == null) {
//error
return;
}
try {
final Uri pdfUri= data.getData();
File pdfFile = new File(getPath(pdfUri));
long length = pdfFile.length();
length = length / 1024;
Toast.makeText(CreateSubEventActivity.this, "File Path : " + pdfFile.getPath() + ", File size : " + length + " KB", Toast.LENGTH_SHORT).show();
// uploadFile(imageFile);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(CreateSubEventActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
});
getPath calling like this
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
If you want to access a File or want a file path from a Uri that was returned from MediaStore, I have got a library that handles all the exceptions you might get. This includes all files on the disk, internal and removable disk. When selecting a File from Dropbox, for example, the File will be copied to your applications directory where you have full access, the copied file path will then be returned.
Let me share my experience to fix this stuff after so reading all.
Get input stream from URI
final Uri pdfUri= data.getData();
getContentResolver().openInputStream(pdfUri)
then do your stuff with InputStream, like I have uploaded pdf using okHttp
try {
RequestBody pdffile = new RequestBody() {
#Override public MediaType contentType() { return MediaType.parse("application/pdf"); }
#Override public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(inputStream);
sink.writeAll(source);
} finally {
Util.closeQuietly(source);
}
}
#Override
public long contentLength() {
try {
return inputStream.available();
} catch (IOException e) {
return 0;
}
}
};
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", "fname.pdf", pdffile)
//.addFormDataPart("Documents", value) // uncomment if you want to send Json along with file
.build();
Request request = new Request.Builder()
.url(serverURL)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS)
.addInterceptor(chain -> {
Request original = chain.request();
Request.Builder builder = original.newBuilder().method(original.method(), original.body());
builder.header("key", key);
return chain.proceed(builder.build());
})
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Call call, final IOException e) {
// Handle the error
setIsLoading(false);
getNavigator().uploadIssue("Facing some issue to upload this file.");
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
setIsLoading(false);
if (!response.isSuccessful()) {
getNavigator().uploadIssue("Facing some issue to upload this file.");
}else {
// Upload successful
getNavigator().uploadedSucessfully();
}
}
});
return true;
} catch (Exception ex) {
// Handle the error
ex.printStackTrace();
}
This one helps in my case on Android 11 hope anyone gets this helpful
private String copyFile(Uri uri, String newDirName) {
Uri returnUri = uri;
Cursor returnCursor = this.getContentResolver().query(returnUri, new String[]{
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
}, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File output;
if (!newDirName.equals("")) {
File dir = new File(this.getFilesDir() + "/" + newDirName);
if (!dir.exists()) {
dir.mkdir();
}
output = new File(this.getFilesDir() + "/" + newDirName + "/" + name);
} else {
output = new File(this.getFilesDir() + "/" + name);
}
try {
InputStream inputStream = this.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(output);
int read = 0;
int bufferSize = 1024;
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return output.getPath();
}
String newPath = copyFileToInternalStorage(uri, getResources().getString(R.string.app_name));

Save file on google drive

Hey I'm trying do application where i check my current location and save this location in ".txt" files. My application save this location in every "user set time" seconds. And it's work. Also I want add save files to Google drive. But I don't know how. Is there any method by which I can create a folder and save ".txt" files same as i did with local folder?
public class Save extends AppCompatActivity {
boolean sms = false;
int n_seconds, n_minutes, n_sum;
private String path = Environment.getExternalStorageDirectory().toString() + "/Loc/Save";
private Button buttonStartThread;
private Handler mainHandler = new Handler();
private volatile boolean stopThread = false;
NumberPicker edit_text_input_back, edit_text_input_back_2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background);
buttonStartThread = findViewById(R.id.button_start_thread);
edit_phone_number = findViewById(R.id.edit_phone_number);
edit_mail = findViewById(R.id.edit_email);
edit_text_input_back = (NumberPicker) findViewById(R.id.edit_text_input_back);
edit_text_input_back.setMaxValue(60);
edit_text_input_back.setMinValue(0);
edit_text_input_back.setValue(0);
edit_text_input_back_2 = (NumberPicker) findViewById(R.id.edit_text_input_back_2);
edit_text_input_back_2.setMaxValue(60);
edit_text_input_back_2.setMinValue(0);
edit_text_input_back_2.setValue(0);
edit_text_input_back.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_seconds = i1;
}
});
edit_text_input_back_2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_minutes = 60 * i1;
}
});
}
public void startThread(View view) {
stopThread = false;
n_sum = n_seconds + n_minutes;
ExampleRunnable runnable = new ExampleRunnable(n_sum);
new Thread(runnable).start();
buttonStartThread.setEnabled(false);
}
public void stopThread(View view) {
stopThread = true;
buttonStartThread.setEnabled(true);
}
class ExampleRunnable implements Runnable {
int seconds;
ExampleRunnable(int seconds) {
this.seconds = seconds;
}
#Override
public void run() {
for (; ; ) {
for (int i = 0; i < seconds; i++) {
if (stopThread)
return;
if (i == n_sum-1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createDir();
createFile();
}
});
}
Log.d(TAG, "startThread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private void createDir() {
File folder = new File(path);
if(!folder.exists()){
try {
folder.mkdirs();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
private void createFile() {
File file = new File(path+"/"+System.currentTimeMillis()+".txt");
FileOutputStream fileOutputStream;
OutputStreamWriter outputStreamWriter;
try {
Intent intent = getIntent();
Double lat = intent.getDoubleExtra("adres", 0);
Double lon = intent.getDoubleExtra("adres2", 0);
String adr = intent.getStringExtra("adres3");
fileOutputStream = new FileOutputStream(file);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.append("Your adress: " + adr + ". " + "Your latitude: " + lat + ", " + "longtitude: " + lon+".");
outputStreamWriter.close();
fileOutputStream.close();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Thank you in advance
There are ample sources you can check for creating a folder, and uploading a file to Google Drive
Creating Folder
File fileMetadata = new File();
fileMetadata.setName("Invoices");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = driveService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Uploading File
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
For the specific mime type of a txt file, you might need to refer this StackOverflow post (text/plain). For specific Google applications mime types, please see documentation.

Downloading a PDF and displaying it (FileUriExposedException)

As a preface, I am familiar with coding (2 years in highschool) but am a complete novice when it comes to Android Studio (and Java, in general). I've been searching for solutions for my problem, but due to my inexperience I have no idea how to implement the solutions to my project.
In short, I need to download a pdf from some external URL, store it into external storage, and display it using some pdf-viewer application. I've been getting error:
...
android.os.FileUriExposedException: file:///storage/emulated/0/pdf/Read.pdf exposed beyond app through Intent.getData()
...
I've been using this source on using an intent to open a pdf-viewer and this source on "File Provider" as references.
Below is what I have so far:
Fire (with a clickable TextView that should download and display the pdf)
public class Fire extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fire);
final TextView testButton = findViewById(R.id.testPDF);
// File file = getFilesDir();
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Fire.this, pdfView.class);
startActivity(intent);
}
});
pdfView activity
public class pdfView extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_view);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile(__PDF_URL___, file);
showPdf();
}
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
Downloader class
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
From my research, it seems that my problem stems from my usage of URI instead of a "File provider." Also, it seems the solution that implements a "File Provider" uses Context in some form or another, and I'm confused on what the purpose of context is and how to implement it.
If you do not have answers that is fine. Any information on how to figure this out or even understand the concept is good enough for me.
If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.
1) First Add a FileProvider tag in AndroidManifest.xml under tag as below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}.my.package.name.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
</manifest>
2) Then create a provider_paths.xml file in res/xml folder. Folder may be needed to created if it doesn't exist.
<paths>
<external-path name="external_files" path="."/>
</paths>
3) Now create PdfDownload.java class file and paste below code:
public class PdfDownload extends Activity {
TextView tv_loading;
Context context;
int downloadedSize = 0, totalsize;
float per = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
isStoragePermissionGranted();
super.onCreate(savedInstanceState);
tv_loading = new TextView(this);
tv_loading.setGravity(Gravity.CENTER);
tv_loading.setTypeface(null, Typeface.BOLD);
setContentView(tv_loading);
downloadAndOpenPDF();
}
public static String getLastBitFromUrl(final String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
void downloadAndOpenPDF() {
final String download_file_url = getIntent().getStringExtra("url");
new Thread(new Runnable() {
public void run() {
Uri path = Uri.fromFile(downloadFile(download_file_url));
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(PdfDownload.this, BuildConfig.APPLICATION_ID, downloadFile(download_file_url));
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
tv_loading
.setError("PDF Reader application is not installed in your device");
}
}
}).start();
}
File downloadFile(String dwnload_file_path) {
File file = null;
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.connect();
String test = getLastBitFromUrl(dwnload_file_path);
String dest_file_path = test.replace("%20", "_");
// set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
// // create a new file, to save the downloaded file
file = new File(SDCardRoot, dest_file_path);
if (file.exists()) {
return file;
}
FileOutputStream fileOutput = new FileOutputStream(file);
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// this is the total size of the file which we are
// downloading
totalsize = urlConnection.getContentLength();
setText("Starting PDF download...");
// create a buffer...
byte[] buffer = new byte[1024 * 1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
per = ((float) downloadedSize / totalsize) * 100;
if ((totalsize / 1024) <= 1024) {
setText("Total PDF File size : " + (totalsize / 1024)
+ " KB\n\nDownloading PDF " + (int) per + "% complete");
} else {
setText("Total PDF File size : " + (totalsize / 1024) / 1024
+ " MB\n\nDownloading PDF " + (int) per + "% complete");
}
// setText("configuring your book pleease wait a moment");
}
// close the output stream when complete //
fileOutput.close();
// setText("Download Complete. Open PDF Application installed in the device.");
setText("configuaration is completed now your book is ready to read");
} catch (final MalformedURLException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final IOException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final Exception e) {
setTextError(
"Failed to download image. Please check your internet connection.",
Color.RED);
}
return file;
}
void setTextError(final String message, final int color) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setTextColor(color);
tv_loading.setText(message);
}
});
}
void setText(final String txt) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setText(txt);
}
});
}
private static final String TAG = "MyActivity";
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG, "Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission: " + permissions[0] + "was " + grantResults[0]);
}
}
}

app crashing after taking a pic on samsung phones only

I am developing an Android app in which the user can select a picture from the gallery or can click a photo through the phone's camera and save in the app's folder called FiZZ. The camera part of app runs perfectly fine on all android phones except Samsung.The code given below throws a NullPointerException at image.setPath(fileUri.getPath()); and crashes.
MainActivity.java:
Below is how I take a photo and save it in /DCIM/FiZZ folder:
/**
* take a photo
*/
private void activeTakePhoto() {
final Dialog dialog = new Dialog(MainActivity.this);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
int MEDIA_TYPE_IMAGE = 1;
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
try {
FileOutputStream outputStream_image = openFileOutput(file_image, MODE_WORLD_READABLE);
outputStream_image.write(string.getBytes());
outputStream_image.close();
Toast.makeText(getBaseContext(), "location of image saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private Uri getOutputMediaFileUri(int MEDIA_TYPE_IMAGE) {
// TODO Auto-generated method stub
if(isExternalStorageWritable()) {
//Toast.makeText(getBaseContext(), "value: "+ Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE)), Toast.LENGTH_LONG).show();
return Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_IMAGE));
}
else
return null;
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "FiZZ");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("FiZZ", "failed to create directory");
Toast.makeText(getBaseContext(),"File directory creation failed",Toast.LENGTH_LONG).show();
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
int MEDIA_TYPE_IMAGE = 1;
if (type == MEDIA_TYPE_IMAGE){
//String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname= "IMG_"+ timeStamp + ".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
The request_image_capture case is called:
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String filePath = imageFile.getAbsolutePath();
String imageName = String.valueOf(mediaFile);
Cursor cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.MediaColumns._ID);
String picturePath = cursor.getString(column_index_data);
MyImage image = new MyImage();
image.setTitle(imageName);
image.setDescription(" ");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
image.setName(null);
image.setPriority("OFF");
images.add(image);
daOdb.addImage(image);
adapter.notifyDataSetChanged();
cursor.close();
} else {
MyImage image = new MyImage();
image.setTitle(imageName);
image.setDescription(" ");
image.setDatetime(System.currentTimeMillis());
image.setPath(fileUri.getPath());//NullPointerException
image.setName(null);
image.setPriority("OFF");
images.add(image);
daOdb.addImage(image);
adapter.notifyDataSetChanged();
//swipelist.invalidateViews();
}
}

Android TextToSpeech.synthesizeToFile() file is not created

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

Categories