Example usage for android.content ContentResolver insert

List of usage examples for android.content ContentResolver insert

Introduction

In this page you can find the example usage for android.content ContentResolver insert.

Prototype

public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values) 

Source Link

Document

Inserts a row into a table at the given URL.

Usage

From source file:org.inftel.ssa.mobile.ui.fragments.ProjectEditFragment.java

public void saveProject() throws ParseException {
    Log.d(getClass().getSimpleName(), "Save Project");

    ContentResolver cr = mActivity.getContentResolver();
    ContentValues values = new ContentValues();

    values.put(Projects.PROJECT_NAME, title.getText().toString());
    values.put(Projects.PROJECT_SUMMARY, summary.getText().toString());
    values.put(Projects.PROJECT_DESCRIPTION, description.getText().toString());
    values.put(Projects.PROJECT_STARTED, secureEpochDate(started.getText().toString()));
    values.put(Projects.PROJECT_CLOSE, secureEpochDate(finished.getText().toString()));
    values.put(Projects.PROJECT_COMPANY, company.getText().toString());
    values.put(Projects.PROJECT_LICENSE, license.getText().toString());

    try {// w ww.ja v  a2  s  .c o m
        if (mState == STATE_INSERT) {
            values.put(Projects.SYNC_STATUS, SsaContract.STATUS_CREATED);
            values.put(Projects.PROJECT_OPENED, Long.toString(System.currentTimeMillis()));
            cr.insert(Projects.CONTENT_URI, values);
        } else {
            values.put(Projects.SYNC_STATUS, SsaContract.STATUS_DIRTY);
            cr.update(mContentUri, values, null, null);
        }
    } catch (NullPointerException e) {
        Log.e(getClass().getSimpleName(), e.getMessage());
    }

}

From source file:net.niyonkuru.koodroid.service.SessionService.java

