2

I am working with android 4.1.1, IDE= eclipse, and SQL Server 2008.

Device= Note 2

android:minSdkVersion="10"

When I run the code snippet on the UI thread It gives me the error "Unable to get information from SQL Server:", but if I run the code in a background thread or AsyncTask Thread it works. Any help in understanding the two processes would be greatly appreciated?

Note: "The issue occurred when I upgrade the minSDKVersion from 8 to 10."

public Boolean open() {
    Boolean res = false;
    try {
        String s = "jdbc:jtds:sqlserver://" + "xx.xxx.x.xx" + "/" + "FOO" + ";instance=SQLEXPRESS";
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        con = DriverManager.getConnection(s, "UserFoo", "1234");
        res = true;
    } catch (SQLException sx) {
        Log.e(TAG, "DB:Open - " + sx.toString());
    } catch (ClassNotFoundException e) {
        Log.e(TAG, "DB:Open - " + e.toString());
    }

    return res;

}
skink
  • 5,133
  • 6
  • 37
  • 58
Frostbyte
  • 31
  • 4
  • 2
    Not to rain on your parade, but instead of calling a SQL Server database directly from your app, you'd be better off creating a web service to expose the data that you want. It's much better for security, more portable, and easier to use in your app. – Jim Nov 15 '12 at 17:47
  • Update: Sorry for the delay. This was fixed when putting connection code in a separate thread. Thanks to all that helped... – Frostbyte Apr 23 '13 at 14:33

1 Answers1

1

Starting with Android 3.0, trying to access the network on the main (UI) thread results in:

NetworkOnMainThreadException

I'm guessing that you didn't see it because somewhere higher in your call stack you have:

catch (Exception)

which leads to:

"Unable to get information from SQL Server:"

As you have already discovered, a separate thread is the solution.

Simon
  • 14,407
  • 8
  • 46
  • 61
  • Thanks for the feedback, Simon. Forgive my noobness, but are you saying starting with Android 3.0 a new thread must be created every time we want to make a connection to SQL Server? If so, what are the best practices? Or do you know of any articles detailing best practices? – Frostbyte Nov 15 '12 at 17:21
  • 1
    Yes. Must be a new thread. http://www.vogella.com/articles/AndroidPerformance/article.html As to best practice, actually good practice since best says that you've evaluated all possible practices, measured them and selected the best, it depends but normally, it makes no difference and and AsyncTask will do nicely. – Simon Nov 15 '12 at 18:04