Cannot Find Driver - My Solution

108 views
Skip to first unread message

David Caplin

unread,
Nov 10, 2014, 9:33:38 AM11/10/14
to pgan...@googlegroups.com
I have been trying to create an app to connect to a PostgreSQL database (Aren't we all?), and have been having a "cannot find suitable driver" errors for weeks. I assumed it was an issue with defining the JDBC/Postgresql driver, so I tried different methods of defining it, Class.forName, Drivermanager.registerDriver etc, no joy at all. Most of the posts on the topic suggest that it was an issue with 
Turns out, in the end, that the issue was it being run in the main activity. So, created an Async task, called by a button click with the whole PostgreSQL code under that task. 
Works perfectly!
Under the main activity I've got a button creating new view: 
public void onClick(View v) {
           
new Asynctask().execute();
           
}
this is executing the class Asynctask which is:
class Asynctask extends AsyncTask {


       
@Override
       
protected Object doInBackground(Object[] params) {
           
try {
               
Class.forName("org.postgresql.Driver");
               
System.out.println("Class Found");
           
} catch (ClassNotFoundException e) {
                e
.printStackTrace();
               
System.out.println("Class not found");
           
}
           
//  System.out.println("Test");
           
Connection connection = null;
           
Statement sql = null;
           
ResultSet result = null;


           
String url = "jdbc:postgresql://urlhere:5432/database";
           
String username = "SkippyMcAwesome";
           
String password = "password";
           
try {


                connection
= DriverManager.getConnection(url, username, password);
                sql
= connection.createStatement();
                result
= sql.executeQuery("select * from test.test");
               
if (result.next()) {
                   
System.out.println(result.getString(1)+ "," + result.getString(2) + "," +result.getString(3));
                   
System.out.println("Connected!");
                    connection
.close();
               
}
           
} catch (SQLException e1) {
                e1
.printStackTrace();
               
System.out.println("connection failed");
           
}
           
return null;
       
}
   
}

I know it's not brilliant, but it works!
And made me very happy.
-Skip
Reply all
Reply to author
Forward
0 new messages