private void login(String email, String password) throws IOException {
    try {/*from  w  w w  .j a  v a  2  s. c  o  m*/
        mPostRequest = new HttpPost(new URI(Config.LOGIN_URL));
    } catch (URISyntaxException e) {
        throw new ServiceException(e.getMessage());
    }

    List<NameValuePair> formData = buildFormData(email, password, getString(R.string.locale));
    try {
        /* fill the login request with form values */
        mPostRequest.setEntity(new UrlEncodedFormEntity(formData, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException(e.getMessage());
    }

    Document doc;

    try {
        final HttpResponse response = mHttpClient.execute(mPostRequest);
        final Integer status = response.getStatusLine().getStatusCode();

        /* scumbag server did not return a 200 code */
        if (status != HttpStatus.SC_OK)
            throw new ServiceException(status.toString());

        HttpEntity entity = response.getEntity();

        doc = Jsoup.parse(EntityUtils.toString(response.getEntity()));

        if (entity != null) {
            entity.consumeContent();
        }
    } catch (UnknownHostException e) {
        throw new ServiceException(e.getMessage());
    } catch (ConnectTimeoutException e) {
        throw new ServiceException(getString(R.string.error_connection_timeout));
    } catch (ClientProtocolException e) {
        throw new ServiceException(e.getMessage());
    } catch (ParseException e) {
        throw new ServiceException(e.getMessage());
    } catch (SocketTimeoutException e) {
        throw new ServiceException(getString(R.string.error_response_timeout));
    } catch (IOException e) {
        // This could be caused by closing the httpclient connection manager
        throw new ServiceException(e.getMessage());
    }

    final Resources resources = getResources();
    final ContentResolver resolver = getContentResolver();

    /* this is a new user logging in */
    if (!email.equalsIgnoreCase(mSettings.email())) {
        /* clear old preferences */
        resolver.delete(Settings.CONTENT_URI, null, null);
    }

    try {
        new SubscribersHandler(resources, email).parseAndApply(doc, resolver);
        new LinksHandler(resources).parseAndApply(doc, resolver);

        ContentValues values = new ContentValues(3);
        values.put(Settings.EMAIL, email);
        values.put(Settings.PASSWORD, password);
        values.put(Settings.LAST_LOGIN, System.currentTimeMillis());

        resolver.insert(Settings.CONTENT_URI, values);

        new BackupManager(this).dataChanged();

    } catch (HandlerException e) {
        /* check if these errors could be caused by invalid pages */
        new ErrorHandler(resources).parseAndThrow(doc);
        throw e;
    }
}

From source file:no.uka.findmyapp.android.rest.client.RestProcessor.java

/**
 * Send to content provider./* www  .  j av a  2 s . c o  m*/
 *
 * @param uri the uri
 * @param object the object
 * @param returnType the return type
 */
private void sendToContentProvider(Uri uri, Serializable object, String returnType) {
    Log.v(debug, "sendToContentProvider: serializable object " + object.getClass().getName());

    ContentResolver cr = mContext.getContentResolver();

    if (object instanceof List) {

        Class theClass = null;
        try {
            theClass = Class.forName(returnType);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        List<ContentValues> list = ContentHelper.getContentValuesList(object, theClass);
        Log.v(debug, "parsing contentvalue array");
        ContentValues[] cva = new ContentValues[list.size()];
        for (ContentValues cv : list) {
            cva[list.indexOf(cv)] = cv;
        }
        Log.v(debug, cva.toString());
        cr.bulkInsert(UkaEventContract.EVENT_CONTENT_URI, cva);
    } else {
        ContentValues cv = new ContentValues(ContentHelper.getContentValues(object));
        cr.insert(uri, cv);
    }
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Insert a form into collect. Returns the URI of the inserted form. Note that
 * form version is not passed in with the content values and is likely
 * therefore not considered. (Not sure exactly how collect checks this.)
 * <p>//  ww w .  j  av a 2 s  .c om
 * Precondition: the form should not exist in Collect before this call is
 * made. In other words, the a query made on the form should return no
 * results.
 *
 * @param resolver
 *          the ContentResolver of the calling activity
 * @param formFilePath
 *          the filePath to the form
 * @param displayName
 *          the displayName of the form
 * @param formId
 *          the id of the form
 * @return the result of the insert call, likely the URI of the resulting
 *         form. If the form was not first deleted there could be a problem
 */
private static Uri insertFormIntoCollect(ContentResolver resolver, String formFilePath, String displayName,
        String formId) {
    ContentValues insertValues = new ContentValues();
    insertValues.put(COLLECT_KEY_FORM_FILE_PATH, formFilePath);
    insertValues.put(COLLECT_KEY_DISPLAY_NAME, displayName);
    insertValues.put(COLLECT_KEY_JR_FORM_ID, formId);
    return resolver.insert(CONTENT_FORM_URI, insertValues);
}

From source file:idea.ruan.oksun.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*  w  w w .j  ava 2  s.c  om*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {

    ContentResolver contentResolver = mContext.getContentResolver();

    Uri locationTableUri = WeatherContract.LocationEntry.CONTENT_URI;

    long locationId;
    Cursor c = contentResolver.query(locationTableUri, new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_CITY_NAME + " = ?", new String[] { cityName }, null);
    if (c.moveToFirst()) {

        int i = c.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = c.getLong(i);

    } else {

        ContentValues cv = new ContentValues();

        cv.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        cv.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        locationId = ContentUris.parseId(contentResolver.insert(locationTableUri, cv));

    }

    c.close();

    return locationId;
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Insert the values existing in the file specified by
 * {@link DATA_FILE_PATH_AND_NAME} into the form specified by params.
 * <p>// www . j a  va2s .  c om
 * If the display name is not defined in the {@code params} parameter then the
 * string resource is used.
 * <p>
 * The inserted row is marked as INCOMPLETE.
 * <p>
 * PRECONDITION: in order to be populated with data, the data file containing
 * the row's data must have been written, most likely by calling
 * writeRowDataToBeEdited().
 * <p>
 * PRECONDITION: previous instances should already have been deleted by now,
 * or the passed in file names should be uniqued by adding timestamps, or
 * something.
 *
 * @param params
 *          the identifying parameters for the form. Should be the same object
 *          used to write the instance file.
 * @param rowNum
 *          the row number of the row being edited
 * @param resolver
 *          the ContentResolver of the activity making the request.
 * @return
 */
/*
 * This is based on the code at: http://code.google.com/p/opendatakit/source/
 * browse/src/org/odk/collect/android/tasks/SaveToDiskTask.java?repo=collect
 * in the method updateInstanceDatabase().
 */
private static Uri getUriForCollectInstanceForRowData(Context context, String appName, String tableId,
        CollectFormParameters params, String rowId, boolean shouldUpdate) {

    String instanceFilePath = getEditRowFormFile(appName, tableId, rowId).getAbsolutePath();

    ContentValues values = new ContentValues();
    // First we need to fill the values with various little things.
    values.put(COLLECT_KEY_STATUS, COLLECT_KEY_STATUS_INCOMPLETE);
    values.put(COLLECT_KEY_CAN_EDIT_WHEN_COMPLETE, Boolean.toString(true));
    values.put(COLLECT_KEY_INSTANCE_FILE_PATH, instanceFilePath);
    values.put(COLLECT_KEY_JR_FORM_ID, params.getFormId());
    values.put(COLLECT_KEY_DISPLAY_NAME,
            params.getRowDisplayName() + "_" + WebUtils.get().iso8601Date(new Date()));
    // only add the version if it exists (ie not null)
    if (params.getFormVersion() != null) {
        values.put(COLLECT_KEY_JR_VERSION, params.getFormVersion());
    }

    ContentResolver resolver = context.getContentResolver();
    Uri uriOfForm;
    if (shouldUpdate) {
        int count = resolver.update(CONTENT_INSTANCE_URI, values, COLLECT_KEY_INSTANCE_FILE_PATH + "=?",
                new String[] { instanceFilePath });
        if (count == 0) {
            uriOfForm = resolver.insert(CONTENT_INSTANCE_URI, values);
        } else {
            Cursor c = null;
            try {
                c = resolver.query(CONTENT_INSTANCE_URI, null, COLLECT_KEY_INSTANCE_FILE_PATH + "=?",
                        new String[] { instanceFilePath }, COLLECT_INSTANCE_ORDER_BY);

                if (c.moveToFirst()) {
                    // we got a result, meaning that the form exists in collect.
                    // so we just need to set the URI.
                    int collectInstanceKey; // this is the primary key of the form in
                    // Collect's
                    // database.
                    collectInstanceKey = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                            c.getColumnIndexOrThrow(BaseColumns._ID));
                    uriOfForm = (Uri.parse(CONTENT_INSTANCE_URI + "/" + collectInstanceKey));
                    c.close();
                } else {
                    c.close();
                    throw new IllegalStateException("it was updated we should have found the record!");
                }
            } finally {
                if (c != null && !c.isClosed()) {
                    c.close();
                }
            }
        }
    } else {
        // now we want to get the uri for the insertion.
        uriOfForm = resolver.insert(CONTENT_INSTANCE_URI, values);
    }
    return uriOfForm;
}

From source file:org.ohmage.activity.SurveyActivity.java

private void storeResponse() {

    //finalize photos
    for (int i = 0; i < mSurveyElements.size(); i++) {
        if (mSurveyElements.get(i) instanceof PhotoPrompt) {
            PhotoPrompt photoPrompt = (PhotoPrompt) mSurveyElements.get(i);
            final String uuid = (String) photoPrompt.getResponseObject();

            if (photoPrompt.isDisplayed() && !photoPrompt.isSkipped()) {
                File[] files = Campaign.getCampaignImageDir(this, mCampaignUrn).listFiles(new FilenameFilter() {

                    @Override//from   w  w  w. jav a  2  s .c  o m
                    public boolean accept(File dir, String filename) {
                        if (filename.contains("temp" + uuid)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });

                for (File f : files) {
                    f.renameTo(new File(Campaign.getCampaignImageDir(this, mCampaignUrn), uuid + ".jpg"));

                    // TODO: add thumbnail generation, oddly enough as a png
                }
            }
        }
    }

    SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
    String username = helper.getUsername();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar now = Calendar.getInstance();
    String date = dateFormat.format(now.getTime());
    long time = now.getTimeInMillis();
    String timezone = TimeZone.getDefault().getID();

    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (loc == null || System.currentTimeMillis() - loc.getTime() > SurveyGeotagService.LOCATION_STALENESS_LIMIT
            || loc.getAccuracy() > SurveyGeotagService.LOCATION_ACCURACY_THRESHOLD) {
        Log.w(TAG, "gps provider disabled or location stale or inaccurate");
        loc = null;
    }

    String surveyId = mSurveyId;

    //get launch context from trigger glue
    JSONObject surveyLaunchContextJson = new JSONObject();
    try {
        surveyLaunchContextJson.put("launch_time", mLaunchTime);
        surveyLaunchContextJson.put("active_triggers",
                TriggerFramework.getActiveTriggerInfo(this, mCampaignUrn, mSurveyTitle));
    } catch (JSONException e) {
        Log.e(TAG, "JSONException when trying to generate survey launch context json", e);
        throw new RuntimeException(e);
    }
    String surveyLaunchContext = surveyLaunchContextJson.toString();

    JSONArray responseJson = new JSONArray();
    JSONArray repeatableSetResponseJson = new JSONArray();
    JSONArray iterationResponseJson = new JSONArray();
    JSONObject itemJson = null;
    boolean inRepeatableSet = false;

    for (int i = 0; i < mSurveyElements.size(); i++) {
        if (mSurveyElements.get(i) instanceof Prompt) {
            if (!inRepeatableSet) {
                itemJson = new JSONObject();
                try {
                    itemJson.put("prompt_id", ((AbstractPrompt) mSurveyElements.get(i)).getId());
                    itemJson.put("value", ((AbstractPrompt) mSurveyElements.get(i)).getResponseObject());
                    Object extras = ((AbstractPrompt) mSurveyElements.get(i)).getExtrasObject();
                    if (extras != null) {
                        // as of now we don't actually have "extras" we only have "custom_choices" for the custom types
                        // so this is currently only used by single_choice_custom and multi_choice_custom
                        itemJson.put("custom_choices", extras);
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException when trying to generate response json", e);
                    throw new RuntimeException(e);
                }
                responseJson.put(itemJson);
            } else {
                JSONObject subItemJson = new JSONObject();
                try {
                    subItemJson.put("prompt_id", ((AbstractPrompt) mSurveyElements.get(i)).getId());
                    subItemJson.put("value", ((AbstractPrompt) mSurveyElements.get(i)).getResponseObject());
                    Object extras = ((AbstractPrompt) mSurveyElements.get(i)).getExtrasObject();
                    if (extras != null) {
                        // as of now we don't actually have "extras" we only have "custom_choices" for the custom types
                        // so this is currently only used by single_choice_custom and multi_choice_custom
                        subItemJson.put("custom_choices", extras);
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException when trying to generate response json", e);
                    throw new RuntimeException(e);
                }
                iterationResponseJson.put(subItemJson);
            }
        } else if (mSurveyElements.get(i) instanceof RepeatableSetHeader) {
            inRepeatableSet = true;
            if (i != 0 && (mSurveyElements.get(i - 1) instanceof RepeatableSetTerminator)
                    && ((RepeatableSetHeader) mSurveyElements.get(i)).getId()
                            .equals(((RepeatableSetTerminator) mSurveyElements.get(i - 1)).getId())) {
                //continue existing set
                iterationResponseJson = new JSONArray();
            } else {
                //start new set
                itemJson = new JSONObject();
                try {
                    itemJson.put("repeatable_set_id", ((RepeatableSetHeader) mSurveyElements.get(i)).getId());
                    itemJson.put("skipped", "false");
                    itemJson.put("not_displayed",
                            ((RepeatableSetHeader) mSurveyElements.get(i)).isDisplayed() ? "false" : "true");
                    repeatableSetResponseJson = new JSONArray();
                    iterationResponseJson = new JSONArray();
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException when trying to generate response json", e);
                    throw new RuntimeException(e);
                }
            }
        } else if (mSurveyElements.get(i) instanceof RepeatableSetTerminator) {
            inRepeatableSet = false;
            repeatableSetResponseJson.put(iterationResponseJson);
            try {
                itemJson.put("responses", repeatableSetResponseJson);
            } catch (JSONException e) {
                Log.e(TAG, "JSONException when trying to generate response json", e);
                throw new RuntimeException(e);
            }
            if (!(i + 1 < mSurveyElements.size() && (mSurveyElements.get(i + 1) instanceof RepeatableSetHeader)
                    && ((RepeatableSetHeader) mSurveyElements.get(i + 1)).getId()
                            .equals(((RepeatableSetTerminator) mSurveyElements.get(i)).getId()))) {
                responseJson.put(itemJson);
            }
        }
    }
    String response = responseJson.toString();

    // insert the response, which indirectly populates the prompt response tables, etc.
    Response candidate = new Response();

    candidate.campaignUrn = mCampaignUrn;
    candidate.username = username;
    candidate.date = date;
    candidate.time = time;
    candidate.timezone = timezone;
    candidate.surveyId = surveyId;
    candidate.surveyLaunchContext = surveyLaunchContext;
    candidate.response = response;
    candidate.status = Response.STATUS_STANDBY;

    if (loc != null) {
        candidate.locationStatus = SurveyGeotagService.LOCATION_VALID;
        candidate.locationLatitude = loc.getLatitude();
        candidate.locationLongitude = loc.getLongitude();
        candidate.locationProvider = loc.getProvider();
        candidate.locationAccuracy = loc.getAccuracy();
        candidate.locationTime = loc.getTime();
    } else {
        candidate.locationStatus = SurveyGeotagService.LOCATION_UNAVAILABLE;
        candidate.locationLatitude = -1;
        candidate.locationLongitude = -1;
        candidate.locationProvider = null;
        candidate.locationAccuracy = -1;
        candidate.locationTime = -1;
        candidate.status = Response.STATUS_WAITING_FOR_LOCATION;
    }

    ContentResolver cr = getContentResolver();
    cr.insert(Responses.CONTENT_URI, candidate.toCV());

    // create an intent and broadcast it to any interested receivers
    Intent i = new Intent("org.ohmage.SURVEY_COMPLETE");

    i.putExtra(Responses.CAMPAIGN_URN, mCampaignUrn);
    i.putExtra(Responses.RESPONSE_USERNAME, username);
    i.putExtra(Responses.RESPONSE_DATE, date);
    i.putExtra(Responses.RESPONSE_TIME, time);
    i.putExtra(Responses.RESPONSE_TIMEZONE, timezone);

    if (loc != null) {
        i.putExtra(Responses.RESPONSE_LOCATION_STATUS, SurveyGeotagService.LOCATION_VALID);
        i.putExtra(Responses.RESPONSE_LOCATION_LATITUDE, loc.getLatitude());
        i.putExtra(Responses.RESPONSE_LOCATION_LONGITUDE, loc.getLongitude());
        i.putExtra(Responses.RESPONSE_LOCATION_PROVIDER, loc.getProvider());
        i.putExtra(Responses.RESPONSE_LOCATION_ACCURACY, loc.getAccuracy());
        i.putExtra(Responses.RESPONSE_LOCATION_TIME, loc.getTime());
    } else {
        i.putExtra(Responses.RESPONSE_LOCATION_STATUS, SurveyGeotagService.LOCATION_UNAVAILABLE);
        i.putExtra(Responses.RESPONSE_STATUS, Response.STATUS_WAITING_FOR_LOCATION);
    }

    i.putExtra(Responses.SURVEY_ID, surveyId);
    i.putExtra(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT, surveyLaunchContext);
    i.putExtra(Responses.RESPONSE_JSON, response);

    this.sendBroadcast(i);
}

From source file:com.prashantpal.sunshine.app.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*from w  ww.j a v a2 s  .com*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    long locationId;
    ContentResolver resolver = mContext.getContentResolver();
    Cursor cursor = resolver.query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", new String[] { locationSetting },
            null);
    if (cursor.moveToFirst()) {
        int locationIdIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = cursor.getLong(locationIdIndex);
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        Uri uri = resolver.insert(WeatherContract.LocationEntry.CONTENT_URI, contentValues);
        locationId = ContentUris.parseId(uri);
    }
    cursor.close();
    // Otherwise, insert it using the content resolver and the base URI
    return locationId;
}

From source file:com.dwdesign.tweetings.fragment.StatusFragment.java

@SuppressLint({ "NewApi", "NewApi", "NewApi" })
@Override/*from   w  w  w .  ja v a2 s.  com*/
public boolean onMenuItemClick(final MenuItem item) {
    if (mStatus == null)
        return false;
    final String text_plain = mStatus.text_plain;
    final String screen_name = mStatus.screen_name;
    final String name = mStatus.name;
    switch (item.getItemId()) {
    case MENU_SHARE: {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "@" + mStatus.screen_name + ": " + text_plain);
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
        break;
    }
    case MENU_RETWEET: {
        if (isMyRetweet(mStatus)) {
            mService.destroyStatus(mAccountId, mStatus.retweet_id);
        } else {
            final long id_to_retweet = mStatus.is_retweet && mStatus.retweet_id > 0 ? mStatus.retweet_id
                    : mStatus.status_id;
            mService.retweetStatus(mAccountId, id_to_retweet);
        }
        break;
    }
    case MENU_TRANSLATE: {
        translate(mStatus);
        break;
    }
    case MENU_QUOTE_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, mStatusId);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, name);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), screen_name, text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_QUOTE: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), screen_name, text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_ADD_TO_BUFFER: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        bundle.putBoolean(INTENT_KEY_IS_BUFFER, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), screen_name, text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        final List<String> mentions = new Extractor().extractMentionedScreennames(text_plain);
        mentions.remove(screen_name);
        mentions.add(0, screen_name);
        bundle.putStringArray(INTENT_KEY_MENTIONS, mentions.toArray(new String[mentions.size()]));
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, mStatusId);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_TWEET, text_plain);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, name);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_FAV: {
        if (mStatus.is_favorite) {
            mService.destroyFavorite(mAccountId, mStatusId);
        } else {
            mService.createFavorite(mAccountId, mStatusId);
        }
        break;
    }
    case MENU_COPY_CLIPBOARD: {
        final String textToCopy = "@" + mStatus.screen_name + ": " + mStatus.text_plain;
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                    Context.CLIPBOARD_SERVICE);
            clipboard.setText(textToCopy);
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                    Context.CLIPBOARD_SERVICE);
            android.content.ClipData clip = android.content.ClipData.newPlainText("Status", textToCopy);
            clipboard.setPrimaryClip(clip);
        }
        Toast.makeText(getActivity(), R.string.text_copied, Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_DELETE: {
        mService.destroyStatus(mAccountId, mStatusId);
        break;
    }
    case MENU_EXTENSIONS: {
        final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_STATUS);
        final Bundle extras = new Bundle();
        extras.putParcelable(INTENT_KEY_STATUS, mStatus);
        intent.putExtras(extras);
        startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions)));
        break;
    }
    case MENU_MUTE_SOURCE: {
        final String source = HtmlEscapeHelper.unescape(mStatus.source);
        if (source == null)
            return false;
        final Uri uri = Filters.Sources.CONTENT_URI;
        final ContentValues values = new ContentValues();
        final SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE).edit();
        final ContentResolver resolver = getContentResolver();
        values.put(Filters.TEXT, source);
        resolver.delete(uri, Filters.TEXT + " = '" + source + "'", null);
        resolver.insert(uri, values);
        editor.putBoolean(PREFERENCE_KEY_ENABLE_FILTER, true).commit();
        Toast.makeText(getActivity(), getString(R.string.source_muted, source), Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_SET_COLOR: {
        final Intent intent = new Intent(INTENT_ACTION_SET_COLOR);
        startActivityForResult(intent, REQUEST_SET_COLOR);
        break;
    }
    case MENU_CLEAR_COLOR: {
        clearUserColor(getActivity(), mStatus.user_id);
        updateUserColor();
        break;
    }
    case MENU_RECENT_TWEETS: {
        openUserTimeline(getActivity(), mAccountId, mStatus.user_id, mStatus.screen_name);
        break;
    }
    case MENU_FIND_RETWEETS: {
        openUserRetweetedStatus(getActivity(), mStatus.account_id,
                mStatus.retweet_id > 0 ? mStatus.retweet_id : mStatus.status_id);
        break;
    }
    default:
        return false;
    }
    return super.onOptionsItemSelected(item);
}

