Example usage for android.support.v4.widget SimpleCursorAdapter SimpleCursorAdapter

List of usage examples for android.support.v4.widget SimpleCursorAdapter SimpleCursorAdapter

Introduction

In this page you can find the example usage for android.support.v4.widget SimpleCursorAdapter SimpleCursorAdapter.

Prototype

public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) 

Source Link

Document

Standard constructor.

Usage

From source file:cm.aptoide.pt.ApkInfo.java

/**
 *
 *///from  w w  w .  j a  v a2 s .c  om
private void loadApkVersions() {
    if (category.equals(Category.INFOXML)) {
        spinner = (Spinner) findViewById(R.id.spinnerMultiVersion);
        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, null,
                new String[] { "vername", "repo_id" }, new int[] { android.R.id.text1 },
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        adapter.setViewBinder(new ViewBinder() {

            @Override
            public boolean setViewValue(View textView, Cursor cursor, int position) {
                ((android.widget.TextView) textView)
                        .setText(getString(R.string.version) + " " + cursor.getString(position) + " - "
                                + RepoUtils.split(db.getServer(cursor.getLong(3), false).url));
                return true;
            }
        });
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (spinnerInstanciated) {
                    if (!download.isNull()) {
                        try {
                            serviceDownloadManager.callUnregisterDownloadObserver(viewApk.hashCode());
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                    loadElements(arg3);
                } else {
                    spinnerInstanciated = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });

        getSupportLoaderManager().initLoader(0, null, ApkInfo.this);

    }
}

From source file:uk.co.massimocarli.friendfence.location.FenceSessionListFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/*from w  w w.  ja va  2 s .  co  m*/
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addApi(Drive.API).addScope(Drive.SCOPE_FILE)
            .addScope(Drive.SCOPE_APPFOLDER).addConnectionCallbacks(mConnectionCallbacks)
            .addOnConnectionFailedListener(mOnConnectionFailedListener).build();
    mGoogleApiClient.connect();
    mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.fragment_session_item, null, FROM, TO, 0);
    mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int i) {
            if (R.id.fence_session_start_date == view.getId()) {
                // We have the date so we have to format it and show
                final Date startDate = mSessionCursorData.getStartDate();
                final TextView dateView = (TextView) view;
                dateView.setText(Conf.SIMPLE_DATE_FORMAT.format(startDate));
                return true;
            } else if (R.id.fence_session_distance == view.getId()) {
                final float distanceInMeters = mSessionCursorData.getTotalDistance();
                final TextView distanceView = (TextView) view;
                distanceView.setText(DistanceUtil.formatDistance(getActivity(), distanceInMeters));
                return true;
            }
            return false;
        }
    });
}

From source file:com.svpino.longhorn.activities.DashboardActivity.java

private void performSearch(String query) {
    this.stockListFragment.hideContextualActionBar();
    Cursor cursor = DataProvider.search(getApplicationContext(), query);

    if (this.searchDialog == null || !this.searchDialog.isShowing()) {
        this.searchDialog = new Dialog(this);
        this.searchDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.searchDialog.setContentView(R.layout.dialog);

        TextView messageTextView = (TextView) this.searchDialog.findViewById(R.id.messageTextView);
        TextView titleTextView = (TextView) this.searchDialog.findViewById(R.id.titleTextView);

        ListView listView = (ListView) this.searchDialog.findViewById(R.id.listView);

        if (cursor != null && cursor.getCount() > 0) {
            titleTextView.setText(String.format(getString(R.string.dialog_search_title), query));
            messageTextView.setVisibility(View.GONE);

            String[] from = new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1,
                    SearchManager.SUGGEST_COLUMN_TEXT_2, LonghornDatabase.KEY_EXCHANGE_SYMBOL };
            int[] to = new int[] { R.id.nameTextView, R.id.descriptionTextView, R.id.additionalTextView };

            SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.dialog_item,
                    cursor, from, to, 0);
            adapter.setViewBinder(new ViewBinder() {

                @Override//from   w  w w. ja  va 2 s .c  om
                public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

                    if (columnIndex == 0) {
                        ((View) view.getParent()).setTag(cursor.getString(columnIndex));
                    }

                    return false;
                }
            });

            listView.setAdapter(adapter);

            listView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                    Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
                    addStockToWatchList(cursor.getString(0));
                    DashboardActivity.this.searchDialog.dismiss();
                }
            });
        } else {
            titleTextView.setText(getString(R.string.dialog_search_empty_title));
            messageTextView.setText(String.format(getString(R.string.dialog_search_empty_message), query));
            messageTextView.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        }

        this.searchDialog.show();
    }
}

