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?
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.