Example usage for android.database MatrixCursor MatrixCursor

List of usage examples for android.database MatrixCursor MatrixCursor

Introduction

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

Prototype

public MatrixCursor(String[] columnNames) 

Source Link

Document

Constructs a new cursor.

Usage

From source file:com.deliciousdroid.client.DeliciousFeed.java

/**
 * Retrieves a list of tags for a Delicious user.
 * //  w w w  . j a  va 2  s  .co  m
 * @param username Username of the Delicious user.
 * @return The list of tags received from the server.
 * @throws JSONException If an error was encountered in deserializing the JSON object returned from 
 * the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 */
public static Cursor fetchFriendTags(String username)
        throws JSONException, IOException, AuthenticationException {

    final HttpGet post = new HttpGet(FETCH_TAGS_URI + username + "?count=100");

    final MatrixCursor tagCursor = new MatrixCursor(new String[] { Tag._ID, Tag.Name, Tag.Count });

    final HttpResponse resp = HttpClientFactory.getThreadSafeClient().execute(post);
    final String response = EntityUtils.toString(resp.getEntity());

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

        final JSONObject tags = new JSONObject(response);
        Iterator<?> i = tags.keys();
        while (i.hasNext()) {
            Object e = i.next();

            tagCursor.addRow(new Object[] { 0, e.toString(), tags.getInt(e.toString()) });
        }

        Log.d(TAG, response);

    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in fetching friend status list");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in fetching friend status list");
            throw new IOException();
        }
    }
    return tagCursor;
}

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    final long now = System.currentTimeMillis();
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
    int provider = Integer.parseInt(sp.getString(Configuration.PREFS_KEY_EXCHANGE_PROVIDER, "0"));
    boolean forceRefresh = sp.getBoolean(Configuration.PREFS_KEY_EXCHANGE_FORCE_REFRESH, false);
    if (forceRefresh)
        sp.edit().putBoolean(Configuration.PREFS_KEY_EXCHANGE_FORCE_REFRESH, false).commit();

    if (lastUpdated == 0 || now - lastUpdated > UPDATE_FREQ_MS) {
        float newCcnBtcConversion = -1;
        if ((ccnBtcConversion == -1 && newCcnBtcConversion == -1) || forceRefresh)
            newCcnBtcConversion = requestCcnBtcConversion(provider);

        if (newCcnBtcConversion != -1)
            ccnBtcConversion = newCcnBtcConversion;

        if (CCNBtcConversion == -1)
            return null;

        Map<String, ExchangeRate> newExchangeRates = null;
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BITCOINAVERAGE_URL, ccnBtcConversion, userAgent,
                    BITCOINAVERAGE_SOURCE, BITCOINAVERAGE_FIELDS);
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BLOCKCHAININFO_URL, ccnBtcConversion, userAgent,
                    BLOCKCHAININFO_SOURCE, BLOCKCHAININFO_FIELDS);

        if (newExchangeRates != null) {
            String providerUrl;/*from w ww.  j a va  2  s  .c  o m*/
            switch (provider) {
            case 0:
                providerUrl = "http://www.cryptsy.com";
                break;
            case 1:
                providerUrl = "http://www.vircurex.com";
                break;
            default:
                providerUrl = "";
                break;
            }
            float mBTCRate = ccnBtcConversion * 1000;
            String strmBTCRate = String.format(Locale.US, "%.5f", mBTCRate).replace(',', '.');
            newExchangeRates.put("mBTC", new ExchangeRate("mBTC",
                    new BigDecimal(GenericUtils.toNanoCoins(strmBTCRate, 0)).toBigInteger(), providerUrl));
            newExchangeRates.put("CCN",
                    new ExchangeRate("CCN", BigInteger.valueOf(100000000), "priceofccn.com"));
            exchangeRates = newExchangeRates;
            lastUpdated = now;

            final ExchangeRate exchangeRateToCache = bestExchangeRate(config.getExchangeCurrencyCode());
            if (exchangeRateToCache != null)
                config.setCachedExchangeRate(exchangeRateToCache);
        }
    }

    if (exchangeRates == null || ccnBtcConversion == -1)
        return null;

    final MatrixCursor cursor = new MatrixCursor(
            new String[] { BaseColumns._ID, KEY_CURRENCY_CODE, KEY_RATE, KEY_SOURCE });

    if (selection == null) {
        for (final Map.Entry<String, ExchangeRate> entry : exchangeRates.entrySet()) {
            final ExchangeRate rate = entry.getValue();
            cursor.newRow().add(rate.currencyCode.hashCode()).add(rate.currencyCode).add(rate.rate.longValue())
                    .add(rate.source);
        }
    } else if (selection.equals(KEY_CURRENCY_CODE)) {
        final ExchangeRate rate = bestExchangeRate(selectionArgs[0]);
        if (rate != null)
            cursor.newRow().add(rate.currencyCode.hashCode()).add(rate.currencyCode).add(rate.rate.longValue())
                    .add(rate.source);
    }

    return cursor;
}

