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:net.olejon.mdapp.NotesEditActivity.java

private void getMedications() {
    try {//from  ww w  .jav  a  2s. co m
        int medicationsJsonArrayLength = mPatientMedicationsJsonArray.length();

        if (medicationsJsonArrayLength == 0) {
            mPatientMedicationsTextView.setVisibility(View.GONE);
        } else {
            mPatientMedicationsTextView.setVisibility(View.VISIBLE);

            final ArrayList<String> medicationsNamesArrayList = new ArrayList<>();
            final ArrayList<String> medicationsManufacturersArrayList = new ArrayList<>();

            final String[] medicationsNamesStringArrayList = new String[medicationsJsonArrayLength + 2];

            medicationsNamesStringArrayList[0] = getString(R.string.notes_edit_medications_dialog_interactions);
            medicationsNamesStringArrayList[1] = getString(R.string.notes_edit_medications_dialog_remove_all);

            for (int i = 0; i < medicationsJsonArrayLength; i++) {
                JSONObject medicationJsonObject = mPatientMedicationsJsonArray.getJSONObject(i);

                String name = medicationJsonObject.getString("name");
                String manufacturer = medicationJsonObject.getString("manufacturer");

                medicationsNamesArrayList.add(name);
                medicationsManufacturersArrayList.add(manufacturer);

                medicationsNamesStringArrayList[i + 2] = name;
            }

            String medicationsNames = "";

            for (int n = 0; n < medicationsNamesArrayList.size(); n++) {
                medicationsNames += medicationsNamesArrayList.get(n) + ", ";
            }

            medicationsNames = medicationsNames.replaceAll(", $", "");

            mPatientMedicationsTextView.setText(Html.fromHtml("<u>" + medicationsNames + "</u>"));

            mPatientMedicationsTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new MaterialDialog.Builder(mContext)
                            .title(getString(R.string.notes_edit_medications_dialog_title))
                            .items(medicationsNamesStringArrayList)
                            .itemsCallback(new MaterialDialog.ListCallback() {
                                @Override
                                public void onSelection(MaterialDialog materialDialog, View view, int i,
                                        CharSequence charSequence) {
                                    if (i == 0) {
                                        String medicationsInteractions = "";

                                        for (int n = 0; n < medicationsNamesArrayList.size(); n++) {
                                            medicationsInteractions += medicationsNamesArrayList.get(n)
                                                    .split(" ")[0] + " ";
                                        }

                                        medicationsInteractions = medicationsInteractions.trim();

                                        Intent intent = new Intent(mContext, InteractionsCardsActivity.class);
                                        intent.putExtra("search", medicationsInteractions);
                                        startActivity(intent);
                                    } else if (i == 1) {
                                        try {
                                            mPatientMedicationsJsonArray = new JSONArray("[]");

                                            getMedications();
                                        } catch (Exception e) {
                                            Log.e("NotesEditActivity", Log.getStackTraceString(e));
                                        }
                                    } else {
                                        int position = i - 2;

                                        String medicationName = medicationsNamesArrayList.get(position);
                                        String medicationManufacturer = medicationsManufacturersArrayList
                                                .get(position);

                                        SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext)
                                                .getReadableDatabase();

                                        String[] queryColumns = { SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID };
                                        Cursor cursor = sqLiteDatabase.query(
                                                SlDataSQLiteHelper.TABLE_MEDICATIONS, queryColumns,
                                                SlDataSQLiteHelper.MEDICATIONS_COLUMN_NAME + " = "
                                                        + mTools.sqe(medicationName) + " AND "
                                                        + SlDataSQLiteHelper.MEDICATIONS_COLUMN_MANUFACTURER
                                                        + " = " + mTools.sqe(medicationManufacturer),
                                                null, null, null, null);

                                        if (cursor.moveToFirst()) {
                                            long id = cursor.getLong(cursor.getColumnIndexOrThrow(
                                                    SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID));

                                            Intent intent = new Intent(mContext, MedicationActivity.class);

                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                                if (mTools.getDefaultSharedPreferencesBoolean(
                                                        "MEDICATION_MULTIPLE_DOCUMENTS"))
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                                                            | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
                                            }

                                            intent.putExtra("id", id);
                                            startActivity(intent);
                                        }

                                        cursor.close();
                                        sqLiteDatabase.close();
                                    }
                                }
                            }).itemColorRes(R.color.dark_blue).show();
                }
            });
        }
    } catch (Exception e) {
        Log.e("NotesEditActivity", Log.getStackTraceString(e));
    }
}

