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
Related
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.
I am trying to get the file from picking image from photos and get intent data, save the file in internal memory and use the file to load on Image views.
But I am getting the error as follows:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.dailyfaithapp.dailyfaith/Files/MI_10052020_1711.png: open failed: ENOENT (No such file or directory)
I checked on the lower version of api i.e. on 24 it worked once or twice but again it failed.
And on api 29 its not working at all. For that I followed this url :
https://medium.com/#sriramaripirala/android-10-open-failed-eacces-permission-denied-da8b630a89df
I checked the code in java and tried the same but still its giving the error.
I am also checking for runtime permissions and have specified permissions in manifest file.
Following is my code:
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name = "android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name = "android.permission.WAKE_LOCK" />
<uses-permission android:name = "android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "com.google.android.apps.photos.permission.GOOGLE_PHOTOS" />
Checking runtime permissions :
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
;
}
private void requestPermissionAndContinue() {
if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
&& ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Allow Daily Faith to access photos," +
"media, and files on your device?");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(ThemesActivity.this,
new String[]{WRITE_EXTERNAL_STORAGE
, READ_EXTERNAL_STORAGE}, 200);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
Log.e("", "permission denied, show dialog");
} else {
ActivityCompat.requestPermissions(ThemesActivity.this,
new String[]{WRITE_EXTERNAL_STORAGE,
READ_EXTERNAL_STORAGE}, 200);
}
} else {
selectImageFromGallery();
}
}
Checking if permission is given:
if (!checkPermission()) {
selectImageFromGallery();
} else {
if (checkPermission()) {
requestPermissionAndContinue();
} else {
selectImageFromGallery();
}
}
Opening intent :
public void selectImageFromGallery()
{
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 2);
}
Get intent data on result :
#RequiresApi(api = Build.VERSION_CODES.KITKAT) #Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a image.
// The Intent's data Uri identifies which item was selected.
if (data != null) {
customTheme = true;
// This is the key line item, URI specifies the name of the data
mImageUri = data.getData();
// Saves image URI as string to Default Shared Preferences
SharedPreferencesData sharedPreferencesData =
new SharedPreferencesData(this);
sharedPreferencesData.setStr("customThemeSet","true");
try {
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(getContentResolver(), mImageUri);
/* Utils.storeImage(bitmap,
ThemesActivity.this);
File file = Utils.getOutputMediaFile(ThemesActivity.this);
*/
try {
final ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(
mImageUri, "r");
final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
Utils.storeImage(bitmap,
ThemesActivity.this);
File file = Utils.getOutputMediaFile(ThemesActivity.this);
int color = Utils.getDominantColor(bitmap);
Log.d("Bitmap", bitmap.toString());
Boolean isDark = Utils.isColorDark(color);
if(customTheme) {
for (Themes themes : themesArrayList) {
themes.setCustomTheme(file.getPath());
themes.setDark(isDark);
}
if(isDark)
sharedPreferencesData.setStr("ThemeColor","dark");
else
sharedPreferencesData.setStr("ThemeColor","light");
themesAdapter = new ThemesAdapter(themesArrayList, this,customTheme);
recyclerView.setAdapter(themesAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
Log.e("Failed", "Failed to Parse Image Uri", e);
try {
throw new Exception("failed to parse image uri");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
}
Saving and getting file
public static File getOutputMediaFile(Context context){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getApplicationContext().getPackageName()
+ "/Files");
// 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()){
mediaStorageDir.mkdirs();
}
else {
return null;
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".png";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
public static void storeImage(Bitmap image,Context context) {
File pictureFile = getOutputMediaFile(context);
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
Before I was getting EACCESS error when I only used above two funtions to save the file.
Later I tried Parcel file descriptor but not working
Why am I getting this error? Is it only on api level 29 or below too?
What can be the solution for this to run on all devices?
Here is what worked for me Using the downloads folder which all phones old and new have public access to..
try{
File csvfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/brcOrdersaved.csv");
final String filename = csvfile.toString();
if (!csvfile.exists()) {
// displayMsg(context, "No Saved Order: ");
return (false);
}
FileReader fr = new FileReader(filename);
BufferedReader reader = new BufferedReader(fr);
String csvLine = "";
final char Separator = ',';
final char Delimiter = '"';
final char LF = '\n';
final char CR = '\r';
boolean quote_open = false;
if (reader.equals(null)) {
displayMsg(context, "NULL");
return (false);//rww 11/13/2021
}
int i = 0;
while (!myendofcsvfile) {
csvLine = reader.readLine();
if (csvLine == null) {
myendofcsvfile = true;
}
// do stuff here
}
fr.close();
fileexists = true;
} catch (Exception e) {
String msg = "Can not Load Saved Order ";
fileexists = false;
return (fileexists);
}
I add this permissions, and it works.
<uses-permission
enter code hereandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
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 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());
}
}
I am trying to pass a String from one activity to another and it returns NULL, the string in question has the uri of an image that I saved previously.
in the activity one I have a function that saves the image and puts the string URI in a variable of the class. Next I put the code.
Activity One
public class PaintActivity extends AppCompatActivity implements PaintView {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paint);
tabLayout.setupWithViewPager(viewPager);
intent = new Intent(this, ResultsActivity.class);
readyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
paintImage.buildDrawingCache();
Bitmap bitmap = paintImage.getDrawingCache();
saveImage(bitmap);
presenter.getColorList();
startActivity(intent);
} catch(Exception e) {
e.getMessage();
}
}
});
}
private void saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/Tersuave");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
// Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(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);
image_path = uri.toString();
intent.putExtra("image_path", image_path);
}
});
}
}
Then in onCreate method
paintImage.buildDrawingCache();
Bitmap bitmap = paintImage.getDrawingCache();
// this method is the one above
saveImage(bitmap);
presenter.getColorList();
startActivity(intent);
Activity Two
Intent intent = getIntent();
// return null
String image = intent.getStringExtra("image_path");
Once you persist the image file after scanner result you could do something like this to start next activity.
MediaScannerConnection.scanFile(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);
image_path = uri.toString();
Intent intent = new Intent(context,Activity2.class);
intent.putExtra("image_path", image_path);
startActivity(intent);
}
});
And inside Activity2 you could do something like this.
String imageFilePath = getIntent().getStringExtra("image_path");
Looking into your implementation you are triggering activity ResultsActivity before and adding the value image_path in to extra into the call back which is delayed.
MediaScannerConnection.scanFile(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);
image_path = uri.toString();
intent.putExtra("image_path", image_path); // this will be called after some time
}
});
presenter.getColorList();
startActivity(intent);
Add above two line after intent.putExtra inside the OnScanCompletedListener and remove it form onClickListener
In your main activity you should do this if yo want to pass the string in the intent
FirstActivity
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("Keyname", image_path);
startActivity(intent);
SecondActivity
onCreate....
if(savedInstanceState == null)
{
Bundle extras = getIntent().getExtras();
if (extras == null)
{
//Extra bundle is null
}else{
String image = extras.getString("Keyname");
}