From source file:com.example.android.vault.VaultProvider.java

@Override
public Cursor queryRoots(String[] projection) throws FileNotFoundException {
    final MatrixCursor result = new MatrixCursor(resolveRootProjection(projection));
    final RowBuilder row = result.newRow();
    row.add(Root.COLUMN_ROOT_ID, DEFAULT_ROOT_ID);
    row.add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE | Root.FLAG_LOCAL_ONLY);
    row.add(Root.COLUMN_TITLE, getContext().getString(R.string.app_label));
    row.add(Root.COLUMN_DOCUMENT_ID, DEFAULT_DOCUMENT_ID);
    row.add(Root.COLUMN_ICON, R.drawable.ic_lock_lock);

    // Notify user in storage UI when key isn't hardware-backed
    if (!mHardwareBacked) {
        row.add(Root.COLUMN_SUMMARY, getContext().getString(R.string.info_software));
    }//from w  ww .  j  ava 2s  .  c o  m

    return result;
}

From source file:com.dopecoin.wallet.ExchangeRatesProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    final long now = System.currentTimeMillis();
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
    int provider = Integer.parseInt(sp.getString(Constants.PREFS_KEY_EXCHANGE_PROVIDER, "0"));
    boolean forceRefresh = sp.getBoolean(Constants.PREFS_KEY_EXCHANGE_FORCE_REFRESH, false);
    if (forceRefresh)
        sp.edit().putBoolean(Constants.PREFS_KEY_EXCHANGE_FORCE_REFRESH, false).commit();

    if (lastUpdated == 0 || now - lastUpdated > UPDATE_FREQ_MS) {
        float newDogeBtcConversion = -1;
        if ((leafBtcConversion == -1 && newDogeBtcConversion == -1) || forceRefresh)
            newDogeBtcConversion = requestDogeBtcConversion(provider);

        if (newDogeBtcConversion != -1)
            leafBtcConversion = newDogeBtcConversion;

        if (leafBtcConversion == -1)
            return null;

        Map<String, ExchangeRate> newExchangeRates = null;
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BITCOINAVERAGE_URL, leafBtcConversion, userAgent,
                    BITCOINAVERAGE_FIELDS);
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BLOCKCHAININFO_URL, leafBtcConversion, userAgent,
                    BLOCKCHAININFO_FIELDS);

        if (newExchangeRates != null) {
            String providerUrl;//from  w  w w. ja va 2s. co m
            switch (provider) {
            case 0:
                providerUrl = "http://www.cryptsy.com";
                break;
            case 1:
                providerUrl = "http://www.vircurex.com";
                break;
            default:
                providerUrl = "";
                break;
            }
            float mBTCRate = leafBtcConversion * 1000;
            String strmBTCRate = String.format("%.5f", mBTCRate).replace(',', '.');
            newExchangeRates.put("mBTC", new ExchangeRate("mBTC",
                    new BigDecimal(GenericUtils.toNanoCoins(strmBTCRate, 0)).toBigInteger(), providerUrl));
            exchangeRates = newExchangeRates;
            lastUpdated = now;

            final ExchangeRate exchangeRateToCache = bestExchangeRate(config.getExchangeCurrencyCode());
            if (exchangeRateToCache != null)
                config.setCachedExchangeRate(exchangeRateToCache);
        }
    }

    if (exchangeRates == null || leafBtcConversion == -1)
        return null;

    final MatrixCursor cursor = new MatrixCursor(
            new String[] { BaseColumns._ID, KEY_CURRENCY_CODE, KEY_RATE, KEY_SOURCE });

    if (selection == null) {
        for (final Map.Entry<String, ExchangeRate> entry : exchangeRates.entrySet()) {
            final ExchangeRate rate = entry.getValue();
            cursor.newRow().add(rate.currencyCode.hashCode()).add(rate.currencyCode).add(rate.rate.longValue())
                    .add(rate.source);
        }
    } else if (selection.equals(KEY_CURRENCY_CODE)) {
        final ExchangeRate rate = bestExchangeRate(selectionArgs[0]);
        if (rate != null)
            cursor.newRow().add(rate.currencyCode.hashCode()).add(rate.currencyCode).add(rate.rate.longValue())
                    .add(rate.source);
    }

    return cursor;
}

