suraj malviya suraj malviya - 6 months ago 10
Java Question

I am getting an Exception while serializing an object

The exception is


java.io.notSerializableException :
com.mysql.jdbc.SingleByteCharacterSetConverter


package business_logics;


import java.util.ArrayList;
import java.util.Iterator;


public class Purchase implements java.io.Serializable
{
String client;
int purchaseID;
String issue;
String due;
ArrayList<Particulars> myparticulars=new ArrayList();
String personal;
double total;
double otheramount;
double previous;
double grandtotal;
String paymentmode;
double paid;
double cbalance;

public Purchase(int id,String client, String issue, String due,String personal, double otheramount, double previous,String payment )
{
this.purchaseID=id;
this.client=client;
this.issue=issue;
this.due=due;
this.personal=personal;
this.otheramount= otheramount*(-1);
this.previous=previous;
this.paymentmode=payment;

}

public void setTransaction(double paid)
{
this.paid=paid;
this.cbalance=this.grandtotal+this.paid;
}

public void setParticulars(ArrayList<Particulars> part)
{
part.stream().map((part1) -> {
this.myparticulars.add(part1);
return part1;
}).forEach((part1) -> {
total += part1.giveAmount();
});
total=total*(-1);
grandtotal=getGrandTotal();
}

public double getGrandTotal()
{
return total+otheramount+previous;
}
public double getTotal()
{
return total;
}

public int getPurchaseID()
{
return purchaseID;
}

public double getBalnace()
{
return cbalance;
}

public String getIsuueDate()
{
return issue;
}

public String getDueDate()
{
return issue;
}

public double getPaid()
{
return paid;
}

public double getPrevious()
{
return previous;
}
public double getOther()
{
return otheramount;
}

public String fullDetail()
{

StringBuilder mydata=new StringBuilder();

mydata.append("------------------------------------------------------------------------------------------");
mydata.append("\n\t\tClient info !!");
mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\nName: ").append(client);

mydata.append("\nIssue Date: "+issue);
mydata.append("\nDue Date: "+due);
mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\n\t\tItem info");
mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\n");
int i=1;
for (Particulars myparticular : myparticulars)
{
mydata.append(i+" | ");
mydata.append(myparticular);
mydata.append("\n");i++;
}
mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\n\t\t\t\tNet Payable : "+"\u20B9 "+total);
mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\n");

mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\n\t Other Info !!");
mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\n");
mydata.append("\nPrevious Amount: "+previous);
mydata.append("\nOther Amount: "+otheramount);
mydata.append("\nPersonal Note : "+personal);
mydata.append("\nPayment Mode: "+paymentmode);
mydata.append("\nTotal Net Payable :"+"\u20B9 "+grandtotal);

mydata.append("\n");
mydata.append("\n------------------------------------------------------------------------------------------");
mydata.append("\n");
mydata.append("\nAmount Paid:"+"\u20B9 "+paid);
mydata.append("\n");
mydata.append("\nCurrent Balance:"+"\u20B9 "+cbalance);

mydata.append("\n------------------------------------------------------------------------------------------");
return mydata.toString();
}

public boolean updateQuantity() throws Exception
{
boolean done=true;
int number=myparticulars.size();

Iterator<Particulars> iterate=myparticulars.iterator();

int count=0;
while(iterate.hasNext())
{
count+=iterate.next().updateParticularQuantity();
}

if(number!=count)
{
done=false;
}
return done;
}


public String getPersonal() {
return personal;
}

}


This is the class i am trying to serialize it from outside like this

public void saveInvoice(Purchase p) throws Exception
{
connect.checkFolderExistence();// working fine !!
String path="C:\\TechBill\\PurchaseInvoices";
File location=new File(path);
if(!(location.exists() && location.isDirectory()))
{
location.mkdir();
saveBill(path,p);
}
else
{
saveBill(path,p);
}
}
private void saveBill(String path,Purchase p) throws Exception
{

path=path+"\\"+purchaseID+".ser";
File myFile=new File(path);

FileOutputStream fout=new FileOutputStream(myFile);
ObjectOutputStream obout=new ObjectOutputStream(fout);
obout.writeObject(p);
obout.close();
fout.close();

}

