How to retrieve and view data from a SQL Server using sqljdbc library in Android? -
i having troubles in "how to's" of connecting prepoppulated database being used our asp.net application.
so, problem have used sqljdbc4.jar library try connect database , during exceptions , cant seem find solution it. appreciate if correct code or give me regarding it. cant seem find solution anywhere.
below code calling in oncreate block in mainactivity in getting os.networkonmainthreadexception
public void testdb() { textview tv = (textview) this.findviewbyid(r.id.text_view); // create variable connection string. string connectionurl = "jdbc:sqlserver://localhost:1433;" + "databasename=cafeapp;user=sunny;password="; string result = "database connection success\n"; // declare jdbc objects. connection con = null; statement stmt = null; resultset rs = null; resultsetmetadata rsmd; try { // establish connection. class.forname("com.microsoft.sqlserver.jdbc.sqlserverdriver"); con = drivermanager.getconnection(connectionurl); // create , execute sql statement returns data. string sql = "select top 10 * inventory.inventory_name"; stmt = con.createstatement(); rs = stmt.executequery(sql); rsmd = rs.getmetadata(); // iterate through data in result set , display it. while (rs.next()) { // system.out.println(rs.getstring(4) + " " + rs.getstring(6)); result += rsmd.getcolumnname(1) + ": " + rs.getint(1) + "\n"; result += rsmd.getcolumnname(2) + ": " + rs.getstring(2) + "\n"; result += rsmd.getcolumnname(3) + ": " + rs.getint(3) + "\n"; } tv.settext(result); } // handle errors may have occurred. catch (exception e) { e.printstacktrace(); tv.settext(e.tostring()); } { if (rs != null) try { rs.close(); } catch(exception e) { } if (stmt != null) try { stmt.close(); } catch(exception e) { } if (con != null) try { con.close(); } catch(exception e) { } }}
you have use asynctask... because android doesn't allow networking task on it's main thread.
just put testdb() method on separate thread.
new thread(new runnable() { @override public void run() { testdb() } }).start();
Comments
Post a Comment