From source file:de.langerhans.wallet.ExchangeRatesProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    final long now = System.currentTimeMillis();
    int provider = config.getExchangeProvider();
    boolean forceRefresh = config.getExchangeForceRefresh();
    if (forceRefresh) {
        config.setExchangeForceRefresh(false);
    }/*from   w  w  w  . ja v a  2  s . c o m*/

    final boolean offline = uri.getQueryParameter(QUERY_PARAM_OFFLINE) != null;

    if (!offline && (lastUpdated == 0 || now - lastUpdated > UPDATE_FREQ_MS) || forceRefresh) {
        double newDogeBtcConversion = -1;
        if ((dogeBtcConversion == -1 && newDogeBtcConversion == -1) || forceRefresh)
            newDogeBtcConversion = requestDogeBtcConversion(provider);

        if (newDogeBtcConversion != -1)
            dogeBtcConversion = newDogeBtcConversion;

        if (dogeBtcConversion == -1)
            return null;

        Map<String, ExchangeRate> newExchangeRates = null;
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BITCOINAVERAGE_URL, dogeBtcConversion, userAgent,
                    BITCOINAVERAGE_SOURCE, BITCOINAVERAGE_FIELDS);
        if (newExchangeRates == null)
            newExchangeRates = requestExchangeRates(BLOCKCHAININFO_URL, dogeBtcConversion, userAgent,
                    BLOCKCHAININFO_SOURCE, BLOCKCHAININFO_FIELDS);

        if (newExchangeRates != null) {
            String providerUrl;
            switch (provider) {
            case 0:
                providerUrl = "http://www.cryptsy.com";
                break;
            case 1:
                providerUrl = "http://www.bter.com";
                break;
            default:
                providerUrl = "";
                break;
            }
            double mBTCRate = dogeBtcConversion * 1000;
            String strmBTCRate = String.format(Locale.US, "%.4f", mBTCRate).replace(',', '.');
            newExchangeRates.put("mBTC",
                    new ExchangeRate(
                            new com.dogecoin.dogecoinj.utils.ExchangeRate(Fiat.parseFiat("mBTC", strmBTCRate)),
                            providerUrl));
            newExchangeRates.put("DOGE",
                    new ExchangeRate(new com.dogecoin.dogecoinj.utils.ExchangeRate(Fiat.parseFiat("DOGE", "1")),
                            "priceofdoge.com"));
            exchangeRates = newExchangeRates;
            lastUpdated = now;

            final ExchangeRate exchangeRateToCache = bestExchangeRate(config.getExchangeCurrencyCode());
            if (exchangeRateToCache != null)
                config.setCachedExchangeRate(exchangeRateToCache);
        }
    }

    if (exchangeRates == null || dogeBtcConversion == -1)
        return null;

    final MatrixCursor cursor = new MatrixCursor(
            new String[] { BaseColumns._ID, KEY_CURRENCY_CODE, KEY_RATE_COIN, KEY_RATE_FIAT, KEY_SOURCE });

    if (selection == null) {
        for (final Map.Entry<String, ExchangeRate> entry : exchangeRates.entrySet()) {
            final ExchangeRate exchangeRate = entry.getValue();
            final com.dogecoin.dogecoinj.utils.ExchangeRate rate = exchangeRate.rate;
            final String currencyCode = exchangeRate.getCurrencyCode();
            cursor.newRow().add(currencyCode.hashCode()).add(currencyCode).add(rate.coin.value)
                    .add(rate.fiat.value).add(exchangeRate.source);
        }
    } else if (selection.equals(QUERY_PARAM_Q)) {
        final String selectionArg = selectionArgs[0].toLowerCase(Locale.US);
        for (final Map.Entry<String, ExchangeRate> entry : exchangeRates.entrySet()) {
            final ExchangeRate exchangeRate = entry.getValue();
            final com.dogecoin.dogecoinj.utils.ExchangeRate rate = exchangeRate.rate;
            final String currencyCode = exchangeRate.getCurrencyCode();
            final String currencySymbol = GenericUtils.currencySymbol(currencyCode);
            if (currencyCode.toLowerCase(Locale.US).contains(selectionArg)
                    || currencySymbol.toLowerCase(Locale.US).contains(selectionArg))
                cursor.newRow().add(currencyCode.hashCode()).add(currencyCode).add(rate.coin.value)
                        .add(rate.fiat.value).add(exchangeRate.source);
        }
    } else if (selection.equals(KEY_CURRENCY_CODE)) {
        final String selectionArg = selectionArgs[0];
        final ExchangeRate exchangeRate = bestExchangeRate(selectionArg);
        if (exchangeRate != null) {
            final com.dogecoin.dogecoinj.utils.ExchangeRate rate = exchangeRate.rate;
            final String currencyCode = exchangeRate.getCurrencyCode();
            cursor.newRow().add(currencyCode.hashCode()).add(currencyCode).add(rate.coin.value)
                    .add(rate.fiat.value).add(exchangeRate.source);
        }
    }

    return cursor;
}