public void makePurchase(int client_id,Purchase p) throws Exception
{
persistPurchase(client_id,p);
Transaction purchaseTransaction=
new Transaction(p.getIsuueDate(),p.getGrandTotal(), client_id,
p.getPurchaseID(), p.getPaid());
purchaseTransaction.makeTransaction(false, 1); //working fine in other same case
updateBalance(client_id,p);
saveInvoice(p);
}


calling the methods in a button action

try
{
double oamt=Double.parseDouble(other.getText());

String mode=credit.isSelected() ? "credit" : "debit";

double previ=Double.parseDouble(prev.getText());
if(prev.getForeground()!=green)
{
previ=previ*(-1);
}

Purchase purchased=new Purchase(Integer.parseInt(pid.getText()),client.getSelectedItem().toString(),
formatDate(issue.getDate()),formatDate(due.getDate()),notes.getText(),oamt,previ,mode);

purchased.setParticulars(myParticulars());


if(!mode.equalsIgnoreCase("credit"))
{
purchased.setTransaction(Double.parseDouble(pai.getText()));
}
else
{
purchased.setTransaction(Double.parseDouble("0.0"));
}


String clientname=getClientName(client.getSelectedItem().toString()).trim();
String clientcity=getClientCity(client.getSelectedItem().toString()).trim();
System.out.println(purchased.fullDetail());
if(purchased.updateQuantity())
{
makePurchase(getClientID(clientname, clientcity), purchased);


JOptionPane.showMessageDialog(this,"Quantity successfully Updated");
//jasper report....
}
else
{
JOptionPane.showMessageDialog(this,"Quantity Not Updated");
}
}
catch (Exception e)
{
e.printStackTrace();
}


the code related to Database manipulation and fetching is as follows:

private void persistPurchase(int id,Purchase p) throws Exception
{
String query="insert into purchase values(?,?,?,?,?,?,?,?,?)";

PreparedStatement ps=connect.giveConnection().prepareStatement(query);

ps.setInt(1, purchaseID);
ps.setInt(2, id);
ps.setString(3, toDataBase(p.getIsuueDate()));
ps.setString(4, toDataBase(p.getDueDate()));
ps.setInt(5, particulartable.getModel().getRowCount());
ps.setDouble(6, p.getPrevious());
ps.setDouble(7, p.getOther());
ps.setDouble(8, p.getGrandTotal());
ps.setString(9, p.getPersonal());
ps.executeUpdate();
}

public void updateBalance(int id,Purchase p) throws Exception
{
String query="update net_balance set Balance="+p.getBalnace()+"where
client_id="+id;
Statement stmt=new
ConnectionSeeker().giveConnection().createStatement();
stmt.executeUpdate(query);
}


The
makeTransaction()
method is defined in Transaction class and this method is all working in other case..

public void makeTransaction(boolean type,int i) throws Exception //type
specifies SELL- true(CREDIT) & PURCHASE- false(DEBIT)....
{
String query="insert into stransaction values(?,?,?,?,?,?,?,?,?)";

PreparedStatement ps=new
ConnectionSeeker().giveConnection().prepareStatement(query);

int no=fetchTransID();

ps.setString(1,toDataBase(issuedate));
ps.setString(2,getbillType(i));
ps.setInt(3,bill_id);
ps.setInt(4,client_id);
ps.setInt(5,no);
ps.setDouble(6,amount);

double cbalance=0;//amount-saveamount;

if(type)
{
cbalance=cbalance+(amount-saveamount);
ps.setDouble(7,0.0);
ps.setDouble(8,round(saveamount, 2));
ps.setDouble(9,round(cbalance,2));
}
else
{
cbalance=cbalance+(amount+saveamount);
ps.setDouble(7,saveamount);
ps.setDouble(8,0.0);
ps.setDouble(9, round(cbalance, 2));
}

ps.executeUpdate();
}


The Exception is occuring while execution of
makePurchase()
in the button click inside the
if(purchased.updateQuantity())


I am getting this exception can please annybody tell me the root cause of occurence of the same. Thanks in Advance.

Answer
  1. The simplest solution is to find the class that throws the exception and make it implement the Serializable interface. However, this may not be feasible if the class that throws the exception belongs to a third-party library.

  2. In case the class refers to non-serializable objects and these objects should not be serialized, then, you can declare these objects as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.

Comments