Cursors

This interface provides random read-write access to the result set returned by a database query.

The cursor begins at position -1 (before the first row). On moveToNext() it will point to the first row and return either true (next row exists) or false (already at end of rows). Other options include moveToPrevious(), moveToFirst() and moveToLast(). getColumnIndex (String columnName) will return the index of the column with the given name (columns are numbered beginning with 0). Use one of the get methods to retrieve the actual value (e.g. getString(int columnIndex), getInt(int columnIndex)), passing in the column index as an argument. getCount() returns the number of rows that are in the Cursor. close() should be called when you are finished interacting with the Cursor to prevent memory leaks leading to app crashes. The following code snippet iterates through all of the rows in the Cursor and prints out what was in the table:

int wordCol = cursor.getColumnIndex(ExampleContract.COLUMN_WORD);
int defCol = cursor.getColumnIndex(ExampleContract.COLUMN_DEFINITION);

while (cursor.moveToNext()) {
  String word = cursor.getString(wordCol);
  String definition = cursor.getString(defCol);
  Log.v("Cursor Example", word + " - " + definition);
}

cursor.close();

This code could be run in the postExecute() method of an AsyncTask so it has access to the data from the Cursor.
ud851-Exercises-student\Lesson08-Quiz-Example\T08.03

Content Resolver

Use a Content Resolver to handle the SQL commands (query(), insert(), update() or delete()) to a Content Provider’s data source. Since this can be a demanding task it should not be run on the main thread (e.g. AsyncTask):

Content URI (e.g. content://com.example.android.exampleapp/data) is comprised of: Content Provider Prefix: content:// Content Authority: com.example.android.exampleapp Path to Specific Data: data Against each argument is the SQL equivalent. For query():

ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query // returns a Cursor object which contains all of the information requested. query() can be replaced with insert/update/delete()
    (ExampleAppContract.CONTENT_URI, // FROM table_name. Developer for Content Provider should have specified this constant in their app
     null, // Projection - col,col,col,... The columns to return for each row
     null, // selection - WHERE col = value. specifies the criteria for selecting rows.
     null, // selectionArgs - No exact equivalent. Selection arguments replace ? placeholders in the selection clause.
     null); // sortOrder - ORDER BY col,col,...

For insert():

ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.insert
    (ExampleAppContract.CONTENT_URI, // FROM table_name. Developer for Content Provider should have specified this constant in their app
     null); // ContentValues - the values to be inserted in array of key-value pairings (key is column name)

For update():

ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.update
    (ExampleAppContract.CONTENT_URI, // FROM table_name. Developer for Content Provider should have specified this constant in their app
     null, // ContentValues - the values to be updated in array of key-value pairings (key is column name)
     null, // selection - WHERE filter specifies the criteria for selecting rows.
     null); // selectionArgs - No exact equivalent. Selection arguments replace ? placeholders in the selection clause.

For delete():

ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.delete
    (ExampleAppContract.CONTENT_URI, // FROM table_name. Developer for Content Provider should have specified this constant in their app
     null, // selection - WHERE filter specifies the criteria for selecting rows.
     null); // selectionArgs - No exact equivalent. Selection arguments replace ? placeholders in the selection clause.

ud851-Exercises-student\Lesson08-Quiz-Example\T08.02

Explicit Intent with URL

Open a third party app to view a webpage using implicit Intent.

    private void openWebPage(String url) {
        /*
         * We wanted to demonstrate the Uri.parse method because its usage occurs frequently. You
         * could have just as easily passed in a Uri as the parameter of this method.
         */
        Uri webpage = Uri.parse(url);

        /*
         * Here, we create the Intent with the action of ACTION_VIEW. This action allows the user
         * to view particular content. In this case, our webpage URL.
         */
        Intent intent = new Intent(Intent.ACTION_VIEW, webpage);

        /*
         * This is a check we perform with every implicit Intent that we launch. In some cases,
         * the device where this code is running might not have an Activity to perform the action
         * with the data we've specified. Without this check, in those cases your app would crash.
         */
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
    }

Build a URL with Uri Builder includes HttpURLConnection function

URL is a specific class of Uri. Use the following function to compile a valid URL. HttpURLConnection will require this when making a connection.

Method to build URL
    final static String BASE_URL =
            "https://api.github.com/search/repositories"; // Query the GitHub repositories
    final static String PARAM_QUERY = "q";
    final static String PARAM_SORT = "sort";
    final static String sortBy = "stars"; // Sorted by the number of stars the repo has

    public static URL buildUrl(String searchQuery) {
        Uri builtURI = Uri.parse(BASE_URL)
                .buildUpon()
                .appendQueryParameter(PARAM_QUERY, searchQuery)
                .appendQueryParameter(PARAM_SORT, sortBy)
                .build();
        try {
            URL url = new URL(builtURI.toString());
            Log.d("buildUrl produced URL ", url.toString()); // Produces URL: https://api.github.com/search/repositories?q=android&sort=stars
            return url;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.d("buildUrl", "Exception thrown");
        }
        return null;
    }

A typical helper method for fetching the results of the query based on the URL.

    public static String getResponseFromHttpUrl(URL url) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            InputStream in = urlConnection.getInputStream();

            Scanner scanner = new Scanner(in);
            scanner.useDelimiter("\\A"); // \A represents the beginning of the stream. Forces the scanner to read the entire contents of the stream
// It buffers the data and also converts the stream from UTF-8 (JSON/JS) to UTF-16 (which Android uses)
            boolean hasInput = scanner.hasNext();
            if (hasInput) {
                return scanner.next();
            } else {
                return null;
            }
        } finally {
            urlConnection.disconnect();
        }
    }

ud851-Exercises-student\Lesson02-GitHub-Repo-Search\T02.06-Exercise-AddPolish