From source file:cn.edu.wyu.documentviewer.RecentLoader.java

@Override
public DirectoryResult loadInBackground() {
    if (mFirstPassLatch == null) {
        // First time through we kick off all the recent tasks, and wait
        // around to see if everyone finishes quickly.

        final Collection<RootInfo> roots = mRoots.getMatchingRootsBlocking(mState);
        for (RootInfo root : roots) {
            if ((root.flags & Root.FLAG_SUPPORTS_RECENTS) != 0) {
                final RecentTask task = new RecentTask(root.authority, root.rootId);
                mTasks.put(root, task);/*from   w  w  w .  jav  a2  s  .co m*/
            }
        }

        mFirstPassLatch = new CountDownLatch(mTasks.size());
        for (RecentTask task : mTasks.values()) {
            ProviderExecutor.forAuthority(task.authority).execute(task);
        }

        try {
            mFirstPassLatch.await(MAX_FIRST_PASS_WAIT_MILLIS, TimeUnit.MILLISECONDS);
            mFirstPassDone = true;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    final long rejectBefore = System.currentTimeMillis() - REJECT_OLDER_THAN;

    // Collect all finished tasks
    boolean allDone = true;
    List<Cursor> cursors = Lists.newArrayList();
    for (RecentTask task : mTasks.values()) {
        if (task.isDone()) {
            try {
                final Cursor cursor = task.get();
                if (cursor == null)
                    continue;

                final FilteringCursorWrapper filtered = new FilteringCursorWrapper(cursor, mState.acceptMimes,
                        RECENT_REJECT_MIMES, rejectBefore) {
                    @Override
                    public void close() {
                        // Ignored, since we manage cursor lifecycle internally
                    }
                };
                cursors.add(filtered);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                // We already logged on other side
            }
        } else {
            allDone = false;
        }
    }

    if (LOGD) {
        Log.d(TAG, "Found " + cursors.size() + " of " + mTasks.size() + " recent queries done");
    }

    final DirectoryResult result = new DirectoryResult();
    result.sortOrder = SORT_ORDER_LAST_MODIFIED;

    // Hint to UI if we're still loading
    final Bundle extras = new Bundle();
    if (!allDone) {
        extras.putBoolean(DocumentsContract.EXTRA_LOADING, true);
    }

    final Cursor merged;
    if (cursors.size() > 0) {
        merged = new MergeCursor(cursors.toArray(new Cursor[cursors.size()]));
    } else {
        // Return something when nobody is ready
        merged = new MatrixCursor(new String[0]);
    }

    final SortingCursorWrapper sorted = new SortingCursorWrapper(merged, result.sortOrder) {
        @Override
        public Bundle getExtras() {
            return extras;
        }
    };

    result.cursor = sorted;

    return result;
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelEpg.java

@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
    Loader<Cursor> loader = null;
    if (Config.SYNC_EPG && mCHannel != null) {
        String where = EpgTbl.EPG_ID + SqlSynatx.EQUALS + mCHannel.getEpgID() + SqlSynatx.AND + EpgTbl.END
                + SqlSynatx.BETWEEN + mDateInfo.getEpgDate().getTime() + SqlSynatx.AND
                + DateUtils.addDay(mDateInfo.getEpgDate()).getTime();
        loader = new CursorLoader(getActivity(), EpgTbl.CONTENT_URI, null, where, null, EpgTbl.END);
    } else {/*ww w.jav  a 2s .  c om*/
        loader = new EpgLoader<Cursor>(getActivity(), mDateInfo) {

            @Override
            protected void onForceLoad() {
                super.onForceLoad();
                setListShown(false);
            }

            @Override
            public Cursor loadInBackground() {
                MatrixCursor cursor = null;
                Date now = mDateInfo.getEpgDate();
                String nowFloat = DateUtils.getFloatDate(now);
                Date tommorrow = DateUtils.addDay(now);
                String tommorrowFloat = DateUtils.getFloatDate(tommorrow);
                String url = ServerConsts.URL_CHANNEL_EPG + mCHannel.getEpgID() + "&start=" + nowFloat + "&end="
                        + tommorrowFloat;
                try {
                    List<EpgEntry> result = null;
                    EpgEntryHandler handler = new EpgEntryHandler();
                    String xml = ServerRequest.getRSString(url);
                    result = handler.parse(xml);
                    if (result != null && !result.isEmpty()) {
                        String[] columnNames = new String[] { EpgTbl._ID, EpgTbl.EPG_ID, EpgTbl.TITLE,
                                EpgTbl.SUBTITLE, EpgTbl.DESC, EpgTbl.START, EpgTbl.END };
                        cursor = new MatrixCursor(columnNames);
                        for (EpgEntry entry : result) {
                            cursor.addRow(new Object[] { entry.getId(), entry.getEpgID(), entry.getTitle(),
                                    entry.getSubTitle(), entry.getDescription(), entry.getStart().getTime(),
                                    entry.getEnd().getTime() });
                        }
                    }

                } catch (AuthenticationException e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "AuthenticationException");
                    e.printStackTrace();
                    showToast(getString(R.string.error_invalid_credentials));
                } catch (ParseException e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "ParseException");
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "ClientProtocolException");
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "IOException");
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "URISyntaxException");
                    e.printStackTrace();
                    showToast(getString(R.string.error_invalid_url) + "\n\n" + ServerConsts.REC_SERVICE_URL);
                } catch (IllegalStateException e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "IllegalStateException");
                    e.printStackTrace();
                    showToast(getString(R.string.error_invalid_url) + "\n\n" + ServerConsts.REC_SERVICE_URL);
                } catch (IllegalArgumentException e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "IllegalArgumentException");
                    showToast(getString(R.string.error_invalid_url) + "\n\n" + ServerConsts.REC_SERVICE_URL);
                } catch (Exception e) {
                    Log.e(ChannelEpg.class.getSimpleName(), "Exception");
                    e.printStackTrace();
                }
                return cursor;
            }
        };
    }

    return loader;
}

