I'm trying to keep adding text into my file (internal storage)
it was tried using FileOutputStream and it was fine but after i changed to use FileWriter then i started having the read-only file-system error
EditText edd = findViewById(R.id.editTextData);
Spinner spp = findViewById(R.id.spinnerCategory);
String text1 = edd.getText().toString();
String text2 = spp.getSelectedItem().toString();
String filepath = text2 + ".txt";
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filepath, true));
bw.write(text1);
bw.newLine();
bw.close();
Toast.makeText(getBaseContext(), "Information Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
} //End try catch statement
}```
It's supposed to say Information Saved but i keep getting read-only file system
EditText edd = findViewById(R.id.editTextData);
Spinner spp = findViewById(R.id.spinnerCategory);
String text1 = edd.getText().toString();
String text2 = spp.getSelectedItem().toString();
String filename = text2 + ".dat";
try {
File fa = new File(getFilesDir(),filename); //getting the filename path
FileWriter fw = new FileWriter(fa,true);
fw.write(text1 + "\n");
fw.close();
Toast.makeText(getBaseContext(), "Information Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
} //End try catch statement
Related
This question already has answers here:
Android permission doesn't work even if I have declared it
(11 answers)
Closed 4 years ago.
I want to store Bitmap image in external storage but I am getting an error creating the file directory.
This is my code.
private void saveImage(Bitmap bitmap){
String root = Environment.getExternalStorageDirectory().toString();
File directory = new File(root + "/Wallpapers");
boolean wasSuccessful = directory.mkdirs();
if(!wasSuccessful){
Toast.makeText(context, "Error Creating directory", Toast.LENGTH_SHORT).show();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt();
String fname = "Wallpaper-"+n+".png";
File file = new File(directory, fname);
if (file.exists()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(context, "Wallpaper Saved Successfully", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Error Saving Wallpaper", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
I already write the permission in android manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I've already tried out many solutions but it cannot resolved my issue.
Writing simple example to store bitmapImage Image given as follows. please try it out ...
//Get file name and bitmapImage and call the method ()
//Bitmap bitmapImage = ImageUtil.getInstance().changeImageRotated(cameraUri, bitmapImage, ImageUtil.TypeMode.CAMERA);
//String fileName = String.valueOf(getCurrentTimeStamp());
//ImageUtil.getInstance().saveImage(bitmapImage, fileName);
//Here is function to save bitmap image to internal storage
public Boolean saveImage(Bitmap imageData, String fileName) {
String savePath = getFilePath(AppConst.getInstance().IMAGE_DIR_APPLY);
isPathMade(savePath);
File file = new File(savePath, fileName);
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
boolean keep = true;
try {
fileOutputStream = new FileOutputStream(file);
imageData.compress(Bitmap.CompressFormat.PNG, AppConst.getInstance().PARKING_APPLY_IMAGE_COMPRESS_QUALITY, fileOutputStream);
} catch (Exception e) {
keep = false;
} finally {
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (fileOutputStream != null){
fileOutputStream.close();
}
if (!keep) {
file.delete();
}
return true;
} catch (Exception e) {
Logger.e(TAG, "saveImageToCache Exception is " + e.toString());
}
}
return false;
}
I have an app that has to take a string, encode it into JSONObject format and write it into a JSON file in the SD. It all seems to be working fine apart from writing part. I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />command in my MANIFEST and that's my code
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String lines[] = importantemail.split("\\r?\\n");
// String firstLine = (lines[0]);
//String secondLine = (lines[1]);
// Toast.makeText(SignificantEmailActivity.this,firstLine + secondLine,Toast.LENGTH_SHORT).show();;
JSONObject jsonObject = makeJsonObject();
try{
Writer output = null;
File file = new File(Environment.getExternalStorageDirectory()+ "importantemail.json");
if (!file.exists()) {
file.mkdirs();
}
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
}
public JSONObject makeJsonObject()
{
JSONObject object = new JSONObject();
try {
object.put("Message ID", id);
object.put("Sender",accountStr);
object.put("Subject",subj);
object.put("E-mail:",importantemail);
}catch (JSONException e)
{
e.printStackTrace();
}
return object;
}
When I press the button I get this message from the Toast
"storage/emulated/0importantemail.json
Permission denied"
No idea why is that though
Tested, Hi replace few lines and this will fix your issue.
JSONObject jsonObject = makeJsonObject();
try{
Writer output = null;
File file = new File(Environment.getExternalStorageDirectory(), "importantemail.json");
if(file.isDirectory()){
file.delete();
}
if(!file.exists()){
file.createNewFile();
}
output = new BufferedWriter(new FileWriter(file));
output.write(jsonObject.toString());
output.close();
Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
public JSONObject makeJsonObject()
{
JSONObject object = new JSONObject();
try {
object.put("Message ID", 5);
object.put("Sender","test");
object.put("Subject","test");
object.put("E-mail:","test");
}catch (JSONException e)
{
e.printStackTrace();
}
return object;
}
in 6.0 or later versions of android, you must give runtime permission. check this.
I got in the data and converted them into what object I want and added them to the ArrayList which is ToDoItems(I've checked what I said above by Toast). Now I notified the adapter to fresh the screen. But error occurs. There's only one adapter and I created this method in the activity where this adapter is.
public void getImport(){
Gson gson = new Gson();
FileInputStream inStream = null;
File file = new File(getCacheDir(),"list1.txt");
try {strong text
String data = null;
inStream = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
inStream.read(fileContent);
data = new String(fileContent);
if(data == null){
Toast.makeText(this, "No data to import", Toast.LENGTH_LONG).show();
}
else{
todoItems.clear();
String[] token = data.split("$$");
for(int i = 0;i<token.length;i++){
todoItems.add(i, gson.fromJson(token[i], ToDoItem.class));
}
aa.notifyDataSetChanged();
}
inStream.close();
Toast.makeText(this, "Import Successfully", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "FileNotFoundException", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_LONG).show();
}
}
I have an EditText in which the user inputs their name, then i want to push a button and the content of the EditText is transferred into a file.
EDITED: I have this code so far:
Button submitButton = (Button) findViewById(R.id.baddNametoFile);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try{
ETName.getText().toString();
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html", true)));
writer.println("<h3 style=padding-left:20px;>" + ETName
+ "</h3><br>");
// new arraylist
writer.close();
}catch (IOException e) {
// put notification here later!!!
e.printStackTrace(); }
}
});
I have it printing to the file what the actual android value is:
android.widget.Button{......./baddNametoFile}
But that is just a placeholder to know the print works. I would like to see what the user has typed printed there instead.
Any help would be great. Thanks
ETName is probably EditText. You didnt post to much code so it should be like:
ETName.getText().toString(); Change View ETName in View v (it is click on a button not on a EditText). Lets try like this:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String etName = ETName.getText().toString();
if(!etName.trim().equals("")){
File file =new File("/sdcard/Accelerometer.html");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(etName);
bufferWritter.close();
}
}catch (IOException e) {
e.printStackTrace(); }
}
try{
File dir = new File("/mnt/sdcard/MyApp/");
if (!dir.exists()) {
dir.mkdir();
System.out.println("Directory created");
}
//ceate .rtf file with header
myFile = new File("/mnt/sdcard/MyApp/Student.rtf");
if (!myFile.exists()) {
myFile.createNewFile();
System.out.println("File created");
}
fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
myOutWriter = new OutputStreamWriter(fOut);
//Write the header : in your case it is : Student class Marsk (only one time)
myOutWriter.write("Student,class,Marks"+"\n");
myOutWriter.flush();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I have a read and write operation at a android app. On onCreate, a file will be read and display it to an editext and can be editted. When the save is pressed, the data will be written to the same file that will be read on onCreate. But I got an error. No such file in directory. I don't get it. I'm creating the file when the save button is pressed. Any ideas?
Java code:
EditText Name;
EditText Age;
EditText Height;
EditText Weight;
EditText MedHistory;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicalhistory);
Name = (EditText) findViewById(R.id.medhistName);
Age = (EditText) findViewById(R.id.medhistAge);
Height = (EditText) findViewById(R.id.medhistHeight);
Weight = (EditText) findViewById(R.id.medhistWeight);
MedHistory = (EditText) findViewById(R.id.MedHist);
int i = 0;
String MedHistData[] = new String[5];
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null)
{
MedHistData[i] = aDataRow;
i++;
}
i = 0;
Name.setText(MedHistData[0]);
Age.setText(MedHistData[1]);
Height.setText(MedHistData[2]);
Weight.setText(MedHistData[3]);
MedHistory.setText(MedHistData[4]);
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
Button Save = (Button) findViewById(R.id.SaveBtn);
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(Name.getText() + "\n");
myOutWriter.append(Age.getText() + "\n");
myOutWriter.append(Height.getText() + "\n");
myOutWriter.append(Weight.getText() + "\n");
myOutWriter.append(MedHistory.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Medical History Saved'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
You should use openFileInput() method to open file for reading and openFileOutput() for writing. These functions return a FileInputStream and FileOutputStream respectively.
My guess: you don't have write access to the file.
You only can access specific folders for writing in android.
Have a look at
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
They have a simple example on how to write a text file.