Errors with FileOutputstream and FileInputStream - android

I have a FileOutputstream here:
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".jpg";
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
default_b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
But I get an error on this line:
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
Saying that openFileOutput is undefined *(please note that this is in a base adapter class, and when I try to do it from context, Context.getApplicationContext().openFileOutput gets the error that "Cannot make a static reference to the non-static method getApplicationContext() from type Context") I also get the warning that Context.MODE_WORLD_WRITABLE is deprecated.
Then I have my FileInputstream here (in another class that extends BaseAdapter):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(mContextGV);
Log.d("GridViewAdapter", "new imageView added");
}
try {
FileInputStream in = new openFileInput("file");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
view.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
That has an error on this line:
FileInputStream in = new openFileInput("file");
saying that openFileInput is undefined and once again when I change it to:
FileInputStream in = new Context.getApplicationContext().openFileInput("file");
I get an error saying that "Context.getApplicationContext() cannot be resolved to a type"

Try to Replace File OutputStream Code
String fname = "Image-" + n ;
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/" + fname +".png");
FileOutputStream fos = new FileOutputStream(f);
default_b.compress(Bitmap.CompressFormat.PNG,90,fos);
} catch (Exception e) {
e.printStackTrace();
}
its works perfect For me to Save Image

Related

how to save editText color,size,Typeface?