From source file:com.teocci.utubinbg.MainActivity.java

/**
 * Options menu in action bar/* w ww  . j  a v  a2  s.  com*/
 *
 * @param menu
 * @return
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    }

    //suggestions
    final CursorAdapter suggestionAdapter = new SimpleCursorAdapter(this, R.layout.dropdown_menu, null,
            new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1 }, new int[] { android.R.id.text1 }, 0);
    final List<String> suggestions = new ArrayList<>();

    searchView.setSuggestionsAdapter(suggestionAdapter);

    searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
        @Override
        public boolean onSuggestionSelect(int position) {
            return false;
        }

        @Override
        public boolean onSuggestionClick(int position) {
            searchView.setQuery(suggestions.get(position), false);
            searchView.clearFocus();

            Intent suggestionIntent = new Intent(Intent.ACTION_SEARCH);
            suggestionIntent.putExtra(SearchManager.QUERY, suggestions.get(position));
            handleIntent(suggestionIntent);

            return true;
        }
    });

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            return false; //if true, no new intent is started
        }

        @Override
        public boolean onQueryTextChange(String suggestion) {
            // check network connection. If not available, do not query.
            // this also disables onSuggestionClick triggering
            if (suggestion.length() > 2) { //make suggestions after 3rd letter

                if (networkConf.isNetworkAvailable()) {

                    new JsonAsyncTask(new JsonAsyncTask.AsyncResponse() {
                        @Override
                        public void processFinish(ArrayList<String> result) {
                            suggestions.clear();
                            suggestions.addAll(result);
                            String[] columns = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1 };
                            MatrixCursor cursor = new MatrixCursor(columns);

                            for (int i = 0; i < result.size(); i++) {
                                String[] tmp = { Integer.toString(i), result.get(i) };
                                cursor.addRow(tmp);
                            }
                            suggestionAdapter.swapCursor(cursor);

                        }
                    }).execute(suggestion);
                    return true;
                }
            }
            return false;
        }
    });

    return true;
}

