2

I am trying to use Google BigQuery in my android app. Unfortunately, I didn't manage to find a tutorial on this topic. So I am trying to call start method of this class:

public class BigQuery {
public static Bigquery createAuthorizedClient() throws IOException {
    // Create the credential
    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);

    if (credential.createScopedRequired()) {
        credential = credential.createScoped(BigqueryScopes.all());
    }

    return new Bigquery.Builder(transport, jsonFactory, credential)
            .setApplicationName("Bigquery Samples")
            .build();
}
private static List<TableRow> executeQuery(String querySql, Bigquery bigquery, String projectId)
        throws IOException {
    QueryResponse query =
            bigquery.jobs().query(projectId, new QueryRequest().setQuery(querySql)).execute();

    // Execute it
    GetQueryResultsResponse queryResult =
            bigquery
                    .jobs()
                    .getQueryResults(
                            query.getJobReference().getProjectId(), query.getJobReference().getJobId())
                    .execute();

    return queryResult.getRows();
}


private static void displayResults(List<TableRow> rows) {
    System.out.print("\nResults:\n------------\n");
    for (TableRow row : rows) {
        for (TableCell field : row.getF()) {
            System.out.printf("%-50s", field.getV());
        }
        System.out.println();
    }
}

public static void main(String[] args) throws IOException {

    String projectId = "ukrbikeapp";

    // Create a new Bigquery client authorized via Application Default Credentials.
    Bigquery bigquery = createAuthorizedClient();

    List<TableRow> rows =
            executeQuery(
                    "SELECT COUNT(event_dim.name) as DefeatEvents,\n" +
                            "event_dim.params.value.string_value as CharacterClass\n" +
                            "FROM [ukrbikeapp:info_firebase_ANDROID.app_events]\n" +
                            "WHERE event_dim.name = 'select_content'\n" +
                            "AND event_dim.params.key = 'item_name'\n" +
                            "GROUP BY CharacterClass\n" +
                            "ORDER BY DefeatEvents desc",
                    bigquery,
                    projectId);

    displayResults(rows);
}
}

But then I get

E/UncaughtException: android.os.NetworkOnMainThreadException

Please, help me to solve this problem.

1 Answers1

1

This is to help prevent the UI for your app stalling while waiting for the network. To fix the issue, use AsyncTask to perform the query in a separate thread and then update the UI based on the results. Take a look at AyncTask Android example.

Community
  • 1
  • 1
Elliott Brossard
  • 32,095
  • 2
  • 67
  • 99