Search code examples
androidserializationarrayssaveobjectoutputstream

why won't "toByteArray()" execute?


I've been trying to figure this out for hours and it's soo frustrating! I am serializing a 'hashtable', which is the object that I am passing to this method 'saveDataToDisk(Object o)', I tested this out in a regular java project and it executes the 'toByteArray()' correctly, but in Android it always goes into the catch whenever it hits toByteArray()... any ideas? Thank you in advance.

public static byte[] saveDataToDisk(Object o)
{
    // Storing the data into byte streams.
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try
    {
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(o);
        out.close();
        // Get the bytes of the serialized object
        byte[] buf = bos.toByteArray();

        return buf;
    }
    catch (IOException ioe)
    {
        return null;
    }
}

Solution

  • I tried to execute your use case, seems to work for me. Refer to the code below I get a byte array : [-84, -19, 0, 5, 116, 0, 2, 72, 105]

    public class WriteObject extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_1);
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener(){
            String s = "Hi";
            @Override
            public void onClick(View v) {
                byte[] b = WriteObject.saveDataToDisk(s);
                Log.i("", b.toString());
    
            }
    
        });
    }
    public static byte[] saveDataToDisk(Object o){
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = null;
        try{
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(o);
            out.close();
            buf = bos.toByteArray();
        }catch (IOException ioe){
            Log.e("", ioe.toString(),ioe);
        }
        return buf;
    }
    
    }