From source file:org.cdmckay.android.provider.MediaWikiProvider.java

private Cursor parseXmlSearch(String apiUrl, String search) {
    final MatrixCursor cursor = new MatrixCursor(SEARCH_COLUMN_NAMES);

    try {//from   ww  w  .jav a  2s . co m
        final OpenSearchHandler handler = new OpenSearchHandler();
        Xml.parse(search, handler);

        final List<OpenSearchHandler.Result> results = handler.getResults();
        for (OpenSearchHandler.Result result : results) {
            cursor.addRow(new Object[] { result.id, result.title, result.description, result.url });
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        throw new RuntimeException(e);
    }

    return cursor;
}

From source file:com.coinomi.wallet.ExchangeRatesProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    final long now = System.currentTimeMillis();

    final List<String> pathSegments = uri.getPathSegments();
    if (pathSegments.size() != 2) {
        throw new IllegalArgumentException("Unrecognized URI: " + uri);
    }/*from  w  w  w.j  av a2s  . com*/

    final boolean offline = uri.getQueryParameter(QUERY_PARAM_OFFLINE) != null;
    long lastUpdated;

    final String symbol;
    final boolean isLocalToCrypto;

    if (pathSegments.get(0).equals("to-crypto")) {
        isLocalToCrypto = true;
        symbol = pathSegments.get(1);
        lastUpdated = symbol.equals(lastLocalCurrency) ? localToCryptoLastUpdated : 0;
    } else if (pathSegments.get(0).equals("to-local")) {
        isLocalToCrypto = false;
        symbol = pathSegments.get(1);
        lastUpdated = symbol.equals(lastCryptoCurrency) ? cryptoToLocalLastUpdated : 0;
    } else {
        throw new IllegalArgumentException("Unrecognized URI path: " + uri);
    }

    if (!offline && (lastUpdated == 0 || now - lastUpdated > Constants.RATE_UPDATE_FREQ_MS)) {
        URL url;
        try {
            if (isLocalToCrypto) {
                url = new URL(String.format(TO_CRYPTO_URL, symbol));
            } else {
                url = new URL(String.format(TO_LOCAL_URL, symbol));
            }
        } catch (final MalformedURLException x) {
            throw new RuntimeException(x); // Should not happen
        }

        JSONObject newExchangeRatesJson = requestExchangeRatesJson(url);
        Map<String, ExchangeRate> newExchangeRates = parseExchangeRates(newExchangeRatesJson, symbol,
                isLocalToCrypto);

        if (newExchangeRates != null) {
            if (isLocalToCrypto) {
                localToCryptoRates = newExchangeRates;
                localToCryptoLastUpdated = now;
                lastLocalCurrency = symbol;
                config.setCachedExchangeRates(lastLocalCurrency, newExchangeRatesJson);
            } else {
                cryptoToLocalRates = newExchangeRates;
                cryptoToLocalLastUpdated = now;
                lastCryptoCurrency = symbol;
            }
        }
    }

    Map<String, ExchangeRate> exchangeRates = isLocalToCrypto ? localToCryptoRates : cryptoToLocalRates;

    if (exchangeRates == null)
        return null;

    final MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID, KEY_CURRENCY_ID, KEY_RATE_COIN,
            KEY_RATE_COIN_CODE, KEY_RATE_FIAT, KEY_RATE_FIAT_CODE, KEY_SOURCE });

    if (selection == null) {
        for (final Map.Entry<String, ExchangeRate> entry : exchangeRates.entrySet()) {
            final ExchangeRate exchangeRate = entry.getValue();
            addRow(cursor, exchangeRate);
        }
    } else if (selection.equals(KEY_CURRENCY_ID)) {
        final ExchangeRate exchangeRate = exchangeRates.get(selectionArgs[0]);
        if (exchangeRate != null) {
            addRow(cursor, exchangeRate);
        }
    }

    return cursor;
}