I have two activities that I want to call the time class bellow but every time i call that class it throws up an exception. But if i put the timeWrite() method in the Activity it works well but if I put it in the time class and then try to call it to write the file it throws up exception.
public class time extends AlphabetActivity{
private int time;
public void timeWrite(int time) {
try {
String timeVal = String.valueOf(time);
FileOutputStream timeStream = openFileOutput("time_file.txt", Context.MODE_PRIVATE);
timeStream.write(timeVal.getBytes());}
timeStream.close();
catch (Exception e) {
e.printStackTrace();}}
It seems like something is wrong with inheritance and I am just not understanding what I am doing wrong.
try {
String timeVal = String.valueOf(time);
FileOutputStream timeStream = openFileOutput("time_file.txt", Context.MODE_PRIVATE);
timeStream.write(timeVal.getBytes());
}
timeStream.close();
catch (Exception e) {
e.printStackTrace();}
}
Your code will compile if you write:
try {
String timeVal = String.valueOf(time);
FileOutputStream timeStream = openFileOutput("time_file.txt", Context.MODE_PRIVATE);
timeStream.write(timeVal.getBytes());
timeStream.close();
}catch (Exception e) {
e.printStackTrace();
}
If think this sytanx is wrong, does this code compile ?
Please read this, I know, long but you have to study now or later:
https://docs.oracle.com/javase/tutorial/essential/exceptions/
same
http://www.tutorialspoint.com/java/java_exceptions.htm
if you write file to the external storge, mind to add the READ and WRITE_EXTERNAL_STORAGE permission to the manifest
Related
I'm working on an app which stores small amounts of data in /data/data/my_app/files using this code:
private void buildFileFromPreset(String fileName) {
fileName = fileName.toLowerCase();
StandardData data = StandardData.getInstance();
String[] list = data.getDataByName(fileName);
FileOutputStream fos = null;
try {
fos = openFileOutput(fileName, Context.MODE_PRIVATE);
PrintWriter writer = new PrintWriter(fos);
for (int i = 0; i < list.length; i++) {
writer.println(list[i]);
}
writer.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
All works fine when the app gets started, in the onCreate() function of the main activity, I want to check if the files that were created last time are still present:
private String getAppFilesDir() {
ContextWrapper c = new ContextWrapper(this);
return c.getFilesDir().toString();
}
which returns something like:
/data/user/0/my_app/files
I've read some older posts (2012) suggesting this method must work but it doesn't, probably since jellybean.
So my question:
How can I check if the files I created using FileOutputStream and PrintWriter in a previous session still exist?
I hope I provided enough info for you guys to answer (:
I still have not found a solution for this specific problem.
Instead I am now using SQLite so I don't have to worry about these kinds of things.
I have a Hashmap in a Fragment variable for a Position(int) to View Relationship.
sometimes I can read the Object in onCreate but with no data ( size 0) , However when I want to store it when onPause or onStop fires of the fragment to internal storage , it gives me a weird error without any clue what cause it:
android.widget.RelativeLayout
Fragment onPause:
#Override
protected void onPause() {
super.onPause();
try
{
FileOutputStream fileOutStream = getContext().openFileOutput("hashMap", Context.MODE_PRIVATE);
ObjectOutputStream objOutStream = new ObjectOutputStream(fileOutStream);
objOutStream.writeObject(HashMap);
objOutStream.close();
Log.v("Fragment:", "Done Writing "+HashMap.size());
}catch (IOException e)
{
Log.v("Fragment:","MainPage(onStop): "+e.getMessage()+e.getLocalizedMessage());
}
}
the following lines to read from internal storage when opening the app.
try {
FileInputStream f = getContext().openFileInput("hashMap");
ObjectInputStream s = new ObjectInputStream(f);
HashMap= (HashMap<Integer, View>) s.readObject();
s.close();
Log.v("Fragment:", "Done Reading " + HashMap.size());
} catch (ClassNotFoundException | IOException e) {
Log.v("Fragment:", "MainPage(onCreate): " + e.getMessage());
}
I think
Only objects that support the java.io.Serializable interface can be written to streams
according to ObjectOutputStream
The View does not seem to implement this interface.
Hi Iam having serious issues try to persist some serializable objects to a file on the local android file system. Iam getting a Bad file descriptor error and I think it is to do with my methods for creating the file. the file and checking if the file exists. i create a private file object in the class. Then, on write or read. I check file existance with the following code.
#Override
public boolean fileExists() {
File file = context.getFileStreamPath(filename);
return file.exists();
}
this doesnt instantiate my file object called "objectfile"!! but does check the "filename" exists.
to create the file I call this method if "filename" doesnt exist.
public void createFile()
{
objectfile = new File(context.getFilesDir(), filename);
objectfile.setReadable(true);
objectfile.setWritable(true);
}
Iam not sure if this will give me back my previously created file which would be ideally what I want to do. Is there a way i can just get the old file or create a new one and pass it to "objectfile" variable in the constructor??
Iam also wondering what the best way to do this is??
Or should i just use the mysqlite db? using object file persistance doesn't seem to be working out for me right now and iam working to a deadline. Also this method is mention in the gooogle docs so I thought it would be legit was to do it.
http://developer.android.com/training/basics/data-storage/files.html
here is my method for reading the serializable objects
public synchronized ArrayList<RoomItem> readObjects() {
final ArrayList<RoomItem> readlist = new ArrayList<>();
if(!fileExists())
return readlist;
if(objectfile == null)
createFile();
try {
finputstream = new FileInputStream(objectfile);
instream = new ObjectInputStream(finputstream);
readwritethread = new Thread(new Runnable() {
#Override
public void run() {
try {
final ArrayList<RoomItem> readitems = (ArrayList<RoomItem>) instream.readObject();
instream.close();
finputstream.close();
handler.post(new Runnable() {
#Override
public void run() {
listener.updateList(readitems);
}
});
} catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
Log.d("read failed", "file read failed");
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
timeOutReadWrite(readwritethread);
readwritethread.start();
try {
readwritethread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("read from file", "file read");
return readlist;
if anyone could suggest any improvements id really appreciate it. I use a handler to pass back to my activity and implement a listener interface on my activity thats call the activity when all the obj are read. Thanks again!
1#: Yes, it will return the original file you created.
2#: Depends on the thing you want to store, seems File is more flex from description
hope helpful.
We have used
FileOutputStream fos = context.openFileOutput("file.ser", Context.MODE_PRIVATE);
to write our serialized files.This will carete files in /data/data/app.package.name/files/. In fact, this path is returned by getFilesDir().
And while deserializing, use
//make sure you pass the same file that was passed to openFileOutput()..
FileInputStream fis = context.openFileInput("file.ser");
Also, to avoid confusing between file names you can use name of class that is being serialized.
Ex:
public static <T> void serialize(final Context context, final T objectToSerialize) {
....
....
Strin fileName = objectToSerialize.getClass().getSimpleName();
...
}
Do this and keep the method in util so it can be used for any type of objects (T type) to serialize.
At first I have strong Java knowledege, but however just started with Android.
My Android app is downloading some fairly complex data (texts, dates, images) which I am saving in a custom object. The data need to be refresh from time to time. However usually the data downloaded will not change.
In order to keep the data in memory I am using the Application Object. Unfortunately, it looks like the application object instance is destroyed when the app is killed.
Hence, I was wondering if it would be of good practice to serialize and save my custom object (which is contained in the application object) in the internal storage during onPause(). Obviously, I would then first read from the file in onResume() before reloading from the internet. The idea is also to enable offline viewing.
In longer term the plan is to move the code downloading the date in a background service. As there seems to be many different ways to keep application state in Android, I would like to be be sure that this is the correct way to go.
Try using those methods class to save the Object(s) (implements serialize) you need:
public synchronized boolean save(String fileName, Object objToSave)
{
try
{
// save to file
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
if (file.exists())
{
file.delete();
}
file.getParentFile().mkdirs();
file.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(objToSave);
oos.close();
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return false;
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
public synchronized Object load(String fileName)
{
try
{
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
if (!file.exists())
{
return null;
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
savedObj = ois.readObject();
ois.close();
return savedObj;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return null;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
You'll need to cast the Object you load().
CONTEXT is an Activity or ApplicationContext to get access to the cachedir.
Your could use Environment.getExternalStorageState() instead to get a directory path. DOn't forget to add it "/filename".
I am trying to save ArrayLists(ArrayOne, ArrayTwo, and ArrayThree) of EditText's to the internal storage. As commented, it clearly shows that it attempts the save, but I never get another TOAST after that. Any help as of why it doesn't show "Save completed" or any error is appreciated.
public void save(Context c)
{
String fileName;
Toast.makeText(this, "Attempting Save", Toast.LENGTH_SHORT).show();//THIS SHOWS
if(semester.getText().toString().length() == 0)
{
Toast.makeText(c, "Please enter a filename", Toast.LENGTH_SHORT).show();
}
else
{
fileName = "test.dat";
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
fos = this.openFileOutput(fileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(ArrayOne);
oos.writeObject(ArrayTwo);
oos.writeObject(ArrayThree);
Toast.makeText(c, "Save Completed", Toast.LENGTH_SHORT).show(); //THIS NEVER SHOWS
}
catch (FileNotFoundException e)
{
Toast.makeText(c, "Could not find " + fileName + " to save.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (oos != null)
oos.close();
if (fos != null)
fos.close();
}
catch (Exception e)
{ /* do nothing */ }
}
}
}
The problem is that the EditText class is not serializable
If you debug and put a break point at on the printStackTrace and examine the IOException it will tell you that
catch (IOException e
{
e.printStackTrace();
}
Classes have to use "implements Serializable" in order for them to be written out as objects, which EditText does not have.
You can not extend the class and add the serializable tag either because the underlying class will still throw the exception.
I suggest you either serialize the data via your own class or save whatever you are trying to do with some other method.
I think the error is beings swallowed in your first Try block because you're only catching FileNotFound and IOException - just for debugging purposes you could catch the generic Exception and printout the stacktrace.
If it also helps this is what I do:
java.io.File file = new java.io.File("/sdcard/mystorage/ArrayOne.bin");
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
out.writeObject(obj);
out.close();
Best
-serkan
If nothing shows after the "Attempting save" you´re getting some exception in this block
catch (IOException e)
{
e.printStackTrace();
}
And you´re not viewing it in any Toast. Also you can be here in this way doing nothing with your exception:
catch (Exception e)
{ /* do nothing */ }
Instead of toasting your messages.. try to use LogCat for debbugging, is easy to use and also you don't need to put toast code in your code. Tell me how is going.