From source file:com.andrew.apolloMod.helpers.AddIdCursorLoader.java

@Override
public Cursor loadInBackground() {

    Cursor mediaCursor = getContext().getContentResolver().query(mUri, mProjection, mSelection, mSelectionArgs,
            mSortOrder);/*from  w  w  w  .  ja v  a  2  s  .c  o  m*/
    //Get cursor filled with Audio Id's
    String[] projection = new String[] { BaseColumns._ID, AlbumColumns.ALBUM };
    Uri uri = Audio.Albums.EXTERNAL_CONTENT_URI;
    String sortOrder = Audio.Albums.DEFAULT_SORT_ORDER;
    Cursor albumCursor = getContext().getContentResolver().query(uri, projection, null, null, sortOrder);

    //Matrix cursor to hold final data to be returned to calling context
    MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID, MediaColumns.TITLE,
            AudioColumns.ARTIST, AudioColumns.ALBUM, AudioColumns.ALBUM_ID });
    //Map data from Audio Id cursor to the ALbumName Colum
    ContentQueryMap mQueryMap = new ContentQueryMap(albumCursor, AlbumColumns.ALBUM, false, null);

    Map<String, ContentValues> data = mQueryMap.getRows();
    if (mediaCursor != null) {
        while (mediaCursor.moveToNext()) {
            String id = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(BaseColumns._ID));
            String title = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(MediaColumns.TITLE));
            String artist = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(AudioColumns.ARTIST));
            String album = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(AudioColumns.ALBUM));

            ContentValues tData = data.get(album);
            String albumid = (String) tData.get(BaseColumns._ID);
            cursor.addRow(new String[] { id, title, artist, album, albumid });
        }
        mediaCursor.close();
    }

    if (cursor != null) {
        // Ensure the cursor window is filled
        registerContentObserver(cursor, mObserver);
    }
    return cursor;
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
    setContentView(R.layout.track_list);

    AnalyticsUtils.sendPageViews(this, this.getLocalClassName() + "/create");

    ApiAdapterFactory.getApiAdapter().hideActionBar(this);

    Display display = getWindowManager().getDefaultDisplay();
    boolean devicesZ = display.getWidth() > 720 || display.getHeight() > 720;
    if (devicesZ) {
        // Disable the Keyboard help link
        View v = findViewById(R.id.help_keyboard_q);
        if (v != null)
            v.setVisibility(View.GONE);
        v = findViewById(R.id.help_keyboard_a);
        if (v != null)
            v.setVisibility(View.GONE);
    }/*  w  ww  . ja  v  a2 s  .  com*/
    trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, bindChangedCallback);

    SharedPreferences sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
    sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
    sharedPreferenceChangeListener.onSharedPreferenceChanged(sharedPreferences, null);

    trackController = new TrackController(this, trackRecordingServiceConnection, true, recordListener,
            stopListener);

    // START MOD
    ImageButton helpButton = (ImageButton) findViewById(R.id.listBtnBarHelp);
    if (helpButton != null)
        helpButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = IntentUtils.newIntent(TrackListActivity.this, HelpActivity.class);
                startActivity(intent);
            }
        });
    /*
     * Record = Pause and Stop managed by track controller ImageButton
     * recordButton = (ImageButton) findViewById(R.id.listBtnBarRecord);
     * recordButton.setOnClickListener(recordListener); ImageButton stopButton =
     * (ImageButton) findViewById(R.id.listBtnBarStop);
     * stopButton.setOnClickListener(stopListener);
     */
    ImageButton searchButton = (ImageButton) findViewById(R.id.listBtnBarSearch);
    if (searchButton != null)
        searchButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                onSearchRequested();
            }
        });
    ImageButton settingsButton = (ImageButton) findViewById(R.id.listBtnBarSettings);
    if (settingsButton != null)
        settingsButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = IntentUtils.newIntent(TrackListActivity.this, SettingsActivity.class);
                startActivity(intent);
            }
        });

    // END MOD
    listView = (ListView) findViewById(R.id.track_list);
    listView.setEmptyView(findViewById(R.id.track_list_empty_view));
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = IntentUtils.newIntent(TrackListActivity.this, TrackDetailActivity.class)
                    .putExtra(TrackDetailActivity.EXTRA_TRACK_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 idIndex = cursor.getColumnIndex(TracksColumns._ID);
            int iconIndex = cursor.getColumnIndex(TracksColumns.ICON);
            int nameIndex = cursor.getColumnIndex(TracksColumns.NAME);
            int categoryIndex = cursor.getColumnIndex(TracksColumns.CATEGORY);
            int totalTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME);
            int totalDistanceIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE);
            int startTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME);
            int descriptionIndex = cursor.getColumnIndex(TracksColumns.DESCRIPTION);

            boolean isRecording = cursor.getLong(idIndex) == recordingTrackId;
            int iconId = TrackIconUtils.getIconDrawable(cursor.getString(iconIndex));
            String name = cursor.getString(nameIndex);
            String totalTime = StringUtils.formatElapsedTime(cursor.getLong(totalTimeIndex));
            String totalDistance = StringUtils.formatDistance(TrackListActivity.this,
                    cursor.getDouble(totalDistanceIndex), metricUnits);
            long startTime = cursor.getLong(startTimeIndex);
            String startTimeDisplay = StringUtils.formatDateTime(context, startTime).equals(name) ? null
                    : StringUtils.formatRelativeDateTime(context, startTime);

            ListItemUtils.setListItem(TrackListActivity.this, view, isRecording, recordingTrackPaused, iconId,
                    R.string.icon_track, name, cursor.getString(categoryIndex), totalTime, totalDistance,
                    startTimeDisplay, cursor.getString(descriptionIndex));
        }
    };
    listView.setAdapter(resourceCursorAdapter);
    ApiAdapterFactory.getApiAdapter().configureListViewContextualMenu(this, listView,
            contextualActionModeCallback);

    getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
            return new CursorLoader(TrackListActivity.this, TracksColumns.CONTENT_URI, PROJECTION, null, null,
                    TracksColumns._ID + " DESC");
        }

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

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            resourceCursorAdapter.swapCursor(null);
        }
    });
    trackDataHub = TrackDataHub.newInstance(this);
    if (savedInstanceState != null) {
        startGps = savedInstanceState.getBoolean(START_GPS_KEY);
    } // Test repeated messaging
    if (!started)
        showStartupDialogs();
}

