user1667162
user1667162

Reputation:

Android Java ODBC Connection

i am here with another problem about android... I am trying to connect to my mysql database with that code:

  public void testDB() {
    TextView tv = (TextView)this.findViewById(R.id.textView1);
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, user, pass);
        /* System.out.println("Database connection success"); */

        String result = "Database connection success\n";
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from users");
        ResultSetMetaData rsmd = rs.getMetaData();

        while(rs.next()) {
            result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
            result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
            result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
        }
        tv.setText(result);
    }
    catch(Exception e) {
        e.printStackTrace();
        tv.setText(e.toString());
    }   

}

In the AVD i get this error:

10-23 16:49:08.103: W/System.err(12939): java.sql.SQLException: Unable to connect to any hosts due to exception: android.os.NetworkOnMainThreadException

I think there's something wrong in the libs, is that true? But i tryied this on bluestack emulator, with android gingerbread i think and the connection work good... Does someone know how can i do?

Upvotes: 1

Views: 3338

Answers (4)

molnarm
molnarm

Reputation: 10031

The exception is very informative: you are doing network operations in the main thread which is not allowed. This article is a guide to background operations.

Upvotes: 2

ajpolt
ajpolt

Reputation: 1002

You're getting a NetworkOnMainThreadException. With Honeycomb and forward, you can't do any networking tasks on your main thread, which means you need to move your code off into a separate thread. I'd suggest an AsyncTask.

Upvotes: 2

kosa
kosa

Reputation: 66637

 java.sql.SQLException: Unable to connect to any hosts due to exception: android.os.NetworkOnMainThreadException

All network calls should be on separate threads instead on main thread. You need to use AsynchTask to make network calls.

Here is android tutorial on how to write asynchtask for this purpose.

Upvotes: 1

Carnal
Carnal

Reputation: 22064

This is because you're doing a network operation in the main thread, consider using an AsyncTask for network operations.

Example of AsyncTask implementation: http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/

Do your network operation in doInBackground.

Upvotes: 1

Related Questions