From source file:org.gnucash.android.ui.accounts.AddAccountFragment.java

private void loadParentAccountList() {
    String condition = DatabaseHelper.KEY_ROW_ID + "!=" + mSelectedAccountId;
    mCursor = mAccountsDbAdapter.fetchAccounts(condition);
    if (mCursor.getCount() <= 0) {
        final View view = getView();
        view.findViewById(R.id.layout_parent_account).setVisibility(View.GONE);
        view.findViewById(R.id.label_parent_account).setVisibility(View.GONE);
    }/*from   ww w .j ava2 s .  co m*/

    String[] from = new String[] { DatabaseHelper.KEY_NAME };
    int[] to = new int[] { android.R.id.text1 };
    mCursorAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_spinner_item, mCursor, from,
            to, 0);
    mCursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mParentAccountSpinner.setAdapter(mCursorAdapter);
}

From source file:org.gnucash.android.ui.transaction.TransactionFormFragment.java

/**
 * Initializes the transaction name field for autocompletion with existing transaction names in the database
 *///from   w w  w. j  a va2  s  .  c om
private void initTransactionNameAutocomplete() {
    final int[] to = new int[] { android.R.id.text1 };
    final String[] from = new String[] { DatabaseHelper.KEY_NAME };

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_dropdown_item_1line, null, from, to, 0);

    adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
        @Override
        public CharSequence convertToString(Cursor cursor) {
            final int colIndex = cursor.getColumnIndexOrThrow(DatabaseHelper.KEY_NAME);
            return cursor.getString(colIndex);
        }
    });

    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence name) {
            return mTransactionsDbAdapter.fetchTransactionsStartingWith(name.toString());
        }
    });

    mNameEditText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            mTransaction = mTransactionsDbAdapter.getTransaction(id);
            mTransaction.setUID(UUID.randomUUID().toString());
            mTransaction.setExported(false);
            mTransaction.setTime(System.currentTimeMillis());
            long accountId = ((TransactionsActivity) getSherlockActivity()).getCurrentAccountID();
            mTransaction.setAccountUID(mTransactionsDbAdapter.getAccountUID(accountId));
            initializeViewsWithTransaction();
        }
    });

    mNameEditText.setAdapter(adapter);
}

From source file:org.kiwix.kiwixmobile.ZimFileSelectActivity.java

protected void startQuery() {

    // Defines a list of columns to retrieve from the Cursor and load into an output row
    String[] mZimListColumns = { MediaStore.Files.FileColumns.TITLE, MediaStore.Files.FileColumns.DATA };

    // Defines a list of View IDs that will receive the Cursor columns for each row
    int[] mZimListItems = { android.R.id.text1, android.R.id.text2 };

    mCursorAdapter = new SimpleCursorAdapter(
            // The Context object
            ZimFileSelectActivity.this,
            // A layout in XML for one row in the ListView
            android.R.layout.simple_list_item_2,
            // The cursor, swapped later by cursorloader
            null,/*w  w  w . j av  a2  s  .  co  m*/
            // A string array of column names in the cursor
            mZimListColumns,
            // An integer array of view IDs in the row layout
            mZimListItems,
            // Flags for the Adapter
            Adapter.NO_SELECTION);

    getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}

