Example usage for android.database MatrixCursor newRow

List of usage examples for android.database MatrixCursor newRow

Introduction

In this page you can find the example usage for android.database MatrixCursor newRow.

Prototype

public RowBuilder newRow() 

Source Link

Document

Adds a new row to the end and returns a builder for that row.

Usage

From source file:com.owncloud.android.providers.UsersAndGroupsSearchProvider.java

private Cursor searchForUsersOrGroups(Uri uri) {
    MatrixCursor response = null;

    String userQuery = uri.getLastPathSegment().toLowerCase();

    /// need to trust on the AccountUtils to get the current account since the query in the client side is not
    /// directly started by our code, but from SearchView implementation
    Account account = AccountUtils.getCurrentOwnCloudAccount(getContext());

    /// request to the OC server about users and groups matching userQuery
    GetRemoteShareesOperation searchRequest = new GetRemoteShareesOperation(userQuery, REQUESTED_PAGE,
            RESULTS_PER_PAGE);//  w ww  .j  a v a  2 s . c  o m
    RemoteOperationResult result = searchRequest.execute(account, getContext());
    List<JSONObject> names = new ArrayList<JSONObject>();
    if (result.isSuccess()) {
        for (Object o : result.getData()) {
            // Get JSonObjects from response
            names.add((JSONObject) o);
        }
    } else {
        showErrorMessage(result);
    }

    /// convert the responses from the OC server to the expected format
    if (names.size() > 0) {
        response = new MatrixCursor(COLUMNS);
        Iterator<JSONObject> namesIt = names.iterator();
        int count = 0;
        JSONObject item;
        String displayName;
        Uri dataUri;
        Uri userBaseUri = new Uri.Builder().scheme("content").authority(DATA_USER).build();
        Uri groupBaseUri = new Uri.Builder().scheme("content").authority(DATA_GROUP).build();
        try {
            while (namesIt.hasNext()) {
                item = namesIt.next();
                String userName = item.getString(GetRemoteShareesOperation.PROPERTY_LABEL);
                JSONObject value = item.getJSONObject(GetRemoteShareesOperation.NODE_VALUE);
                byte type = (byte) value.getInt(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE);
                String shareWith = value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH);
                if (GetRemoteShareesOperation.GROUP_TYPE.equals(type)) {
                    displayName = getContext().getString(R.string.share_group_clarification, userName);
                    dataUri = Uri.withAppendedPath(groupBaseUri, shareWith);
                } else {
                    displayName = userName;
                    dataUri = Uri.withAppendedPath(userBaseUri, shareWith);
                }
                response.newRow().add(count++) // BaseColumns._ID
                        .add(displayName) // SearchManager.SUGGEST_COLUMN_TEXT_1
                        .add(dataUri);
            }
        } catch (JSONException e) {
            Log_OC.e(TAG, "Exception while parsing data of users/groups", e);
        }
    }

    return response;
}

From source file:fr.seeks.SuggestionProvider.java

