Android内部对象存储

时间:2011-07-05 13:03:12

标签: android object storage

我正在尝试将EditText的ArrayLists(ArrayOne,ArrayTwo和ArrayThree)保存到内部存储。正如评论的那样,它清楚地表明它会尝试保存,但之后我再也没有得到另一个TOAST。任何帮助,为什么它没有显示“保存完成”或任何错误表示赞赏。

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 */ }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

问题是EditText类不可序列化

如果你在printStackTrace上调试并设置一个断点并检查IOException,它会告诉你

catch (IOException e
{
     e.printStackTrace();
} 

类必须使用“implements Serializable”才能将它们写为对象,而EditText则没有。

您无法扩展类并添加serializable标记,因为底层类仍将抛出异常。

我建议您通过自己的类序列化数据,或者使用其他方法保存您尝试做的任何事情。

答案 1 :(得分:0)

我认为错误是你的第一个Try块被吞没,因为你只捕获FileNotFound和IOException - 只是出于调试目的,你可以捕获通用的Exception并打印出栈跟踪。

如果这也有助于我这样做:

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();

最佳

-serkan

答案 2 :(得分:0)

如果在“尝试保存”后没有显示任何内容,则会在此块中出现一些异常

 catch (IOException e)
         {
             e.printStackTrace();
         } 

你没有在任何Toast中查看它。此外,你可以通过这种方式在这里做任何事情:

 catch (Exception e)
        { /* do nothing */ }

而不是烘烤你的消息..尝试使用LogCat进行debbugging,易于使用,而且你不需要在代码中放入toast代码。告诉我怎么回事。