From source file:com.awrtechnologies.carbudgetsales.MainActivity.java

public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {// ww  w.  j a  v a  2  s  .c  o  m
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * @param threadId// w w w .  j av a2  s .co  m
 * @param lastTime
 * @return
 */
public static ArrayList<ECMessage> queryIMessageListAfter(long threadId, String lastTime) {
    ArrayList<ECMessage> al = null;
    Cursor cursor = null;
    StringBuffer sb = new StringBuffer();
    if (lastTime != null && !lastTime.equals("") && !lastTime.equals("0")) {
        sb.append(IMessageColumn.CREATE_DATE + " > ").append(lastTime);
    } else {
        sb.append("1=1");
    }
    sb.append(" and " + IMessageColumn.OWN_THREAD_ID + " = ").append(threadId);
    sb.append(" and  " + IMessageColumn.BOX_TYPE + " != 3");
    try {
        cursor = getInstance().sqliteDB().query(false, DatabaseHelper.TABLES_NAME_IM_MESSAGE, null,
                sb.toString(), null, null, null, IMessageColumn.RECEIVE_DATE + " asc", null);
        if (cursor != null) {
            if (cursor.getCount() == 0) {
                return null;
            }
            al = new ArrayList<ECMessage>();
            while (cursor.moveToNext()) {

                long id = cursor.getLong(cursor.getColumnIndex(IMessageColumn.ID));
                String sender = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.sender));
                String msgId = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_ID));
                long ownThreadId = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.OWN_THREAD_ID));
                long createDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.CREATE_DATE));
                long receiveDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.RECEIVE_DATE));
                String userData = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.USER_DATA));
                int read = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.READ_STATUS));
                int boxType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.BOX_TYPE));
                int msgType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_TYPE));
                int sendStatus = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.SEND_STATUS));

                ECMessage ecMessage = null;
                if (msgType == ECMessage.Type.TXT.ordinal()) {
                    String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
                    ecMessage = ECMessage.createECMessage(ECMessage.Type.TXT);
                    ECTextMessageBody textBody = new ECTextMessageBody(content);
                    ecMessage.setBody(textBody);
                } else {
                    /*
                    * String fileUrl =
                    * cursor.getString(cursor.getColumnIndexOrThrow
                    * (IMessageColumn.FILE_URL)); String fileLocalPath =
                    * cursor
                    * .getString(cursor.getColumnIndexOrThrow(IMessageColumn
                    * .FILE_PATH));
                    * 
                    * if (msgType == ECMessage.Type.VOICE.ordinal()) { int
                    * duration =
                    * cursor.getInt(cursor.getColumnIndexOrThrow(
                    * IMessageColumn.DURATION)); ECVoiceMessageBody
                    * voiceBody = new ECVoiceMessageBody(new
                    * File(fileLocalPath), 0);
                    * voiceBody.setRemoteUrl(fileUrl);
                    * ecMessage.setBody(voiceBody); ecMessage =
                    * ECMessage.createECMessage(ECMessage.Type.VOICE); }
                    * else if (msgType == ECMessage.Type.IMAGE.ordinal() ||
                    * msgType == ECMessage.Type.FILE.ordinal()) {
                    * ECFileMessageBody fileBody = new } else { continue; }
                    */
                }
                ecMessage.setId(id);
                ecMessage.setFrom(sender);
                ecMessage.setMsgId(msgId);
                ecMessage.setMsgTime(createDate);
                ecMessage.setUserData(userData);
                ecMessage.setDirection(getMessageDirect(boxType));
                al.add(0, ecMessage);
            }
        }
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }
    return al;
}