public void setCursorOfQueryThrow(Uri uri, String query, MatrixCursor matrix)
        throws MalformedURLException, IOException {
    String url = getUrlFromKeywords(query);
    Log.v(TAG, "Query:" + url);

    String json = null;//  ww  w. ja  va  2  s  . co  m

    while (json == null) {
        HttpURLConnection connection = null;
        connection = (HttpURLConnection) (new URL(url)).openConnection();

        try {
            connection.setDoOutput(true);
            connection.setChunkedStreamingMode(0);
            connection.setInstanceFollowRedirects(true);

            connection.connect();
            int response = connection.getResponseCode();
            if (response == HttpURLConnection.HTTP_MOVED_PERM
                    || response == HttpURLConnection.HTTP_MOVED_TEMP) {
                Map<String, List<String>> list = connection.getHeaderFields();
                for (Entry<String, List<String>> entry : list.entrySet()) {
                    String value = "";
                    for (String s : entry.getValue()) {
                        value = value + ";" + s;
                    }
                    Log.v(TAG, entry.getKey() + ":" + value);
                }
                // FIXME
                url = "";
                return;
            }
            InputStream in = connection.getInputStream();

            BufferedReader r = new BufferedReader(new InputStreamReader(in));
            StringBuilder builder = new StringBuilder();

            String line;
            while ((line = r.readLine()) != null) {
                builder.append(line);
            }

            json = builder.toString();

            /*
             * Log.v(TAG, "** JSON START **"); Log.v(TAG, json); Log.v(TAG,
             * "** JSON END **");
             */
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            connection.disconnect();
        }
    }

    JSONArray snippets;
    JSONObject object;
    JSONArray suggestions;

    Boolean show_snippets = mPrefs.getBoolean("show_snippets", false);
    if (show_snippets) {
        try {
            object = (JSONObject) new JSONTokener(json).nextValue();
            snippets = object.getJSONArray("snippets");
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }
        Log.v(TAG, "Snippets found: " + snippets.length());
        for (int i = 0; i < snippets.length(); i++) {
            JSONObject snip;
            try {
                snip = snippets.getJSONObject(i);
                matrix.newRow().add(i).add(snip.getString("title")).add(snip.getString("summary"))
                        .add(snip.getString("title")).add(Intent.ACTION_SEND).add(snip.getString("url"));
            } catch (JSONException e) {
                e.printStackTrace();
                continue;
            }
        }
    } else {
        try {
            object = (JSONObject) new JSONTokener(json).nextValue();
            suggestions = object.getJSONArray("suggestions");
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }
        Log.v(TAG, "Suggestions found: " + suggestions.length());
        for (int i = 0; i < suggestions.length(); i++) {
            try {
                matrix.newRow().add(i).add(suggestions.getString(i)).add("").add(suggestions.getString(i))
                        .add(Intent.ACTION_SEARCH).add("");
            } catch (JSONException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);

}

From source file:saschpe.birthdays.service.CalendarSyncService.java

private static Cursor getContactsEvents(Context context, ContentResolver contentResolver) {
    // Account blacklist from our provider
    List<Account> accountBlacklist = AccountProviderHelper.getAccountList(context);

    List<String> addedEventsIdentifiers = new ArrayList<>();

    /* 1. Get all raw contacts with their corresponding Account name and type (only raw
     *    contacts get Account affiliation) */
    Uri rawContactsUri = ContactsContract.RawContacts.CONTENT_URI;
    String[] rawContactsProjection = new String[] { ContactsContract.RawContacts._ID,
            ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,
            ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE };
    Cursor rawContacts = contentResolver.query(rawContactsUri, rawContactsProjection, null, null, null);

    /* 2. Go over all raw contacts and check if the Account is allowed. If account is allowed,
     *    get display name and lookup key and all events for this contact. Build a new
     *    MatrixCursor out of this data that can be used. */
    String[] columns = new String[] { BaseColumns._ID, ContactsContract.Data.DISPLAY_NAME,
            ContactsContract.Data.LOOKUP_KEY, ContactsContract.CommonDataKinds.Event.START_DATE,
            ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.LABEL, };
    MatrixCursor mc = new MatrixCursor(columns);
    int mcIndex = 0;
    try {// w  w  w.j a v a  2 s  . co m
        while (rawContacts != null && rawContacts.moveToNext()) {
            long rawId = rawContacts.getLong(rawContacts.getColumnIndex(ContactsContract.RawContacts._ID));
            String accountType = rawContacts
                    .getString(rawContacts.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
            String accountName = rawContacts
                    .getString(rawContacts.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME));

            // 2a. Check if Account is allowed (not in blacklist)
            boolean addEvent;
            if (TextUtils.isEmpty(accountType) || TextUtils.isEmpty(accountName)) {
                // Workaround: Simply add events without proper Account
                addEvent = true;
            } else {
                Account account = new Account(accountName, accountType);
                addEvent = !accountBlacklist.contains(account);
            }

            if (addEvent) {
                String displayName = null;
                String lookupKey = null;

                // 2b. Get display name and lookup key from normal contact table
                String[] displayProjection = new String[] { ContactsContract.Data.RAW_CONTACT_ID,
                        ContactsContract.Data.DISPLAY_NAME, ContactsContract.Data.LOOKUP_KEY };
                String displayWhere = ContactsContract.Data.RAW_CONTACT_ID + "= ?";
                String[] displaySelectionArgs = new String[] { String.valueOf(rawId) };
                Cursor displayCursor = contentResolver.query(ContactsContract.Data.CONTENT_URI,
                        displayProjection, displayWhere, displaySelectionArgs, null);
                try {
                    if (displayCursor != null && displayCursor.moveToNext()) {
                        displayName = displayCursor
                                .getString(displayCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                        lookupKey = displayCursor
                                .getString(displayCursor.getColumnIndex(ContactsContract.Data.LOOKUP_KEY));
                    }
                } finally {
                    if (displayCursor != null && !displayCursor.isClosed()) {
                        displayCursor.close();
                    }
                }

                /* 2c. Get all events for this raw contact. We don't get this information for
                 *     the (merged) contact table, but from the raw contact. If we would query
                 *     this information from the contact table, we would also get events that
                 *     should have been filtered. */
                Uri thisRawContactUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI,
                        rawId);
                Uri entityUri = Uri.withAppendedPath(thisRawContactUri,
                        ContactsContract.RawContacts.Entity.CONTENT_DIRECTORY);
                String[] eventsProjection = new String[] { ContactsContract.RawContacts._ID,
                        ContactsContract.RawContacts.Entity.DATA_ID,
                        ContactsContract.CommonDataKinds.Event.START_DATE,
                        ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.LABEL };
                String eventsWhere = ContactsContract.RawContacts.Entity.MIMETYPE + " = ? AND "
                        + ContactsContract.RawContacts.Entity.DATA_ID + " IS NOT NULL";
                String[] eventsSelectionArgs = new String[] {
                        ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
                Cursor eventsCursor = contentResolver.query(entityUri, eventsProjection, eventsWhere,
                        eventsSelectionArgs, null);
                try {
                    while (eventsCursor != null && eventsCursor.moveToNext()) {
                        String startDate = eventsCursor.getString(
                                eventsCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
                        int type = eventsCursor.getInt(
                                eventsCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE));
                        String label = eventsCursor.getString(
                                eventsCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.LABEL));

                        /* 2d. Add this information to our MatrixCursor if not already added
                         *     previously. If two Event Reminder accounts have the same contact
                         *     with duplicated events, the event will already be in the HashSet
                         *     addedEventsIdentifiers.
                         *
                         *     eventIdentifier does not include startDate, because the
                         *     String formats of startDate differ between accounts. */
                        //String eventIdentifier = lookupKey + type + label;
                        String eventIdentifier = lookupKey + type;
                        if (addedEventsIdentifiers.contains(eventIdentifier)) {
                            Log.d(TAG, "Duplicate event was not added!");
                        } else {
                            Log.d(TAG, "Event was added with identifier " + eventIdentifier);

                            addedEventsIdentifiers.add(eventIdentifier);

                            mc.newRow().add(mcIndex).add(displayName).add(lookupKey).add(startDate).add(type)
                                    .add(label);
                            mcIndex++;
                        }

                    }
                } finally {
                    if (eventsCursor != null && !eventsCursor.isClosed()) {
                        eventsCursor.close();
                    }
                }
            }
        }
    } finally {
        if (rawContacts != null && !rawContacts.isClosed()) {
            rawContacts.close();
        }
    }
    /*if (BuildConfig.DEBUG) {
    DatabaseUtils.dumpCursor(mc);
    }*/
    return mc;
}