From source file:org.mariotaku.twidere.fragment.UserProfileFragment.java

@Override
public boolean onMenuItemClick(final MenuItem item) {
    if (mUser == null || mTwitterWrapper == null)
        return false;
    switch (item.getItemId()) {
    case MENU_TAKE_PHOTO: {
        takePhoto();/* w  w w .  jav a  2s.co m*/
        break;
    }
    case MENU_ADD_IMAGE: {
        pickImage();
        break;
    }
    case MENU_BLOCK: {
        if (mTwitterWrapper == null || mFriendship == null) {
            break;
        }
        if (mFriendship.isSourceBlockingTarget()) {
            mTwitterWrapper.destroyBlock(mAccountId, mUser.user_id);
        } else {
            mTwitterWrapper.createBlockAsync(mAccountId, mUser.user_id);
        }
        break;
    }
    case MENU_REPORT_SPAM: {
        mTwitterWrapper.reportSpam(mAccountId, mUser.user_id);
        break;
    }
    case MENU_MUTE_USER: {
        final String screen_name = mUser.screen_name;
        final Uri uri = Filters.Users.CONTENT_URI;
        final ContentValues values = new ContentValues();
        final ContentResolver resolver = getContentResolver();
        values.put(Filters.Users.TEXT, screen_name);
        resolver.delete(uri, Filters.Users.TEXT + " = '" + screen_name + "'", null);
        resolver.insert(uri, values);
        Toast.makeText(getActivity(), R.string.user_muted, Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_MENTION: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        final String name = mUser.name;
        final String screen_name = mUser.screen_name;
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        bundle.putString(INTENT_KEY_TEXT, "@" + screen_name + " ");
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, name);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_SEND_DIRECT_MESSAGE: {
        final Uri.Builder builder = new Uri.Builder();
        builder.scheme(SCHEME_TWIDERE);
        builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION);
        builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(mAccountId));
        builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, String.valueOf(mUser.user_id));
        startActivity(new Intent(Intent.ACTION_VIEW, builder.build()));
        break;
    }
    case MENU_SET_COLOR: {
        final Intent intent = new Intent(getActivity(), SetColorActivity.class);
        startActivityForResult(intent, REQUEST_SET_COLOR);
        break;
    }
    case MENU_CLEAR_COLOR: {
        clearUserColor(getActivity(), mUserId);
        mProfileNameContainer.drawLeft(getUserColor(getActivity(), mUserId));
        break;
    }
    default: {
        if (item.getIntent() != null) {
            try {
                startActivity(item.getIntent());
            } catch (final ActivityNotFoundException e) {
                Log.w(LOGTAG, e);
                return false;
            }
        }
        break;
    }
    }
    return true;
}