i have an editText and I have a button that changes the color ,size and Typeface so when saving the file as pdf or txt file how can i get the this 3 things with the text i'm getting only the text with normal black style this is my code.
size.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtSpeechInput.setTextSize(25);
txtSpeechInput.setTextColor(Color.rgb(150,0,0));
txtSpeechInput.setTypeface(null, Typeface.BOLD);
the save code:
final File externalStorageDir = new File(
Environment
.getExternalStorageDirectory(), "MyVoiceText");
boolean success = true;
if (!externalStorageDir.exists()) {
success = externalStorageDir.mkdirs();
}
if (success) {
final Dialog dialog2 = new Dialog(MainActivity.this);
dialog2.setContentView(R.layout.dialog_save);
dialog2.show();
editsave = (EditText) dialog2.findViewById(R.id.edit_save);
pdf = (Button) dialog2.findViewById(R.id.pdf_save);
pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pdf.setEnabled(false);
txt.setEnabled(true);
}
});
txt = (Button) dialog2.findViewById(R.id.txt_save);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt.setEnabled(false);
pdf.setEnabled(true);
}
});
dia_save = (Button) dialog2.findViewById(R.id.dia_save);
dia_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String savename = editsave.getText().toString();
if(!txt.isEnabled()) {
File myFile = new File(externalStorageDir + "/" + savename + ".txt");
File myFile = new File(externalStorageDir + "/" + savename + ".txt");
try {
StringBuffer string = new StringBuffer();
string.append(txtSpeechInput.getText().toString());
Properties properties = new Properties();
// set the properties value
properties.put("text",string.append(txtSpeechInput.getText().toString())); properties.put("textstyle","bold");
properties.put("typeface",txtstyle);
properties.put("etxtColor",txtcolor);
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(string);
myOutWriter.close();
fOut.flush();
fOut.close();
} catch (Exception e) {
}
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
dialog2.dismiss();
}else if(!pdf.isEnabled()){
try
{
String savename2 = editsave.getText().toString();
String takeit = txtSpeechInput.getText().toString();
Document document = new Document(PageSize.A4);
Paragraph p = new Paragraph();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(Environment.getExternalStorageDirectory() + "/MyVoiceText/" +savename2+".pdf"));
document.open();
writer.getDirectContent();
p.add(new Phrase(takeit));
document.add(p);
document.close();
Log.d("OK", "done");
} catch (Exception e) {
//LOGGER.error(e.getMessage());
}
reload the text file
File sdcard = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyVoiceText/");
//Get the text file
File file = new File(sdcard, String.valueOf(selected));
InputStream input = null;
try {
input = new FileInputStream(file);
Properties prop = new Properties();
// load a properties file
prop.load(input);
}catch (Exception e){
e.printStackTrace();
}
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
catch (IOException e) {
//You'll need to add proper error handling here
}
By your code, it seems like you are using iTextPDF library to generate the PDF.
Use Font class of iTextPDF to create a new font and use it like below:
private static Font HelveticaBlue = new Font(Font.FontFamily.HELVETICA, 6,
Font.BOLD, BaseColor.BLUE);
new Paragraph("Blue ColorText"), HelveticaBlue);
We can add Properties to File that contains entries in key and value format.
And we can write our own Properties in File also retrieve.
like below code:
Write Properties to File:
private void addPropertiesToFile(String mytext){
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/CHETAN");
if (!myDir.exists ())
myDir.mkdirs();
String fname = "mytext.txt";
File myFile = new File (myDir, fname);
if (!myFile.exists ())
myFile.createNewFile();
Properties properties = new Properties();
// set the properties value
properties.put("text","dsf");
properties.put("textstyle","bold");
properties.put("typeface","arial");
properties.put("etxtColor","green");
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(mytext);
// save properties to project root folder
properties.store(myOutWriter,null);
myOutWriter.close();
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Retrieve Properties from File:
private void retrievePropertiesFromFile(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/CHETAN");
String fname = "mytext.txt";
File myFile = new File (myDir, fname);
InputStream input = null;
try {
input = new FileInputStream(myFile);
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
Log.i(getClass().getSimpleName(),prop.getProperty("text"));
Log.i(getClass().getSimpleName(),prop.getProperty("textstyle"));
Log.i(getClass().getSimpleName(),prop.getProperty("typeface"));
Log.i(getClass().getSimpleName(),prop.getProperty("typeface"));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

java.io.FileNotFoundException: mounted/saved_images/Image-6999.jpg (No such file or directory)

I create take a screenshot in Android through a button click, but image can't be saved. I have an error message in "No such file or directory". What can I do?
My code:
public class MainActivity extends Activity {
LinearLayout L1;
ImageView image;
Bitmap bm;
File file;
FileOutputStream fileoutputstream;
View v1;
ByteArrayOutputStream bytearrayoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bytearrayoutputstream = new ByteArrayOutputStream();
L1 = (LinearLayout) findViewById(R.id.layout);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
final ScrollView scrollview = (ScrollView) findViewById(R.id.scroll);
scrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener(){
#Override
public void onScrollChanged() {
if (scrollview != null) {
if (scrollview.getChildAt(0).getBottom() <= (scrollview.getHeight() + scrollview.getScrollY())) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
} else {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView01);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("bottom-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
// String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
});
}
}
Image can't be saved in sdcard. What mistake did I make? I can't understand what is the problem or how to save an image on sdcard?
I use this method to capture screen. First, add proper permission to save file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
Try this,
Before write the file you have to check the permissions for marshmallow
public static final int REQUEST_STORAGE = 101;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE);
} else {
writeFile()
}
}
/*check permissions for marshmallow*/
#SuppressWarnings("BooleanMethodIsAlwaysInverted")
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
/*get Permissions Result*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG", "PERMISSION_GRANTED");
writeFile();
} else {
Toast.makeText(mContext, "The app was not allowed to write to your storage", Toast.LENGTH_LONG).show();
}
}
}
}
public void writeFile()
{
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
final String root = Environment.getExternalStorageState().toString();
File myDir=new File(root + "/saved_images/" );
State is no storage. Change to:
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images" );
And adapt your code for mkdirs as explained in comment.
if (!myDir.exists())
{
if (!myDir.mkdirs())
{
Toast.makeText(this, "Sorry could not create directory:\n" + myDir.getAbsolutePath(), Toast.LENGTH_LONG).show();
return;
}
}
You complain that the file is not created but it starts with the directory.
You never answered my question about Androud version. But for 6.0 and above you should ask the user also for runtime permission. Add that code.
Or, as a quick solution, go to the Android settings of your app and switch the Storage toggle button to ON.

Create file from drawable to send with sendbird

I want use sendFileMessage in sendbird api. It need file value and I want use this file from drawable (or assets). sendBird API
this is snipped code from sendbird
Hashtable<String, Object> info = Helper.getFileInfo(getActivity(), uri);
final String path = (String) info.get("path");
File file = new File(path);
String name = file.getName();
String mime = (String) info.get("mime");
int size = (Integer) info.get("size");
sendFileMessage(file, name, mime, size, "", new BaseChannel.SendFileMessageHandler() {
public void onSent(FileMessage fileMessage, SendBirdException e) {
if (e != null) {
return;
}
mAdapter.appendMessage(fileMessage);
mAdapter.notifyDataSetChanged();
}
});
This code working well which I got uri from open image intent. but I want to use to other purpose and I want to replace this code
File file = new File(path);
become something like
File file = new File(<path or uri from drawable or assets>);
I have tried with uri
Uri uri = Uri.parse("android.resource://com.package.name/raw/filenameWithoutExtension");
File file = new File(uri.getPath());
with inputStream
try {
File f=new File("file name");
InputStream inputStream = getResources().openRawResource(R.raw.myrawfile);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
always failed in getting file and return error code ERR_REQUEST_FAILED 800220
Have you tried like below?
String fileName = FILE_NAME;
File cachedFile = new File(this.getActivity().getCacheDir(), fileName);
try {
InputStream is = getResources().openRawResource(R.raw.sendbird_ic_launcher);
FileOutputStream fos = new FileOutputStream(cachedFile);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
fos.write(buf, 0, len);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
groupChannel.sendFileMessage(cachedFile, fileName, "image/jpg", (int) cachedFile.length(), "", new BaseChannel.SendFileMessageHandler() {
#Override
public void onSent(FileMessage fileMessage, SendBirdException e) {
}
});
This works for me.

Getting bitmap from external storage

I have saved a bitmap to external storage via FileOutputStream and am trying to retrieve that file in another class so that it can be put into a imageView. Here is where I save the bitmap:
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".png";
File file = new File (myDir, fname);
Log.i("AppInfoAdapter", "" + file);
if (file.exists()) file.delete();
try {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + fname + ".png");
// FileOutputStream out = mContext.getApplicationContext().openFileOutput("bitmapA", Context.MODE_WORLD_WRITEABLE);
FileOutputStream out = new FileOutputStream(file);
default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and I am trying to recieve it here:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
FileInputStream in = Context.openFileInput("bitmapA");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
view.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
I have done plenty of searching on this and have come across multiple ways of doing the same thing but for at the moment, this way of doing it doesn't work.
I have seen it where you use openFileOutput and openFileInput and then I have also seen where people just create new FileInput and Output streams.
Which one is better to use for the bitmap?
and then depending on which one is better to use (since I have both set up for when I save the bitmap), how can I get that bitmap from external storage?
Thanks!

Saving image overwrite in sdcard android

i'm using the following code for saving the image
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
// File root = Environment.getExternalStorageDirectory();
// File file = new File(root, "androidlife.jpg");
// File file = new File(Environment.getExternalStorageDirectory()
// + File.separator + "/test.jpg");
Random fCount = new Random();
// for (int i = 0; i < 10; i++) { Comment by Lucifer
int roll = fCount.nextInt(600) + 1;
//System.out.println(roll);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(roll) +".jpg" );
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// } Comment by Lucifer
it save the image perfectly but overwrite when i press the save button twice...What can be the issue? Any sugestion??
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
You have given a static file name.
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
So, Everytime it is going to create a image with test.jpg name and at a same location. The only logic you need to implement is to change your file name to be a dynamic file name. You can try it in this way
static int fCount = 0;
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(fCount++) +".jpg" );
Now above line is going to create a new file every time, starting with name test0.jpg, test1.jpg ... and so on.
But this could create a problem when you close your application and restart your application. Because it will going to start again from 0 counter.
So i suggest you to go with a random number contacatination with file name.
sticker_view.setLocked(true);
sticker_view.setDrawingCacheEnabled(true);
Bitmap bitmap = sticker_view.getDrawingCache();
Log.e("BITMAP", "onOptionsItemSelected: " + bitmap);
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Edited Image");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String photoName = "Image-" + n + ".jpg";
Log.e("PHOTONAME", "onOptionsItemSelected: " + photoName);
File file = new File(newDir, photoName);
String filePath = file.getAbsolutePath();
Log.e("FILEPATH", "onOptionsItemSelected: " + filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(EditActivity.this, "Image Already Exist.", Toast.LENGTH_SHORT).show();
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(file);
Log.e("OUT", "onOptionsItemSelected: " + out);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
bitmap.recycle();
Toast.makeText(EditActivity.this, "Saved In Edited Image.", Toast.LENGTH_SHORT).show();
item.setVisible(false);
MediaScannerConnection.scanFile(EditActivity.this, new String[]{file.getAbsolutePath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Intent intent = new Intent();
intent.setAction("URI");
intent.putExtra("uri", filePath);
sendBroadcast(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
You can just add System.currentTimeMillis() in the name of your file name to get a complete unique file name. This will add current time in milliseconds since epoch to your file name and unless you can create more than one file in a single millisecond, no overwrite will be done.

Categories

Resources