I have a project in which i connect to my Local Network DB
. I Insert,Update and Select from DB
, and DB type is SQL Server 2005
.
I made a class named ConnectionHelper
and everywhere i want to connect to DB, i make an Instance
of it and then call its getConnection
Method.
This class has a Constructor
like this :
public ConnectionHelper() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setConnection(connection);
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
setIpAddress("X.X.X.X:1433");
setDb("XXX");
setUserName("XX");
setPassword("XXXX");
setConnectionURL("jdbc:jtds:sqlserver://" + getIpAddress() + ";"
+ "databaseName=" + getDb() + ";user=" + getUserName()
+ ";password=" + getPassword() + ";");
setConnection(DriverManager.getConnection(getConnectionURL()));
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
}
And this is getConnection
Method :
public Connection getConnection() {
return connection;
}
And here is the sample of using this with Callable Statement
( Call an Update Stored Procedure
) :
ConnectionHelper connectionHelper = new ConnectionHelper();
CallableStatement callableStatement;
try {
callableStatement = connectionHelper.getConnection().prepareCall("{call MySP(?, ?, ?)}");
callableStatement.setInt(1, X);
callableStatement.setInt(2, X));
callableStatement.setInt(3, X);
callableStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
Well, it works good, But Android Devices
connect to Local Network
via WIFI
, and sometimes they could not connect to DB due to Network Problems and then App close it by itself with unfortunately Error.
I want to handle if it could not connect to DB, retry again or display an Toast
message to user and do not close the App.
How can i should handle the Exception
?