From source file:nl.sogeti.android.gpstracker.actions.NameTrack.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //This activity hides itself, the TrackList activity switches it's visible state
    this.setVisible(false);
    paused = false;/*  w w w  .  j a  v a2 s .c  o m*/
    mTrackUri = this.getIntent().getData();
    mCurStartStationNameFilter = "";
    mCurEndStationNameFilter = "";

    getSupportLoaderManager().initLoader(STARTSTATIONCURSOR_LOADER, null, this);
    getSupportLoaderManager().initLoader(ENDSTATIONCURSOR_LOADER, null, this);

    String[] uiBindFrom = { Tracks.NAME };
    int[] uiBindTo = { android.R.id.text1 };

    mStartStationSimpleCursorAdapter = new SimpleCursorAdapter(this,
            android.R.layout.simple_dropdown_item_1line, null, uiBindFrom, uiBindTo, 0);

    mEndStationSimpleCursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line,
            null, uiBindFrom, uiBindTo, 0);

    // Set the CursorToStringConverter, to provide the labels for the
    // choices to be displayed in the AutoCompleteTextView.
    mStartStationSimpleCursorAdapter
            .setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
                public String convertToString(android.database.Cursor cursor) {
                    // Get the label for this row out of the "state" column
                    final int columnIndex = cursor.getColumnIndexOrThrow(Tracks.NAME);
                    final String str = cursor.getString(columnIndex);
                    return str;
                }
            });

    //TODO : Maybe I should have this in an external object I'd reuse instead of two anonymous objects ?
    mEndStationSimpleCursorAdapter
            .setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
                public String convertToString(android.database.Cursor cursor) {
                    // Get the label for this row out of the "state" column
                    final int columnIndex = cursor.getColumnIndexOrThrow(Tracks.NAME);
                    final String str = cursor.getString(columnIndex);
                    return str;
                }
            });

    //DO NOT BE TEMPTED, THE FOLLOWING CODE MAKE THE QUERY FROM THE UI THREAD I THINK, AND THIS IS BAD, VERY BAD !
    // Set the FilterQueryProvider, to run queries for choices
    // that match the specified input.
    /*mStartStationSimpleCursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
       // Search for states whose names begin with the specified letters.
       Cursor cursor = mDbHelper.getMatchingStates(
               (constraint != null ? constraint.toString() : null));
       return cursor;
        }
    });*/
}

From source file:se.chalmers.watchme.ui.MovieListFragment.java

/**
 * Set up adapter and set adapter.//from  w w  w  .j  av  a2s  .c  om
 */
private void setUpAdapter() {

    // Bind columns from the table Movies to items in the rows.
    String[] from = new String[] { MoviesTable.COLUMN_TITLE, MoviesTable.COLUMN_RATING, MoviesTable.COLUMN_DATE,
            MoviesTable.COLUMN_POSTER_SMALL };

    int[] to = new int[] { R.id.title, R.id.raiting, R.id.date, R.id.poster };

    getActivity().getSupportLoaderManager().initLoader(LOADER_ID, null, this);
    setAdapter(new SimpleCursorAdapter(getActivity(), R.layout.list_item_movie, null, from, to, 0));

    /**
     * Manipulate the shown date in list
     */
    getAdapter().setViewBinder(new ViewBinder() {

        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

            if (columnIndex == cursor.getColumnIndexOrThrow(MoviesTable.COLUMN_DATE)) {

                String dateString = cursor.getString(columnIndex);
                TextView textView = (TextView) view;
                Calendar date = Calendar.getInstance();
                date.setTimeInMillis(Long.parseLong(dateString));

                /*
                 * If the movie's release date is within a given threshold (fetched 
                 * from resource file), change the text color of the field. 
                 */
                int threshold = Integer.parseInt(getString(R.string.days_threshold));

                if (DateTimeUtils.isDateInInterval(date, threshold, TimeUnit.DAYS)) {
                    String color = getString(R.string.color_threshold);
                    textView.setTextColor(Color.parseColor(color));
                }
                /*
                 * Set to original color if not in threshold
                 */
                else {
                    textView.setTextColor(R.string.list_date_color);
                }

                // Format the date to relative form ("two days left")
                String formattedDate = DateTimeUtils.toHumanDate(date);
                textView.setText(formattedDate);

                return true;
            }

            /*
             * Handle rating bar conversion
             */
            else if (columnIndex == cursor.getColumnIndexOrThrow(MoviesTable.COLUMN_RATING)) {
                int rating = cursor.getInt(columnIndex);
                RatingBar bar = (RatingBar) view;
                bar.setRating(rating);

                return true;
            }

            /*
             * Handle poster images
             */

            else if (columnIndex == cursor.getColumnIndexOrThrow(MoviesTable.COLUMN_POSTER_SMALL)) {
                String smallImageUrl = cursor.getString(columnIndex);
                final ImageView imageView = (ImageView) view;

                if (smallImageUrl != null && !smallImageUrl.isEmpty()) {

                    // Fetch the image in an async task
                    imageTask = new ImageDownloadTask(new ImageDownloadTask.TaskActions() {

                        // When task is finished, set the resulting
                        // image on the poster view
                        public void onFinished(Bitmap image) {
                            if (image != null) {
                                ((ImageView) imageView).setImageBitmap(image);
                            }
                        }
                    });

                    imageTask.execute(new String[] { smallImageUrl });
                }

                return true;
            }

            return false;
        }
    });
}

