Example usage for android.database Cursor getColumnIndexOrThrow

List of usage examples for android.database Cursor getColumnIndexOrThrow

Introduction

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

Prototype

int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException;

Source Link

Document

Returns the zero-based index for the given column name, or throws IllegalArgumentException if the column doesn't exist.

Usage

From source file:com.navjagpal.fileshare.WebServer.java

private String getFolderListing() {
    /* Get list of folders */
    Cursor c = mContext.getContentResolver().query(FileSharingProvider.Folders.CONTENT_URI, null, null, null,
            null);//w w w.j  a  v  a  2 s . c  om
    int nameIndex = c.getColumnIndexOrThrow(FileSharingProvider.Folders.Columns.DISPLAY_NAME);
    int idIndex = c.getColumnIndexOrThrow(FileSharingProvider.Folders.Columns._ID);
    String s = "";
    while (c.moveToNext()) {
        String name = c.getString(nameIndex);
        int id = c.getInt(idIndex);
        s += folderToLink(name, id) + "<br/>";
    }
    c.close();
    return s;
}

From source file:com.demo.android.smsapp.activities.SMSChatActivity.java

private void getChatWithNumber() {
    try {//  w  ww .  j  ava2s.c  o  m
        Uri uri = Uri.parse("content://sms/");
        String[] columns = new String[] { "_id", "address", "person", "date", "body", "type" };
        Cursor cursor = getContentResolver().query(uri, columns, "address='" + number + "'", null, "date asc");
        cursor.moveToFirst();
        Log.e("total:", cursor.getCount() + "");
        String id, address, body, person, type, date;

        for (int i = 0; i < cursor.getCount(); i++) {

            address = cursor.getString(cursor.getColumnIndex("address"));
            body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
            person = cursor.getString(cursor.getColumnIndex("person"));
            type = cursor.getString(cursor.getColumnIndex("type"));
            date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
            id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));

            smsModels.add(SMSModel.getSMSModelObject(id, address, body, type, date));

            Log.e("readSMS", "Number:" + address + ",Person:" + person + ",Message: " + body + ",type:" + type
                    + ",date:" + date + ",id:" + id);

            cursor.moveToNext();
        }
    } catch (SQLiteException ex) {
        Log.e("SQLiteException", ex.getMessage());
    }
}

From source file:com.google.android.apps.mytracks.MarkerListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ImageButton backButton = (ImageButton) findViewById(R.id.listBtnBarBack);
    if (backButton != null)
        backButton.setOnClickListener(new OnClickListener() {
            @Override/*from   w ww  . j a v  a  2  s .  c o  m*/
            public void onClick(View v) {
                MarkerListActivity.this.finish();
            }
        });
    // listBtnBarSearch listBtnBarMarker

    ImageButton sButton = (ImageButton) findViewById(R.id.listBtnBarSearch);
    if (sButton != null)
        sButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ApiAdapterFactory.getApiAdapter().handleSearchMenuSelection(MarkerListActivity.this);
            }
        });

    ImageButton mButton = (ImageButton) findViewById(R.id.listBtnBarMarker);
    if (mButton != null)
        mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = IntentUtils.newIntent(MarkerListActivity.this, MarkerEditActivity.class)
                        .putExtra(MarkerEditActivity.EXTRA_TRACK_ID, trackId);
                startActivity(intent);
            }
        });
    trackId = getIntent().getLongExtra(EXTRA_TRACK_ID, -1L);
    if (trackId == -1L) {
        Log.d(TAG, "invalid track id");
        finish();
        return;
    }

    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

    getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);

    ListView listView = (ListView) findViewById(R.id.marker_list);
    listView.setEmptyView(findViewById(R.id.marker_list_empty));
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = IntentUtils.newIntent(MarkerListActivity.this, MarkerDetailActivity.class)
                    .putExtra(MarkerDetailActivity.EXTRA_MARKER_ID, id);
            startActivity(intent);
        }
    });
    resourceCursorAdapter = new ResourceCursorAdapter(this, R.layout.list_item, null, 0) {
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            int typeIndex = cursor.getColumnIndex(WaypointsColumns.TYPE);
            int nameIndex = cursor.getColumnIndex(WaypointsColumns.NAME);
            int categoryIndex = cursor.getColumnIndex(WaypointsColumns.CATEGORY);
            int timeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME);
            int descriptionIndex = cursor.getColumnIndex(WaypointsColumns.DESCRIPTION);

            boolean statistics = cursor.getInt(typeIndex) == Waypoint.TYPE_STATISTICS;
            int iconId = statistics ? R.drawable.yellow_pushpin : R.drawable.blue_pushpin;
            String category = statistics ? null : cursor.getString(categoryIndex);
            String description = statistics ? null : cursor.getString(descriptionIndex);
            long time = cursor.getLong(timeIndex);
            String startTime = time == 0L ? null
                    : StringUtils.formatRelativeDateTime(MarkerListActivity.this, time);

            ListItemUtils.setListItem(MarkerListActivity.this, view, false, true, iconId, R.string.icon_marker,
                    cursor.getString(nameIndex), category, null, null, startTime, description);
        }
    };
    listView.setAdapter(resourceCursorAdapter);
    ApiAdapterFactory.getApiAdapter().configureListViewContextualMenu(this, listView,
            contextualActionModeCallback);

    final long firstWaypointId = MyTracksProviderUtils.Factory.get(this).getFirstWaypointId(trackId);
    getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
            return new CursorLoader(MarkerListActivity.this, WaypointsColumns.CONTENT_URI, PROJECTION,
                    WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns._ID + "!=?",
                    new String[] { String.valueOf(trackId), String.valueOf(firstWaypointId) }, null);
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            resourceCursorAdapter.swapCursor(cursor);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            resourceCursorAdapter.swapCursor(null);
        }
    });
}

