-1

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());
    }
Flava
  • 77
  • 1
  • 8
  • 1
    It looks like you're trying to save Views and read them back in which case you can't do this nor would you ever want to. Views don't inherit from the `Seriablizable` interface. Save the **state** of the View (i.e. the data the View is displaying), and rebuild it when coming back. – DeeV Jan 18 '16 at 15:54

1 Answers1

1

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.

Radu Ionescu
  • 3,462
  • 5
  • 24
  • 43
  • my Fragment class : public class MainPage extends Fragment implements java.io.Serializable(...) – Flava Jan 18 '16 at 16:02
  • But the HashMap is of Views and to deal with non-serializable fields you need something like this [Serialization with non serilazable parts](http://stackoverflow.com/questions/95181/java-serialization-with-non-serializable-parts) – Radu Ionescu Jan 18 '16 at 16:06