im developing a app in Android. in this project im using a List of Objects and i need to convert the list object in byte array. but there is a null pointer exception shown in logcat? here is my coading.
class MyContact
{
String Name;
Bitmap Image;
String Number;
public MyContact(String cName, String cNumber, Bitmap cImage) {
Name = cName;
Number = cNumber;
Image = cImage;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public Bitmap getImage() {
return Image;
}
public void setImage(Bitmap image) {
Image = image;
}
public String getNumber() {
return Number;
}
public void setNumber(String number) {
Number = number;
}
}
List<MyContact> list = new ArrayList<MyContact>();
I added some values to the List object, using
MyContact contactObj = new MyContact(name, phoneNo, photo);
list.add(contactObj);
bla bla bla ....
and i need store the entire list object into the Android Mobiles local file. i used ,
FileOutputStream fos = openFileOutput( fileName, Context.MODE_PRIVATE);
fos.write(toByteArray(MyTrackList)); // null pointer error occured here
fos.close();
here is a byte array conversion coding.
public static byte[] toByteArray (Object obj)
{
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
bytes = bos.toByteArray ();
}
catch (IOException ex) {
//TODO: Handle the exception
}
return bytes;
}
but returns null pointer exception in the line of above i marked in comment
how can i resolve this problem. any suggestion? thanks in advance….
There is your problem: If there is an IOException, your method will just return null and not tell you about it.
Do not catch the exception, change the method to
throws IOException(since there is nothing you can do at that point anyway) and then find out what caused it.Most likely it is because your
MyContactclass does not implementSerializable, so that it cannot be written to an ObjectOutputStream.Also, performance and memory-usage can be improved by not having that intermediate byte array and connecting the ObjectOutputStream directly to the FileOutputStream instead.