From source file:com.openerp.base.ir.Attachment.java

private String[] getFileName(Uri uri) {
    String[] file_info = null;//from ww w. ja  v  a  2s .  co  m
    String filename = "";
    String file_type = "";
    if (uri.getScheme().toString().compareTo("content") == 0) {
        Cursor cursor = mContext.getContentResolver().query(uri, null, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            filename = cursor.getString(column_index);

            File fl = new File(filename);
            filename = fl.getName();
        }
        file_type = mContext.getContentResolver().getType(uri);
    } else if (uri.getScheme().compareTo("file") == 0) {
        filename = uri.getLastPathSegment().toString();
        file_type = "file";
    } else {
        filename = filename + "_" + uri.getLastPathSegment();
        file_type = "file";
    }
    file_info = new String[] { filename, file_type };
    return file_info;
}

From source file:com.game.simple.Game3.java

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(self, contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();//from  w  w  w.  java2 s  . c o  m
    return cursor.getString(column_index);
}

From source file:org.ueu.uninet.it.IragarkiaBidali.java

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();//from  w  w w.  j a v a  2  s .  c om
        return cursor.getString(column_index);
    } else
        return null;
}

From source file:ca.mudar.mtlaucasou.BaseMapFragment.java

/**
 * Get the list of Placemarks from the database and return them as array to
 * be added as OverlayItems in the map.//www.  ja  v a2 s .  c  om
 * 
 * @return ArrayList of MarpMarkers
 */
protected ArrayList<MapMarker> fetchMapMarkers() {
    MapMarker mMapMarker;
    ArrayList<MapMarker> alLocations = new ArrayList<MapMarker>();

    Cursor cur = getActivity().getApplicationContext().getContentResolver()
            .query(mActivityHelper.getContentUri(indexSection), MAP_MARKER_PROJECTION, null, null, null);
    if (cur.moveToFirst()) {
        final int columnId = cur.getColumnIndexOrThrow(BaseColumns._ID);
        final int columnName = cur.getColumnIndexOrThrow(PlacemarkColumns.PLACEMARK_NAME);
        final int columnAddress = cur.getColumnIndexOrThrow(PlacemarkColumns.PLACEMARK_ADDRESS);
        final int columnGeoLat = cur.getColumnIndexOrThrow(PlacemarkColumns.PLACEMARK_GEO_LAT);
        final int columnGeoLng = cur.getColumnIndexOrThrow(PlacemarkColumns.PLACEMARK_GEO_LNG);

        do {
            mMapMarker = new MapMarker(cur.getInt(columnId), cur.getString(columnName),
                    cur.getString(columnAddress), cur.getDouble(columnGeoLat), cur.getDouble(columnGeoLng));
            alLocations.add(mMapMarker);

        } while (cur.moveToNext());
    }
    /**
     * Note: using startManagingCursor() crashed the application when
     * running on Honeycomb! So we don't manage the cursor and close it
     * manually here.
     */
    cur.close();

    return alLocations;
}