From source file:com.esri.arcgisruntime.sample.findplace.MainActivity.java

/**
 * Sets up the POI SearchView. Uses MatrixCursor to show suggestions to the user as the user inputs text.
 *///w w w . j  a  v  a 2s. c o m
private void setupPoi() {

    mPoiSuggestParameters = new SuggestParameters();
    // filter categories for POI
    mPoiSuggestParameters.getCategories().add("POI");
    mPoiGeocodeParameters = new GeocodeParameters();
    // get all attributes
    mPoiGeocodeParameters.getResultAttributeNames().add("*");
    mPoiSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String address) {
            // if proximity SearchView text box is empty, use the device location
            if (mProximitySearchViewEmpty) {
                mPreferredSearchProximity = mLocationDisplay.getMapLocation();
                mProximitySearchView.setQuery("Using current location...", false);
            }
            // keep track of typed address
            mPoiAddress = address;
            // geocode typed address
            geoCodeTypedAddress(address);
            // clear focus from search views
            mPoiSearchView.clearFocus();
            mProximitySearchView.clearFocus();
            return true;
        }

        @Override
        public boolean onQueryTextChange(final String newText) {
            // as long as newText isn't empty, get suggestions from the locatorTask
            if (!newText.equals("")) {
                mPoiSuggestParameters.setSearchArea(mCurrentExtentGeometry);
                final ListenableFuture<List<SuggestResult>> suggestionsFuture = mLocatorTask
                        .suggestAsync(newText, mPoiSuggestParameters);
                suggestionsFuture.addDoneListener(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            // get the results of the async operation
                            List<SuggestResult> suggestResults = suggestionsFuture.get();

                            if (!suggestResults.isEmpty()) {
                                MatrixCursor suggestionsCursor = new MatrixCursor(mColumnNames);
                                int key = 0;
                                // add each poi_suggestion result to a new row
                                for (SuggestResult result : suggestResults) {
                                    suggestionsCursor.addRow(new Object[] { key++, result.getLabel() });
                                }
                                // define SimpleCursorAdapter
                                String[] cols = new String[] { COLUMN_NAME_ADDRESS };
                                int[] to = new int[] { R.id.suggestion_address };
                                final SimpleCursorAdapter suggestionAdapter = new SimpleCursorAdapter(
                                        MainActivity.this, R.layout.suggestion, suggestionsCursor, cols, to, 0);
                                mPoiSearchView.setSuggestionsAdapter(suggestionAdapter);
                                // handle a poi_suggestion being chosen
                                mPoiSearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
                                    @Override
                                    public boolean onSuggestionSelect(int position) {
                                        return false;
                                    }

                                    @Override
                                    public boolean onSuggestionClick(int position) {
                                        // get the selected row
                                        MatrixCursor selectedRow = (MatrixCursor) suggestionAdapter
                                                .getItem(position);
                                        // get the row's index
                                        int selectedCursorIndex = selectedRow
                                                .getColumnIndex(COLUMN_NAME_ADDRESS);
                                        // get the string from the row at index
                                        mPoiAddress = selectedRow.getString(selectedCursorIndex);
                                        mPoiSearchView.setQuery(mPoiAddress, true);
                                        return true;
                                    }
                                });
                            } else {
                                mPoiAddress = newText;
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "Geocode suggestion error: " + e.getMessage());
                        }
                    }
                });
            }
            return true;
        }
    });
}

From source file:de.hshannover.f4.trust.ironcontrol.view.list_activities.ListVendorMetadataActivity.java

private void setListAdapter() {
    String[] from = new String[] { VendorMetadata.COLUMN_NAME, VendorMetadata.COLUMN_CARDINALITY };
    int[] to = new int[] { R.id.tvLabel, R.id.tvInfo1 };
    switch (ACTIVE_VIEW) {
    case OVERVIEW:
        adapter = new SimpleCursorAdapter(this, R.layout.responses_list_row, null, from, to, 0);
        break;//from w  w w  .j  a  v a 2  s  .  c  o  m
    case ATTRIBUTES_VIEW:
        adapter = new SimpleCursorAdapter(this, R.layout.responses_list_row, null,
                new String[] { MetaAttributes.COLUMN_NAME }, new int[] { R.id.tvLabel }, 0);
        break;
    }
    super.setListAdapter(adapter);
}