I am trying to use a method to generate a bitmap from Layouts and save the bitmap to a file in the internal memory. However, the getApplicationContext() is not resolved.
Here is the code for the method
private void generateAndSaveBitmap(View layout) {
//Generate bitmap
layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap imageToSave = layout.getDrawingCache();
//Create a file and path
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File fileName = new File(directory, "sharableImage.jpg");
if (fileName.exists())
fileName.delete();
//Compress and save bitmap under the mentioned fileName
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileName);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// return directory.getAbsolutePath();
}
Used some help from StackOverFlow codes to generate this method. Even after reading related queries on getApplicationContext(), I am unable to find the issue. Any help would be really appreciated
EDIT : Forgot to mention, that the method generateAndSaveBitmap(View layout) is defined inside a separate class
Regards
Step #1: Delete ContextWrapper cw = new ContextWrapper(getApplicationContext());, as you do not need it.
Step #2: Replace cw.getDir("imageDir", Context.MODE_PRIVATE); with layout.getContext().getDir("imageDir", Context.MODE_PRIVATE);
Also, please move this disk I/O to a background thread.
Try ,
ContextWrapper cw = new ContextWrapper(getActivity());
incase it's a fragment.
Have you tried:
File dir = getApplicationContext().getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
Now, from the image processing to the write of the file into the directory everything should be done off thread. Encapsulate it in an AsyncTask when possible and within it move generateAndSaveBitmap() method to it.
Related
I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.
I'm trying to implement the "share" button. It is necessary to send a picture.
That's what I'm doing:
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
File outputDir = context.getCacheDir();
File outputFile = null;
try {
outputFile = File.createTempFile("temp_", ".jpg", outputDir);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent,
getResources().getText(R.string.send_via)));
but I get a message saying that it's impossible to upload an image. What's the matter?
First, third-party apps have no rights to access files in your portion of internal storage.
Second, on Android 7.0+, you cannot use file Uri values, such as those returned by Uri.fromFile().
To solve both problems, use FileProvider to make the image available to other apps. Use FileProvider.getUriForFile() instead of Uri.fromFile(), and be sure to add FLAG_GRANT_READ_URI_PERMISSION to the Intent.
This sample app demonstrates using FileProvider with third-party apps (for ACTION_IMAGE_CAPTURE and ACTION_VIEW, but the same technique will work for ACTION_SEND).
I found lot of topics with the same problem, but they couldn't fix mine.
I initially write a file as follow:`
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File notefile = new File(root, sFileName);
FileWriter writer = null;
try {
writer = new FileWriter(notefile);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.append(sBody);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Don't worry about the try and catch blocks, i will clear them later :D.
And this is the reader which should works in the same directory ("Notes" of the sdcard, if it doesn't exist, will be created), read the file, and put it on a Notify as you can see:`
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, "Nota.txt");
//Read text from file
text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close() ;
}catch (IOException e) {
e.printStackTrace();
}
I really don't understand why i get this problem, i even try with
getExternalStorageDirectory().getAbsolutePath()
but without success.
Can someone help me?
You've tried to check with a debugger if root exists when you do:
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
I do not think it will create the folder when you write the file
To write a file in external storage,
you need to have WRITE_EXTERNAL_STORAGE permission enabled.
Why are you trying to write a file in external storage?
I mean if you want this file for your app only means, use context.getExternalDirs() to get your app's sandbox, it doesn't require write permission, above android 4.2(Jelly bean).
If you want to share the file to other apps, you're doing the right job.
And before writing the file, check whether external storage is mounted programmatically.
Problem Solved
I used SharedPreferences of Android.
I stored the data in MainActivity and take in in my Class as follow:
MainActivity
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("string_id", InputString); //InputString: from the EditText
editor.commit();
In my Class to get my data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String data = prefs.getString("string_id", "no id"); //no id: default value
Here is I want to make. I want to make an app, for example it has a button that will download a certain video file and put it on the resource(raw) folder. Is it possible?
Short answer : You can not.
You can not, under any circumstance, write/dump a file to the raw/assets folder in runtime.
What you can do is to download the video and store it into Internal Memory (application reserved storage) or External Memory (usually your SDCard))
For example, you can store media files, for instance a Bitmap to your external storage like this.
private void saveAnImageToExternalMemory(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "yourimagename.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);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And equally, read an file, in this example an image (which is then loaded to an imageView), from external memory
private void loadImageFromStorage(String path){
try {
File f=new File(path, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Edit: Additionally, you can store your data into internal memory
Alternatively you can also save the Bitmap to the internal storage in
case the SD card is not available or for whatever other reasons you
may have. Files saved to the internal storage are only accessible by
the application which saved the files. Neither the user nor other
applications can access those files
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = context.openFileOutput("yourimage.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
Check this documentation for more information
Regards,
I have a Java form in which you can select a file to open. I have that file:
File my_file = ...
I want to be able to save my file as a different name.
how can I do it using "File my_file"?
I tried:
File current_file = JPanel_VisualizationLogTab.get_File();
String current_file_name = current_file.getName();
//String current_file_extension = current_file_name.substring(current_file_name.lastIndexOf('.'), current_file_name.length()).toLowerCase();
FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fileDialog.setFile(current_file_name);
fileDialog.setVisible(true);
But that doesn't save the file.
I would recommend using the Apache Commons IO library to make this task easier. With this library, you could use the handy FileUtils class that provides many helper functions for handling file IO. I think you would be interested in the copy(File file, File file) function
try{
File current_file = JPanel_VisualizationLogTab.get_File();
File newFile = new File("new_file.txt");
FileUtils.copyFile(current_file, newFile);
} catch (IOException e){
e.printStackTrace();
}
Documentation
If you want to copy it with a different name, i found this piece of Code via google
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
now you can call it with
File inF = new File("/home/user/inputFile.txt");
File outF = new File("/home/user/outputFile.txt");
copyFile(inF, outF);
it´s just important that both Files exist, otherswise it will raise an exception
You can rename the file name.
Use:
myfile.renameTo("neeFile")
There is a Method called renameTo(new File("whatever you want")); for File Objects