String[] items = new String[10];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://servername.database.windows.net;" +
"databaseName=School;user=username@servername;password=userpassword";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.list_item,
new ArrayList()));
new AddStringTask().execute();
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM dbo.tbl";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
String items = rs.getArray(2) + " " + rs.getArray(3);
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
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) {}
}
}
class AddStringTask extends AsyncTask<Void, String, Void> {
@Override
protected Void doInBackground(Void... unused) {
return(null);
}
@Override
protected void onProgressUpdate(String... item) {
((ArrayAdapter)getListAdapter()).add(item[0]);
}
@Override
protected void onPostExecute(Void unused) {
Toast
.makeText(AsyncDemo.this, "Done!", Toast.LENGTH_SHORT)
.show();
}
}
In the while loop inside onCreate I would like to get 10 rows and 2 columns from the table in the remote database which is sql azure then store it in a string array. Then that string array gets outputted to the user as a list view. JDBC driver download link min.bz/wC4Am (Non-Windows users get compressed file. The last one listed)Also updated the link.
Android-Java-SQLAzure good combination, congrats!
On the other hand, why do you access database (SQL Azure) directly from mobile app? This has a few drawbacks:
Therefore you should create a web service or REST API with Java or ASP.NET which you can execute your queries through this proxy and gives you results back in a JSON, or XML or a good format that Java can easily parse and adapt your ArrayAdapter.