From source file:com.ezac.gliderlogs.FlightDetailActivity.java

public void addItemSpinner1() {
    Uri uri = FlightsContentProvider.CONTENT_URI_GLIDER;
    String[] projection = { GliderLogTables.G_REGISTRATION, GliderLogTables.G_CALLSIGN, GliderLogTables.G_SEATS,
            GliderLogTables.G_PRIVATE };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, "Registratie ASC");
    if (cursor != null) {
        cursor.moveToFirst();/*from w ww  .ja va  2 s. c o m*/
        // insert dummy item with no data as to avoid pre-selection
        GliderList.add("");
        GliderCall.add("");
        GliderSeatsList.add("");
        GliderPrivateList.add("");
        for (int i = 0; i < cursor.getCount(); i++) {
            GliderList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.G_REGISTRATION)));
            GliderCall.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.G_CALLSIGN)));
            GliderSeatsList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.G_SEATS)));
            GliderPrivateList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.G_PRIVATE)));
            cursor.moveToNext();
        }
        cursor.close();
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(FlightDetailActivity.this,
                android.R.layout.simple_spinner_item, GliderList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mRegiSpin.setAdapter(dataAdapter);
    }
}

From source file:com.ezac.gliderlogs.FlightDetailActivity.java

public void addItemSpinner2() {
    Uri uri = FlightsContentProvider.CONTENT_URI_MEMBER;
    String[] projection = { GliderLogTables.M_ID, GliderLogTables.M_2_NAME, GliderLogTables.M_3_NAME,
            GliderLogTables.M_1_NAME, GliderLogTables.M_INSTRUCTION };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, "Voornaam ASC");
    if (cursor != null) {
        cursor.moveToFirst();/*from ww w .  ja  v  a2s .  co  m*/
        // insert dummy item with no data as to avoid pre-selection
        MemberList.add("");
        //MemberTrainList.add("");
        MemberIndexList.add("");
        MemberInstrList.add("");
        for (int i = 0; i < cursor.getCount(); i++) {
            String tmp = cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.M_1_NAME)) + " "
                    + cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.M_2_NAME)) + " "
                    + cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.M_3_NAME));
            MemberList.add(tmp.replaceAll("\\s+", " "));
            MemberIndexList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.M_ID)));
            //      MemberTrainList.add(cursor.getString(cursor
            //            .getColumnIndexOrThrow(GliderLogTables.M_TRAIN)));
            MemberInstrList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.M_INSTRUCTION)));
            // some logic add as to deal with new members with dummy id
            if (Integer
                    .parseInt(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.M_ID))) >= ini_id) {
                ini_id = Integer.parseInt(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.M_ID)))
                        + 1;
                Log.d(TAG, "key " + ini_id);
            }
            cursor.moveToNext();
        }
        cursor.close();
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(FlightDetailActivity.this,
                android.R.layout.simple_spinner_item, MemberList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mPilotSpin.setAdapter(dataAdapter);
        mCoPilotSpin.setAdapter(dataAdapter);
    }
}

