Android activity won't save information to file - java

I'm trying to save user information in a single save file in local directory. However every time I run the app, the information doesn't save--I can tell by rerunning the app and the file data isn't updated or returning to the activity and finding out the data displayed isn't updated upon returning to the same activity. Here is the function in the activity where I set up a file output stream and decided to write in the information through a string containing all the User information and display "FILE CLOSED" once I assumed the file has written. Could you spot any missing steps or anything that I missed so that the file can be written?
public void saveToFile() throws FileNotFoundException{
//new filestream
FileOutputStream fostream;
fostream = openFileOutput(fileName, Context.MODE_PRIVATE);
//Write into file for each User in Array
for (int i = 0; i < userArrayList.size(); i++){
String contents = userArrayList.get(i).display();
System.out.println(userArrayList.get(i).display());
try {
fostream.write(contents.getBytes());
} catch (IOException e) {
System.out.println("NOTHING WRITTEN");
e.printStackTrace();
}
}
try {
fostream.close();
System.out.println("FILE CLOSED");
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks so much for your help!

Related

Android studio, open a file , continuously write and then close

I have code that is generating data every second and displaying onscreen.
This all works fine but I want to create a log file of all the data to analyze later.
I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file
String data= reading1","+reading2+","+time +"/n";
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
I would prefer to have the file open when the start button is clicked.
if ( v.getId() == R.id.start ){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
but when it comes to closing the file, no options for .close() appear when out is typed
if ( v.getId() == R.id.stop ){
// checks which button is clicked
out. // no valid options appear
messageValue.setText(R.string.stopButtonText);// changes the hallo world text
readNoRead=false;
}
Does all the open/write/close need to be together or is it possible to
***open file***
-----
Cycle through all the data
-----
***Close file***
You should store a link to your FileOutputStream on top level in your class.
Example to your code:
FileOutputStream out;
void clickStart() {
if (v.getId() == R.id.start){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void writeData() {
String data= reading1+","+reading2+","+time +"/n";
try {
out.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
void clickStop() {
if (v.getId() == R.id.stop) {
try {
out.close();
} catch(IOException e) {
e.printStackTrace();
}
messageValue.setText(R.string.stopButtonText);// changes the hello world text
readNoRead=false;
}
}
It is definitely possible to open, process and close a file all in one block without closing the file.
Your out variable is not showing any method suggestions because it has not been defined in that block. Change the line
FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
to
out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
and then add FileOutputStream out; to a line above the first if statement (outside of the block).
You may want to also look into 'try-catch-finally', or 'try with resources' as options for closing files in a try-catch block.

Android Studio - Read and Write to/from file in local storage within a folder

So I'm trying to read and write to and from a file that is inside a folder within the app's directory. So the path is something like "package/userFiles/'insert file name here'" but I can't find a way to do it anywhere.
I haven't been able to test this yet but the below is the code I've got for writing a quick and simple string to the file. If you could take a look over that I would be grateful, and if at all possibly give me some direction over how to read from the file.
FileOutputStream outputStream;
File path = new File(getFilesDir(),"userFiles");
path.mkdirs();
File mypath =new File(path,newFileNameText);
try {
FileOutputStream out = new FileOutputStream(mypath);
String defaultMessage = "Empty File";
out.write(defaultMessage.getBytes());
out.close();
Intent intent = new Intent(getApplicationContext(), EditFileContents.class);
intent.putExtra(EXTRA_MESSAGE,newFileNameText);
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can see the code starts a new activity, it is this activity from which I would like to be able to read the contents of the file.

Trying to send data to text file

Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..

Writing and reading from txt file android

I know that this is a widely discussed question , but I am really confused with those examples provided on android developers manual .
So , I have a "source.txt" in my res/raw folder .For example I want to write 2 lines in it(for ex. Hello\nWorld) and then read them from another activity. Can anyone write the source code for this , please.
You should replace your .txt file to your extornal or internal storage.And You must give permission for write text from androidManifest.xml
for reading file you can do this
public String readFile(String filePath) {
String jString = null;
StringBuilder builder = new StringBuilder();
File yourFile = new File("/sdcard/" + filepath);
if (yourFile.exists()) {
Log.i("file", "file founded");
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(yourFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String row = "";
try {
while ((row = bufferedReader.readLine()) != null) {
builder.append(row + "\n");
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jString = builder.toString();
}
else {
Log.i("FAIL", "FILE NOT FOUND");
}
return jString;
}
for writing file you can use this
public void writetoFile(String filename,String text) {
File file = new File("/sdcard/" + filename);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileWriter fileWriter;
try {
//you can change second parametre true or false this is about append or clean and write
fileWriter = new FileWriter(file, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append(jsonText);
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Whatever is in your APK file is read-only, therefore you are unable to write to file stored in res/raw source folder as it is still in your APK. if you want to work on file shipped with your app, you need to copy if to internal storage or SD card from APK first so that would allow you to alter the content.
Every file in your apk is read only, so you need to create the file in your internal storage or SD Card. If you just want to send small amount to of data to second activity, you can send data along with intent or use sharedPreference.
If you really want to read and write data to/from SD card then you need to use FileInputStream and OutputStreamWriter to read/write data to a file. Check this tutorial here to see how it's done. http://www.java-samples.com/showtutorial.php?tutorialid=1523

Why do I get FileNotFoundException when I create and try to write to file on Android emulator?

First off, I am not trying to write to the SDCard. I want to write some information to a file that persists between uses of the app. It is essentially a file to hold favorites of the particular user. Here is what the code looks like:
try {
File file = new File("favorites.txt");
if (file.exists()) {
Log.d(TAG, "File does exist.");
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
}
else {
Log.d(TAG, "File does not exist.");
return favDests;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When running this code, we always get the "File does not exist." message in our DDMS log.
We have also tried the following code to no avail:
try {
File file = new File(GoLincoln.FAV_DEST_FILE);
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is this second portion of code that results in the FileNotFoundException.
I have read multiple tutorials on writing and reading files on Android and I believe I am following them pretty closely, so I am not sure why this code doesn't work successfully. I appreciate any help!
You shouldn't use the File class directly. Use Activity.getCacheDir() to get the cache dir which is specific to your application. Then use new File(cachedir, "filename.tmp") to create the file.
Preferences and SQLLite will both allow you to have persistent data without managing your own files.
To use shared preferences you grab it from your context, then you edit the values like so
mySharedPreferences = context.getSharedPreferences("DatabaseNameWhateverYouWant", 0);
mySharedPreferences.getEditor().putString("MyPreferenceName", "Value").commit();
To get a preference out
mySharedPreferences.getString("MyPreferenceName", "DefaultValue");
This is really the simplest way to do basic preferences, much easier then doing a file. More then strings are supported, most basic data types are available to be added to the Preferences class.

Categories