From source file:ca.ualberta.app.activity.CreateAnswerActivity.java

/**
 * function that user to get the image path
 * /*from  ww  w.j a  v a  2 s. c o  m*/
 * @param context
 *            the context
 * @param imageFileUri
 *            the imageFileUri that contains the URL of the image
 * @return return the imagePath of the image
 */
private String getPath(Context context, Uri imageFileUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    String result = null;

    CursorLoader cursorLoader = new CursorLoader(context, imageFileUri, proj, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();

    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
    }
    return result;
}

From source file:com.winsuk.pebbletype.WatchCommunication.java

private void sendThreadList(Context context) {
    Cursor msgCursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null,
            null);// w ww  . ja  va  2s . c o m
    Activity act = new Activity();
    act.startManagingCursor(msgCursor);
    ArrayList<SMSThread> threads = new ArrayList<SMSThread>();

    if (msgCursor.moveToFirst()) {
        for (int i = 0; i < msgCursor.getCount(); i++) {
            int thread_id = msgCursor.getInt(msgCursor.getColumnIndexOrThrow("thread_id"));
            SMSThread th = null;
            for (int t = 0; t < threads.size(); t++) {
                SMSThread existingTh = threads.get(t);
                if (existingTh.thread_id == thread_id) {
                    th = existingTh;
                }
            }

            if (th == null) {
                String address = msgCursor.getString(msgCursor.getColumnIndexOrThrow("address")).toString();
                String name = "";

                Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
                Cursor contactCursor = context.getContentResolver().query(uri,
                        new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
                if (contactCursor.moveToFirst()) {
                    name = contactCursor.getString(contactCursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
                    contactCursor.close();
                }

                th = new SMSThread();
                th.thread_id = thread_id;
                th.address = address;
                th.name = name;
                //th.messages = new ArrayList<String>();
                threads.add(th);
            }

            /* TODO: this line is causing crashes on select few devices
            String body = msgCursor.getString(msgCursor.getColumnIndexOrThrow("body")).toString();
            if (th.messages.size() < 5) {
               th.messages.add(body);
            }
            */

            msgCursor.moveToNext();
        }
    }
    msgCursor.close();

    int limit = (threads.size() <= THREAD_LIMIT ? threads.size() : THREAD_LIMIT);
    String output = "";

    if (limit > 0) {
        // Calculate how many characters names can take up
        int availibleCharacters = 120;
        for (int i = 0; i < limit; i++) {
            availibleCharacters -= threads.get(i).address.length();
            availibleCharacters -= 2; //for ; and \n
        }
        int maxNameLength = availibleCharacters / limit - 3;

        for (int i = 0; i < limit; i++) {
            SMSThread thread = threads.get(i);

            String name = "";
            if (thread.name.length() < maxNameLength) {
                name = thread.name;
            } else {
                name = thread.name.substring(0, maxNameLength - 1);
                name += "";
            }

            output = output + thread.address + ";" + name + "\n";

            /* List messages
            for (int ii = 0; ii < thread.messages.size(); ii++) {
               output = output + thread.messages.get(ii) + "\n";
            }*/
        }
    }
    PebbleDictionary data = new PebbleDictionary();
    data.addString(KEY_THREAD_LIST, output);
    PebbleKit.sendDataToPebble(context, PEBBLE_APP_UUID, data);
}

From source file:com.google.plus.samples.photohunt.ThemeViewActivity.java

@Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
    super.onActivityResult(requestCode, responseCode, intent);

    switch (requestCode) {
    case REQUEST_CODE_IMAGE_CAPTURE:
        if (responseCode == RESULT_OK) {
            sendImage(Intents.getPhotoImageUri().getPath(), mTheme.id);
        }// w  ww .  j  a va 2  s .  com
        break;
    case REQUEST_CODE_IMAGE_SELECT:
        if (responseCode == RESULT_OK && intent != null && intent.getData() != null) {
            String imageUriString = intent.getDataString();
            Uri imageUri = intent.getData();

            if ("content".equals(imageUri.getScheme())) {
                Cursor cursor = getContentResolver().query(imageUri, new String[] { Media.DATA }, null, null,
                        null);
                int column_index = cursor.getColumnIndexOrThrow(Media.DATA);
                cursor.moveToFirst();

                imageUriString = cursor.getString(column_index);
            }

            sendImage(imageUriString, mTheme.id);
        }
        break;
    }
}