I have created a Public Class for my Database connection as am running various Database query's throughout the application
Every time i call the Class con
always returns Null
But if i use it outside of the Class, and directly in the Activity then it connects and runs.
I have no idea why and would greatly appreciate any pointers in the right direction please.
Here are my ConnectionManager class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
static String serverName ="192.168.1.5";
static String serverPort ="1433";
static String databaseName ="DBNAME";
static String db = String.format("jdbc:jtds:sqlserver://%s:%s/%s", serverName, serverPort, databaseName);
static String un = "sa";
static String pass = "";
static Connection con;
public static Connection getConnection() {
try {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection(db, un, pass);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return con;
}
}
And from within my Activity i am calling it as follow:
try {
con = ConnectionManager.getConnection();
if (con == null) {
z = "Check Your Internet Access!";
Toast.makeText(StockEnquiry.this, z, Toast.LENGTH_LONG).show();
} else {
stmt = con.createStatement();
String query = "select * from Details where ID= '1111' ";
rs = stmt.executeQuery(query);
if (rs.next()) {
String sCode = rs.getString("Short_Code");
String sDesc = rs.getString("Short_Desc");
Toast.makeText(StockEnquiry.this, (sCode + " " + sDesc), Toast.LENGTH_LONG).show();
con.close();
} else {
Toast.makeText(StockEnquiry.this,"Invalid Code!", Toast.LENGTH_LONG).show();
}
Toast.makeText(StockEnquiry.this, "Message1", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
Toast.makeText(StockEnquiry.this, "Appears to have failed in catch", Toast.LENGTH_LONG).show();
}
}
}