Android Internal Object Storage - android

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.

Related

Can't get path to /data/data/my_app/files

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.

Can not read text files

I am trying to write and read a text file which is full of words and add it to an ArrayList. The ArrayList later is used from another part of the program to display text in a TextView. But when i run the program and open the specific part of it, then there is nothing. The ArrayList is just empty. I don't get any exceptions but for some reason it doesn't work. Please help me.
I don't seem to have problems with the file writing:
TextView txt = (TextView)findViewById(R.id.testTxt);
safe = txt.getText().toString();
try {
FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(safe);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException ex){
Log.e("Exception", "File write failed: ");
}
} catch (IOException e) {
Log.e("Exception", "File write failed: ");
}
But I think the problem is in the file reading. I made some "Log.d" and found out that everything works fine till the InputStreamReader line:
public favHacks() {
testList = new ArrayList<String>();
try {
//Works fine till here
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput("test.txt"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null )
{
testList.add(receiveString);
}
bufferedReader.close();
}
catch (FileNotFoundException ex) {
Log.d("login activity", "File not found: ");
} catch (IOException ex) {
Log.d("login activity", "Can not read file: ");
}
}
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
http://developer.android.com/training/basics/data-storage/shared-preferences.html
also if you want to write/read files, or do any kind of operations that can block the Main Thread try to use another Thread like when you are trying to save the data in a file or use a Handler if you have multiple Threads (one for saving and one for reading).
https://developer.android.com/training/multiple-threads/index.html
In your code the method called favHacks can return an ArrayList with the list of all the strings Something like
//
public ArrayList<String> readFromFile(String file){
ArrayList<String> mArrayList= new ArrayList<String>();
//read from file here
return mArrayList;
}
but as I said before, you need to the operations that can block the UI thread in a new Thread.
https://developer.android.com/training/multiple-threads/communicate-ui.html
And also I think that the best way to do this is using Asynk task
Why and how to use asynctask

Why am I getting warnings Serialize ArrayList

I'm getting odd warnings in my reading of a ArrayList of Serializable objects. Here is the code:
public void loadBoard() {
FileInputStream fis = null;
ObjectInputStream is;
try {
fis = this.openFileInput(saveFile);
is = new ObjectInputStream(fis);
// Build up sample vision board
if (mVisionBoard == null) {
mVisionBoard = new ArrayList<VisionObject>();
} else {
mVisionBoard.clear();
}
ArrayList<VisionObject> readObject = (ArrayList<VisionObject>) is.readObject();
mVisionBoard = readObject;
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (StreamCorruptedException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "loadBoard failed: "+e);
}
}
and the warning I'm getting is (on readObject line):
"Type safety: unchecked cast from Object to ArrayList"
The few examples I've read indicate that this is the correct code for reading an ArrayList of serializable objects. The code I made to write the arraylist isn't giving me any warnings. Am I doing something wrong here?
kind of late but it will help someone...
the reason of the warning is because of the return of the method readObject...
see:
public final Object readObject()
it returns actually an object
and if you just by mistake read and deserialize a lets say String object ant try to cast that into an array list then you will get a runtime execption (the reason must be obvious)
in order to avoid that predictable failure you can check the type of the returned object before the cast...
that is why you get the warning:
"Type safety: unchecked cast from Object to ArrayList<VisionObject>"

Android - print full exception backtrace to log

I have a try/catch block that throws an exception and I would like to see information about the exception in the Android device log.
I read the log of the mobile device with this command from my development computer:
/home/dan/android-sdk-linux_x86/tools/adb shell logcat
I tried this first:
try {
// code buggy code
} catch (Exception e)
{
e.printStackTrace();
}
but that doesn't print anything to the log. That's a pity because it would have helped a lot.
The best I have achieved is:
try {
// code buggy code
} catch (Exception e)
{
Log.e("MYAPP", "exception: " + e.getMessage());
Log.e("MYAPP", "exception: " + e.toString());
}
Better than nothing but not very satisfying.
Do you know how to print the full backtrace to the log?
Thanks.
try {
// code that might throw an exception
} catch (Exception e) {
Log.e("MYAPP", "exception", e);
}
More Explicitly with Further Info
(Since this is the oldest question about this.)
The three-argument Android log methods will print the stack trace for an Exception that is provided as the third parameter. For example
Log.d(String tag, String msg, Throwable tr)
where tr is the Exception.
According to this comment those Log methods "use the getStackTraceString() method ... behind the scenes" to do that.
This helper function also works nice since Exception is also a Throwable.
try{
//bugtastic code here
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
catch (Exception e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream stream = new PrintStream( baos );
e.printStackTrace(stream);
stream.flush();
Log.e("MYAPP", new String( baos.toByteArray() );
}
Or... ya know... what EboMike said.
public String getStackTrace(Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
e.printStackTrace() prints it to me. I don't think you're running the logcat correctly. Don't run it in a shell, just run
/home/dan/android-sdk-linux_x86/tools/adb logcat
The standard output and error output are directed to /dev/null by default so it is all lost. If you want to log this output then you need to follow the instructions "Viewing stdout and stderr" shown here
try{
...
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e.getCause());
}
if you want to print out stack trace without exception, you can create it by following command
(new Throwable()).printStackTrace();
In the context of Android, I had to cast the Exception to a String:
try {
url = new URL(REGISTRATION_PATH);
urlConnection = (HttpURLConnection) url.openConnection();
} catch(MalformedURLException e) {
Log.i("MALFORMED URL", String.valueOf(e));
} catch(IOException e) {
Log.i("IOException", String.valueOf(e));
}
KOTLIN SOLUTION:
You can make use of the helper function getStackTraceString() belonging to the android.util.Log class to print the entire error message on console.
Example:
try {
// your code here
} catch (e: Exception) {
Log.e("TAG", "Exception occurred, stack trace: " + e.getStackTraceString());
}
Kotlin extension. Returns the detailed description of this throwable with its stack trace.
e.stackTraceToString()

90112 bytes limit for data files?

I create data file in android for my application in the app's data directory. The write is successful with no exceptions but file contents are not complete. It truncates at 90112 bytes. Any idea what is going on ? Is there a limit ?
Here is the snippet
try {
fos = parentActivity.openFileOutput(mmCacheFName,
Context.MODE_PRIVATE | Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bosw = new BufferedWriter(osw);
int indx = lastIndx - 10;
while (indx >= 0) {
IEventHolder ev = deltaList.get(indx);
bosw.write(ev.getRawData() + "\n");
indx--;
}
osw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Throwable t) {
t.printStackTrace()
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
There might be lots of reasons. If you send your code, it's easier to track the problem. But you could check:
you have closed your Stream when writing to the file (It is recommended that you do it in a finally block) like this:
try{
....
write the data to the file with some outputStream
}finally{
outputStream.close();
}
If you want to read the data before closing the stream, make sure your output-stream does not buffer the output. if it does, before reading the data, flush the output to the file:
outputStream.flush();
Check for any exception that might be caught, but not logged, some code like this:
try{
...
}catch(IOException ex){
// here must log the exception.
}
}
Thanks for your responses. I figured out what the issue was, I should be flushing and closing the BufferedWriter instead of OutputStreamWriter. Thanks again

Categories

Resources