From source file:com.cpic.taylor.logistics.activity.HomeActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA) {
        path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/userIcon.jpg";
        if (!cameraUri.getPath().isEmpty()) {
            Bitmap temp = BitmapFactory.decodeFile(cameraUri.getPath());
            Bitmap bitmap = big(temp, 60, 60);
            ivIcon.setImageBitmap(bitmap);
            changeInfo(USER_ICON);/*from   ww  w. ja  v a  2s. c  om*/
        }

        // upLoadUserIcon(new File(Environment.getExternalStorageDirectory()
        // .getAbsolutePath() + "/usericon.PNG"));
    } else if (requestCode == PHOTO) {
        if (data != null) {
            Uri uri = data.getData();
            // uriContentProvider?sd?
            // decodeFile?
            // ContentResolver?
            ContentResolver cr = HomeActivity.this.getContentResolver();
            try {
                Bitmap b = MediaStore.Images.Media.getBitmap(cr, uri);
                Bitmap bitmap = big(b, 60, 60);
                bitmap.getByteCount();
                ivIcon.setImageBitmap(bitmap);
                // ?
                String[] proj = { MediaStore.Images.Media.DATA };
                // ?android???Android
                Cursor cursor = HomeActivity.this.managedQuery(uri, proj, null, null, null);
                // ? 
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                //  ????
                cursor.moveToFirst();
                // ???
                path = cursor.getString(column_index);
                changeInfo(USER_ICON);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } else if (requestCode == INFO_CAMERA) {
        path1 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/carInfo.jpg";
        Log.i("oye", "" + path1);
        if (!cameraUri.getPath().isEmpty()) {
            Bitmap temp = BitmapFactory.decodeFile(cameraUri.getPath());
            Bitmap bitmap = big(temp, 60, 60);
            ivCarInfo.setImageBitmap(bitmap);
            changeInfo(CAR_INFO);
        }
    } else if (requestCode == INFO_PHOTO) {
        if (data != null) {
            Uri uri = data.getData();
            // uriContentProvider?sd?
            // decodeFile?
            // ContentResolver?
            ContentResolver cr = HomeActivity.this.getContentResolver();
            try {
                Bitmap b = MediaStore.Images.Media.getBitmap(cr, uri);
                Bitmap bitmap = big(b, 60, 60);
                bitmap.getByteCount();
                ivCarInfo.setImageBitmap(bitmap);
                // ?
                String[] proj = { MediaStore.Images.Media.DATA };
                // ?android???Android
                Cursor cursor = HomeActivity.this.managedQuery(uri, proj, null, null, null);
                // ? 
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                //  ????
                cursor.moveToFirst();
                // ???
                path1 = cursor.getString(column_index);
                changeInfo(CAR_INFO);
                // Log.i("oye", path);
                // ?
                // upLoadUserIcon(new File(path));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

protected void sendClientPhotos(SyncContext context, ContentProvider clientDiffs, Object syncInfo,
        SyncResult syncResult) {//from  www. j  a  v a 2  s . co m
    Entry entry = new MediaEntry();

    GDataServiceClient client = getGDataServiceClient();
    String authToken = getAuthToken();
    ContentResolver cr = getContext().getContentResolver();
    final String account = getAccount();

    Cursor c = clientDiffs.query(Photos.CONTENT_URI, null /* all columns */, null /* no where */,
            null /* no where args */, null /* default sort order */);
    try {
        int personColumn = c.getColumnIndexOrThrow(Photos.PERSON_ID);
        int dataColumn = c.getColumnIndexOrThrow(Photos.DATA);
        int numRows = c.getCount();
        while (c.moveToNext()) {
            if (mSyncCanceled) {
                if (Config.LOGD)
                    Log.d(TAG, "stopping since the sync was canceled");
                break;
            }

            entry.clear();
            context.setStatusText("Updating, " + (numRows - 1) + " to go");

            cursorToBaseEntry(entry, account, c);
            String editUrl = entry.getEditUri();

            if (TextUtils.isEmpty(editUrl)) {
                if (Config.LOGD) {
                    Log.d(TAG, "skipping photo edit for unsynced contact");
                }
                continue;
            }

            // Send the request and receive the response
            InputStream inputStream = null;
            byte[] imageData = c.getBlob(dataColumn);
            if (imageData != null) {
                inputStream = new ByteArrayInputStream(imageData);
            }
            Uri photoUri = Uri.withAppendedPath(People.CONTENT_URI,
                    c.getString(personColumn) + "/" + Photos.CONTENT_DIRECTORY);
            try {
                if (inputStream != null) {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Updating photo " + entry.toString());
                    }
                    ++mPhotoUploads;
                    client.updateMediaEntry(editUrl, inputStream, IMAGE_MIME_TYPE, authToken);
                } else {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Deleting photo " + entry.toString());
                    }
                    client.deleteEntry(editUrl, authToken);
                }

                // Mark that this photo is no longer dirty. The next time we sync (which
                // should be soon), we will get the new version of the photo and whether
                // or not there is a new one to download (e.g. if we deleted our version
                // yet there is an evergreen version present).
                ContentValues values = new ContentValues();
                values.put(Photos.EXISTS_ON_SERVER, inputStream == null ? 0 : 1);
                values.put(Photos._SYNC_DIRTY, 0);
                if (cr.update(photoUri, values, null /* no where */, null /* no where args */) != 1) {
                    Log.e(TAG, "error updating photo " + photoUri + " with values " + values);
                    syncResult.stats.numParseExceptions++;
                } else {
                    syncResult.stats.numUpdates++;
                }
                continue;
            } catch (ParseException e) {
                Log.e(TAG, "parse error during update of " + ", skipping");
                syncResult.stats.numParseExceptions++;
            } catch (IOException e) {
                if (Config.LOGD) {
                    Log.d(TAG, "io error during update of " + entry.toString() + ", skipping");
                }
                syncResult.stats.numIoExceptions++;
            } catch (HttpException e) {
                switch (e.getStatusCode()) {
                case HttpException.SC_UNAUTHORIZED:
                    if (syncResult.stats.numAuthExceptions == 0) {
                        if (Config.LOGD) {
                            Log.d(TAG, "auth error during update of " + entry + ", skipping");
                        }
                    }
                    syncResult.stats.numAuthExceptions++;
                    try {
                        GoogleLoginServiceBlockingHelper.invalidateAuthToken(getContext(), authToken);
                    } catch (GoogleLoginServiceNotFoundException e1) {
                        if (Config.LOGD) {
                            Log.d(TAG, "could not invalidate auth token", e1);
                        }
                    }
                    return;

                case HttpException.SC_CONFLICT:
                    if (Config.LOGD) {
                        Log.d(TAG, "conflict detected during update of " + entry + ", skipping");
                    }
                    syncResult.stats.numConflictDetectedExceptions++;
                    break;
                case HttpException.SC_BAD_REQUEST:
                case HttpException.SC_FORBIDDEN:
                case HttpException.SC_NOT_FOUND:
                case HttpException.SC_INTERNAL_SERVER_ERROR:
                default:
                    if (Config.LOGD) {
                        Log.d(TAG, "error " + e.getMessage() + " during update of " + entry.toString()
                                + ", skipping");
                    }
                    syncResult.stats.numIoExceptions++;
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:app.view.chat.ChatActivity.java

/**
 * ??/*from ww  w.ja va2s  .c o  m*/
 *
 * @param uri
 */
private void sendFile(Uri uri) {
    String filePath = null;
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        filePath = uri.getPath();
    }
    File file = new File(filePath);
    if (file == null || !file.exists()) {
        Toast.makeText(getApplicationContext(), "?", Toast.LENGTH_SHORT).show();
        return;
    }
    if (file.length() > 10 * 1024 * 1024) {
        Toast.makeText(getApplicationContext(), "?10M", Toast.LENGTH_SHORT).show();
        return;
    }

    // ?
    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
    // ?chattype,??
    if (chatType == CHATTYPE_GROUP)
        message.setChatType(ChatType.GroupChat);

    message.setReceipt(toChatUsername);
    // add message body
    NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
    message.addBody(body);

    conversation.addMessage(message);
    listView.setAdapter(adapter);
    adapter.refresh();
    listView.setSelection(listView.getCount() - 1);
    setResult(RESULT_OK);
}